Skip to content

input-admission gate counts replayed reasoning that the openai-chat adapter never sends, causing false context_length_exceeded refusals #5696

Closed

Description

@c040340

Client or integration

Codex App (Desktop), observed against cli_version: 0.155.0-alpha.16. Also reasoned about from source only (not client-specific): the bug is in the proxy's own pre-dispatch gate, so any client that sends a long Responses history should trigger it.

Area

Proxy and routing (input-admission gate), with a cross-cutting dependency on the openai-chat provider adapter's reasoning handling.

Summary

The pre-dispatch input-admission gate (src/server/responses/input-admission.ts, checkInputAdmission) estimates a turn's size by walking the whole replayed message history and counting every assistant thinking part (estimateInputTokens, the else if (part.type === "thinking") total += estimateTokens(part.thinking, modelId); branch). For an openai-chat provider whose model is not in provider.preserveReasoningContentModels, that same reasoning is unconditionally dropped a few steps later when the request is actually translated to the wire (src/adapters/openai-chat/messages.ts, assistant-message branch: reasoningContent is only attached to chatMsg when modelInList(provider.preserveReasoningContentModels, parsed.modelId) is true; otherwise the computed reasoningContent string is simply discarded).

So the gate's estimate and the actual outbound payload diverge by exactly the size of the replayed reasoning. At reasoning_effort: max on a long-running Codex thread, I've observed replayed reasoning make up 70–86% of the gate's estimate, i.e. the estimate runs 3–5x the real upstream input. Since the gate refuses at estimatedTokens > modelContextWindows[model] * ADMISSION_TOLERANCE (2.5x), this means a turn whose real input is well under both the model's real context window and OpenCodex's own 90%-of-window auto-compact point gets refused locally — the provider is never contacted — with a response.failed / context_length_exceeded event whose message ("The provider rejected this turn because its input exceeds the provider size or context limit...") reads as an upstream rejection even though it is a purely local, and in this case incorrect, refusal.

I hit this in production against a self-hosted openai-chat provider (configured modelContextWindows = 1,000,000, no preserveReasoningContentModels entry for the model) 7 times between 2026-09-16 and 2026-09-23. Refusals landed at real upstream input between ~365k and ~850k tokens — nowhere near the configured window — with the gate's own error message reporting estimates consistently around 2.48M–2.50M (i.e. right at 1,000,000 * 2.5). Replaying the exact failing request bodies offline through the installed package's own parseRequest + checkInputAdmission reproduces admitted:false; stripping only the reasoning items from the same bodies drops the estimate by 70–86%, landing in the same few-hundred-thousand-token range as the real upstream input OpenCodex itself had recorded for adjacent turns in that same thread.

Reproduction

This reproduces the gate's estimate/dispatch mismatch directly, without needing a reachable upstream — the interesting behavior (the refusal) happens before any provider I/O.

  1. Register any openai-chat provider with a small modelContextWindows for one model (a stub, unreachable baseUrl is fine — the gate runs before any request would be sent), e.g.:

    POST /api/providers
    {"name":"repro","provider":{"adapter":"openai-chat","baseUrl":"http://127.0.0.1:1/v1","apiKey":"x","authMode":"key","allowPrivateNetwork":true,"models":["demo-model"],"modelContextWindows":{"demo-model":100000}}}
    

    (window 100,000 → gate ceiling 250,000; demo-model doesn't match any of AGENT_MODEL_PREFIXES, so it uses the default 4 chars/token estimator.)

  2. Send a Responses turn whose only large item is a reasoning item — every other item is trivial:

    const body = {
      model: "repro/demo-model", store: false, stream: true,
      input: [
        {type: "message", role: "user", content: [{type: "input_text", text: "Refactor foo()."}]},
        {type: "reasoning", id: "rs_1", summary: [], content: [{type: "reasoning_text", text: "x".repeat(1200000)}]},
        {type: "function_call", call_id: "call_1", name: "shell", arguments: "{\"command\":[\"echo\",\"ok\"]}"},
        {type: "function_call_output", call_id: "call_1", output: "ok"},
        {type: "message", role: "user", content: [{type: "input_text", text: "Now summarize what you did."}]},
      ],
    };
    await fetch("http://127.0.0.1:10100/v1/responses", {
      method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(body),
    }).then(r => r.text()).then(console.log);
  3. Observed: HTTP 200 with an SSE stream ending in response.failed, code: "context_length_exceeded", message reporting an estimate north of 250,000 tokens — even though the real non-reasoning content here is a few hundred bytes, and demo-model is not in preserveReasoningContentModels, so an actual send would never have included the x-filled reasoning at all.

  4. Expected: the gate should admit this, since the request OpenCodex would actually transmit for this provider/model is tiny. Removing just the reasoning item and resending the same body confirms the gate's own estimate was the problem: with the stub baseUrl above (nothing listening on port 1) this now gets past the gate and fails downstream instead — an HTTP 502 with no SSE body at all, i.e. no context_length_exceeded — because OpenCodex proceeded to actually try to dial the upstream. Pointing baseUrl at a real (even minimally-implemented) openai-chat-compatible endpoint instead of a dead port makes this branch return a normal 200/response.completed.

Suggested fix

estimateInputTokens (and its combo-target counterpart checkComboTargetInputAdmission) should skip part.type === "thinking" content for a routed target whose adapter will not forward it — mirroring the exact modelInList(provider.preserveReasoningContentModels, modelId) check adapters/openai-chat/messages.ts already uses to decide whether to serialize it. Targets that do forward reasoning (Anthropic thinking blocks, preserve-listed openai-chat models, native Codex targets that replay raw Responses reasoning items) should keep counting it exactly as today — this is specifically about the openai-chat providers that unconditionally drop it.

Happy to open a PR against this if a maintainer wants a starting point; I have a working offline harness (runs parseRequest + checkInputAdmission directly against the installed package with bun, no network) that I used to confirm the bug mechanism above, though I have not yet tried the suggested fix itself against it.

Version

2.63.0 (also read through 2.64.0 source on GitHub; the relevant code is unchanged)

Operating system

Windows 11 24H2

Provider and model

openai-chat adapter, any model not listed in that provider's preserveReasoningContentModels (production case: a self-hosted DeepSeek-compatible endpoint, reasoning_effort: max)

Checks

  • I searched existing issues and documentation.
  • I removed secrets, tokens, account details, request credentials, and personal data.

Activity

  1. added
    bug
    streaming
    on Sep 23, 2026
  2. lidge-jun commented on Sep 24, 2026

    @lidge-jun
    Owner

    Fixed on dev by bundle #5738 (squash-merged as df61bce); it will ship in the next release. Closing manually because dev is not the default branch, so GitHub does not auto-close. If you still see this on a build that includes df61bce, please reopen with the version and a redacted reproduction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugstreaming

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions