Fix Codex "Stream Disconnected Before Completion" Errors

Zivv••36 min read
On this page
  1. What the Error Means
  2. Read the Reason After the Colon
  3. Causes and Fixes at a Glance
  4. Step 1: Confirm Which Provider Codex Is Using
  5. Step 2: Test Responses Streaming with curl
  6. Step 3: Fix the Cause
  7. Telling Codex Errors Apart
  8. Using Codex Through Zivv
  9. Prevention Checklist
  10. FAQ

In OpenAI's Codex CLI the error typically reads:

stream disconnected before completion: upstream request failed

Before it appears you will usually see a few Reconnecting... 1/5, Reconnecting... 2/5 notices. This guide is for anyone running Codex against OpenAI or an OpenAI-compatible provider who keeps hitting this message halfway through longer tasks. If you are seeing 401 Unauthorized instead, that is an authentication problem covered in the 401 Unauthorized guide; if a GPT endpoint returns a plain 502, see the 502 Bad Gateway guide.

What the Error Means

Codex talks to models through OpenAI's Responses API (/v1/responses) and always consumes it as a stream: the server sends HTTP headers, then a sequence of events such as response.created and response.output_text.delta, and closes with response.completed. The Responses API vs Chat Completions comparison explains how that differs from the older endpoint.

The Codex source defines this error precisely: the HTTP handshake succeeded, but the stream disconnected or reported an error before response.completed. That rules several things out right away:

  • Your key is fine; a bad key fails the handshake with a 401
  • The URL and model name are fine; those normally fail with a 404
  • The failure happened after the stream started and before it finished

Codex treats this as a transient failure and retries the turn automatically, up to stream_max_retries times as set on the provider (5 by default). The Reconnecting... n/5 notices are those retries. By the time the error shows up, the problem has happened several times in a row.

Read the Reason After the Colon

The text after the colon is where the diagnosis starts. Based on the Codex source, the common ones are:

After the colonWhat it meansLook at first
upstream request failed or another one-line messageThe server sent a failure event (response.failed or error) and wrote this messageThe relay or gateway you connect to, and its upstream
stream closed before response.completedThe connection closed cleanly but the completion event never came; the stream was truncatedGateway, proxies, network
idle timeout waiting for SSENo events for stream_idle_timeout_ms (5 minutes by default)A stuck upstream, or a layer swallowing data
Incomplete response returned, reason: content_filterA content filter stopped the outputThe request content
A network error description (connection reset and the like)The transport droppedLocal network, proxies, VPN

upstream request failed is not text Codex generates; it comes from the failure event the server sent. Relays and gateways commonly use that wording when their own request to the model provider fails. Read it literally: the hop between you and the gateway works, the hop between the gateway and its upstream does not.

Causes and Fixes at a Glance

CauseTypical signsFix
The gateway's upstream failed mid-stream (rate limit, overload, account trouble, 5xx)upstream request failed, intermittent, fine an hour laterWait and retry; check the gateway's status and usage logs; switch model or group
The provider lacks full Responses API supportFails immediately, or always on the same kind of step (tool calls, long reasoning)Confirm /v1/responses streaming with curl; use a provider that supports Responses
A local proxy, VPN or office network kills long connectionsstream closed before response.completed or network errors; fine on another networkCompare with proxies removed; set NO_PROXY
An intermediary's idle timeout or bufferingBreaks after a consistent duration, worse on long reasoningDisable buffering and raise read timeouts on your proxy
Codex's own idle timeoutidle timeout waiting for SSERaise stream_idle_timeout_ms and find out why nothing arrived for so long
An oversized sessionFrequent late in long sessions/compact, or /new for a fresh session

Step 1: Confirm Which Provider Codex Is Using

Codex reads its provider settings from ~/.codex/config.toml. For an OpenAI-compatible service, define an explicit model_providers entry. For Zivv it looks like this:

model_provider = "zivv"
model = "gpt-6.1-sol"

[model_providers.zivv]
name = "zivv"
base_url = "https://zivv.pro/v1"
env_key = "ZIVV_API_KEY"
wire_api = "responses"

Then set the key in the same terminal you start Codex from:

export ZIVV_API_KEY=sk-your-key
echo $ZIVV_API_KEY | cut -c1-6     # print only the prefix to confirm it is set
codex

Check three things:

  • base_url includes /v1, and model_provider names the entry you defined
  • wire_api is "responses". Current Codex releases no longer accept wire_api = "chat"; that value fails at startup with a message telling you to switch to responses, so your provider must support the Responses API
  • Inside Codex, run /status to see the current session configuration and confirm the provider and model are the ones you expect

The full setup walkthrough is in connecting Codex to an OpenAI-compatible gateway.

Step 2: Test Responses Streaming with curl

Bypass Codex and send a streaming Responses request straight to the provider. -N disables curl's output buffering:

curl -N https://zivv.pro/v1/responses \
  -H "Authorization: Bearer $ZIVV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-6.1-sol","stream":true,"input":"Count from 1 to 30, one number per line"}'

A healthy stream starts with response.created, continues with response.output_text.delta lines and ends with response.completed. Interpret the result:

curl resultMeaningNext move
Events arrive line by line and end with response.completedThe provider and this network path are fineThe issue is in Codex's environment or only shows on long tasks; go to step 3
A response.failed event with an error objectThe server explicitly reported a failureRead its code and message; it is a gateway or upstream problem
The stream stops without response.completedSomething truncated itRetest without proxies, check any self-hosted proxy
Long pause, then all events at onceSomething in the path is bufferingTurn buffering off in that layer
404No /v1/responses on the provider, or a wrong URL or model nameSee 404 model not found
401The key is wrongSee the 401 guide
403 this channel requires a specific clientThis key's group only accepts a specific clientThe path works; test with codex exec "Count from 1 to 30" instead

If curl succeeds consistently while Codex keeps failing, the cause is almost certainly a proxy or network issue where Codex runs, or something specific to long tasks.

Step 3: Fix the Cause

upstream request failed: The Gateway's Upstream Broke

This is the most common variant. Your request reached the gateway, and the gateway's call to the model failed, whether from an upstream rate limit, overload, an account problem or a 5xx. What to do:

  • Wait before retrying. Codex already retried five times, so the upstream problem has lasted a while; hammering it again right away rarely helps
  • Check the gateway's status page or usage logs to see whether failures cluster on one model or time window
  • Switch models for now, for example from gpt-6.1-sol to gpt-6.2-sol or gpt-6.1-terra, or move to another group
  • During shaky periods, raise stream_max_retries (below) so Codex rides out more blips

Partial Responses Support on the Provider

Codex speaks only the Responses protocol. Some providers support only Chat Completions, or translate Responses into another protocol inside their gateway, which can break mid-stream on richer content such as reasoning items or tool calls. To check:

  • Run the step 2 curl and confirm /v1/responses streaming reliably reaches response.completed
  • Notice whether failures always hit the same kind of step (every tool call, say) while simple prompts work
  • Run Codex on a GPT-family model first to rule out protocol translation, then try other models

Network, Proxies and Timeouts

When curl works from a clean environment but Codex keeps dropping, compare with the proxy variables removed:

env -u HTTPS_PROXY -u HTTP_PROXY -u ALL_PROXY \
    -u https_proxy -u http_proxy -u all_proxy \
    codex exec "Count from 1 to 30"

If that fixes it, send only the API host direct:

export NO_PROXY=zivv.pro

Corporate proxies that decrypt TLS, VPNs in global mode switching nodes, and WSL or containers with proxy variables that differ from the host can all cut long connections midway. If you run your own nginx between Codex and the provider, turn off proxy_buffering for /v1/responses and set proxy_read_timeout above the model's longest silence (nginx defaults to 60 seconds). The complete configuration is in AI API streaming with SSE.

Tune Codex's Retries and Idle Timeout

A Codex provider entry accepts three optional network settings (field names as defined in the Codex source and the official configuration reference):

[model_providers.zivv]
name = "zivv"
base_url = "https://zivv.pro/v1"
env_key = "ZIVV_API_KEY"
wire_api = "responses"
stream_max_retries = 10          # reconnect attempts after a dropped stream, default 5
stream_idle_timeout_ms = 600000  # silence before a stream counts as lost, default 300000 (5 min)
request_max_retries = 4          # retries when the HTTP request itself fails, default 4

Both retry counts are capped at 100. They solve different problems:

  • stream_max_retries helps with intermittent upstream failures by absorbing more of them
  • stream_idle_timeout_ms only matters when the reason is idle timeout waiting for SSE. If a layer in the middle cuts the connection first, raising Codex's value changes nothing
  • More retries mean longer waits on failure and the same request sent again. Do not use them to paper over a persistent fault

Keep Sessions Lean

In a long session every turn carries more history, so the model takes longer before it emits anything and the connection idles longer. Run /compact when responses slow down and /new when you switch tasks. Splitting a big job into steps that finish in a few minutes is far more reliable than a half-hour single run, the same idea as the task splitting in 529 overloaded and timeout fixes.

Telling Codex Errors Apart

ErrorWhen it happensWhere to look
unexpected status 401 UnauthorizedAt the handshake; the key was rejected401 Unauthorized guide
404, model not foundAt the handshake; URL or model does not exist404 model not found
429At the handshake; rate or quota limit429 Too Many Requests
502, 503 and other gateway errorsAt the handshake; the gateway got no valid upstream response502 Bad Gateway guide
stream disconnected before completion: ...After the stream started, before it completedThis guide

The first four fail as soon as the request goes out; this one fails after streaming has begun. Keeping that distinction in mind saves you from rechecking keys and URLs that already work.

Using Codex Through Zivv

If Codex points at Zivv, this is what the gateway does with Responses streams, based on the code:

  • No buffering on `/v1/responses`. The reverse proxy disables buffering on this path and allows reads of up to an hour; both HTTP streaming and WebSocket mode are supported
  • Keepalives during upstream silence. While the upstream has not started writing or pauses mid-stream, Zivv writes a : keepalive comment line every 15 seconds so intermediaries do not recycle the connection as idle
  • Failures before the first content are rerouted. If the upstream sends response.failed before any content, and the problem is not with the request itself, Zivv holds those events back from Codex and retries on another channel. When that succeeds, Codex never notices
  • Failures after output has started are passed on as they are. At that point bytes have already gone out and cannot be recalled. Request-level problems such as context_length_exceeded, and capacity problems such as rate limits and overload, keep their standard codes so Codex can decide whether to compact, wait or stop; other upstream faults are reported as server_error with the message upstream service error, please retry later
  • Failed and truncated streams are not billed. A stream that reports failure, or ends before its completion event, is recorded as failed and not charged

The console's usage logs show each request's status code, duration, time to first token (TTFT) and request ID, which also comes back in the X-Request-ID response header. Find the request by the time of the error and you can tell whether it failed upstream (a 5xx-class status) or on the client side (499, meaning Codex, a local proxy or the network closed the connection first).

Prevention Checklist

  • Define an explicit model_provider entry with wire_api = "responses" in ~/.codex/config.toml instead of relying on exported variables
  • After switching providers or models, run the step 2 curl before starting real work
  • Route the API host direct or via split routing, away from TLS inspection and global proxies
  • /compact long sessions regularly and split large tasks
  • Give each team member their own key so problems show up per key in the usage logs; see team API key and budget best practices

If you do not have a key yet, sign up for Zivv. One key covers both Codex and Claude Code, and the dashboard shows the model, status and cost of every request.

FAQ

How is "stream disconnected before completion" different from a 401?

A 401 happens at the handshake: the server rejected the key, and Codex reports unexpected status 401 Unauthorized (see the 401 guide). stream disconnected before completion means the handshake succeeded and the key is valid; the failure came after the stream started. Skip the key checks and look at the gateway, its upstream and the network.

Codex already retries automatically. Why do I still get the error?

By default Codex retries a dropped stream 5 times (stream_max_retries); the Reconnecting... n/5 notices are those attempts. When the error appears, all five failed, so the problem lasted at least tens of seconds. That usually means a persistently unstable upstream or a layer that reliably cuts the connection. Brief blips tend to recover during the retries and never surface as an error.

Will raising stream_idle_timeout_ms fix it?

Only when the reason after the colon is idle timeout waiting for SSE, because that setting controls how long Codex itself waits without events before giving up. If the reason is upstream request failed, stream closed before response.completed or a network error, the fault is in the gateway, its upstream or an intermediary, and a longer idle timeout does nothing.

Am I charged for a stream that disconnected?

That depends on the provider's billing rules. On Zivv, a stream that reports failure or ends before its completion event is recorded as failed and not charged. If the client side disconnected first (status 499 in the usage logs), the input the upstream already processed and any output already delivered are billed. Each automatic retry by Codex is a separate request with its own record.

Can I switch Codex to Chat Completions to avoid this?

No. Current Codex releases have removed wire_api = "chat" and talk only over the Responses API, so your provider must support streaming on /v1/responses. If a provider only offers Chat Completions, use one that supports Responses; on Zivv, GPT-family models are available at https://zivv.pro/v1/responses.