Skip to content

Responses stream: a top-level error event is ignored and the turn is retried five times #61547

Open

Description

@HengYangDS

What version of Codex CLI is running?

codex-cli 0.169.0 (the latest release; codex-rs/codex-api on main at 65a5410 reads the same way)

What subscription do you have?

None for this report: a custom model provider with wire_api = "responses". The reproduction uses a local scripted provider.

Which model were you using?

Any. The reproduction names a placeholder model, probe-model.

What platform is your computer?

Darwin 27.2.0 arm64 arm

What terminal emulator and version are you using (if applicable)?

Not applicable: codex exec.

Codex doctor report

Not included. The reproduction runs in a new CODEX_HOME whose whole configuration is shown below.

What issue are you seeing?

A provider ends a Responses stream with the error event that the streaming reference documents, with code and message beside type:

event: response.created
event: response.in_progress
event: error
data: {"type": "error", "code": "validation_error", "message": "web search is not supported for this request", "param": "", "sequence_number": 2}

Codex does not act on the event. It reports the end of the stream as a disconnection and sends the same request six times in all:

Reconnecting... 1/5 (stream disconnected before completion: stream closed before response.completed)
…
Reconnecting... 5/5 (stream disconnected before completion: stream closed before response.completed)
stream disconnected before completion: stream closed before response.completed

The provider's code and message never reach the user, and a request that the provider refused as invalid is retried five times.

What steps can reproduce the bug?

  1. Save this as upstream.py and run python3 upstream.py 18961. It answers every POST with response.created, response.in_progress and one ending, ends the chunked body, and prints one line per request.
"""A scripted Responses provider. Usage: python3 upstream.py <port> [flat|nested|nested-known|failed]"""
import http.server, json, sys

PORT, SHAPE = int(sys.argv[1]), (sys.argv[2] if len(sys.argv) > 2 else "flat")
MESSAGE = "web search is not supported for this request"
RESPONSE = {"id": "resp_1", "object": "response", "status": "in_progress", "model": "probe-model", "output": []}
FAILED = RESPONSE | {"status": "failed", "error": {"code": "validation_error", "message": MESSAGE}}
ENDINGS = {
    "flat": {"type": "error", "code": "validation_error", "message": MESSAGE, "param": ""},
    "nested": {"type": "error", "error": {"code": "validation_error", "message": MESSAGE}},
    "nested-known": {"type": "error", "error": {"code": "context_length_exceeded", "message": MESSAGE}},
    "failed": {"type": "response.failed", "response": FAILED},
}
EVENTS = [
    {"type": "response.created", "response": RESPONSE},
    {"type": "response.in_progress", "response": RESPONSE},
    ENDINGS[SHAPE],
]


class Handler(http.server.BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def do_POST(self):
        self.rfile.read(int(self.headers.get("Content-Length") or 0))
        print("POST", self.path, flush=True)
        self.send_response(200)
        self.send_header("Content-Type", "text/event-stream")
        self.send_header("Transfer-Encoding", "chunked")
        self.end_headers()
        for number, event in enumerate(EVENTS):
            body = json.dumps(event | {"sequence_number": number})
            data = f"event: {event['type']}\ndata: {body}\n\n".encode()
            self.wfile.write(b"%x\r\n%s\r\n" % (len(data), data))
        self.wfile.write(b"0\r\n\r\n")

    def log_message(self, *args):
        pass


http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
  1. In a new directory, write config.toml:
model = "probe-model"
model_provider = "probe"

[model_providers.probe]
name = "probe"
base_url = "http://127.0.0.1:18961/v1"
wire_api = "responses"
  1. Run one turn with that directory as CODEX_HOME:
CODEX_HOME=<that directory> codex exec --skip-git-repo-check --json -c features.memories=false "Reply with the word ready."

Result: the server prints six POST /v1/responses lines, Codex prints five Reconnecting... events, and the turn fails with exit status 1.

The second argument of the script selects other endings. Measured with the same command:

The stream ends with Requests Codex's last message
flat: error, code validation_error beside type 6 stream closed before response.completed
nested: error, code validation_error in an error member 6 stream closed before response.completed
nested-known: error, code context_length_exceeded in an error member 1 Codex ran out of room in the model's context window. …
failed: response.failed, code validation_error in response.error 6 stream disconnected before completion: web search is not supported for this request

What is the expected behavior?

An error event that carries code and message beside type ends the turn with that code and message, as nested-known does today for a nested, known code. A refusal such as a validation error is shown to the user and not retried five times.

Additional information

Where the event is read, at the tag rust-v0.169.0:

  • process_responses_event in codex-rs/codex-api/src/sse/responses.rs handles "error" with parse_terminal_provider_error(event.error.as_ref(), None). ResponsesStreamEvent has an error member and no top-level code or message, so the documented shape yields nothing.
  • parse_terminal_provider_error in codex-rs/codex-api/src/error.rs returns an error only for a fixed list of codes. Any other code falls through, and the end of the stream then reads as "stream closed before response.completed", which is retried.

Where it was met: a third-party Responses provider refuses a request that carries a web_search tool for a model without web search, with the event above. With features.memories on, a new Codex home starts a memory import thread whose request carries that tool, so each such thread costs six refused requests beside the turn that the user asked for.

Follow-up, 15 November 2026

Thanks @r266-tech for running the additional cases. Their 0.169.0 binary results, with retries disabled, show:

After response.failed(validation_error) Result
EOF Original provider error, exit 1
Held-open stream Idle timeout replaces the provider error
response.completed False success, exit 0

These are scripted cases, not evidence of the same event sequence in production. The held-open failure is already tracked in #43140.

I rechecked current main at ee344ca9. The parser still saves unclassified failures for EOF; timeout and completion bypass that saved error. The flat error decoding gap in this report also remains.

Acceptance should cover both: expose the documented flat error's code/message and avoid retrying an invalid request; end a response immediately on response.failed so timeout or later completion cannot replace it. The outer request retry policy must retain genuine transient retries. The existing success and recognized-error controls should remain unchanged. I have not rerun the binary here.

Native stream test follow-up, 15 November 2026

Thanks @r266-tech for the native regression tests. They report five failures on main ee344ca9 and 214 passing library tests after terminating the stream on the decoded response.failed event. The checks cover held-open bodies, later completion, transport errors and malformed failure fields; completion-first and transient retry controls still pass.

That gives maintainers a tested fix for the terminality part of #43140. The two gaps in this report remain: decode the documented flat error, and stop retrying a request refused as invalid. I rechecked the same main source; I have not run their tests or built the CLI. Their library result does not establish production recovery.

Activity

  1. added
    bug
    CLI
    custom-model
    connectivity
    on Nov 14, 2026
  2. Nakagawa-master commented on Nov 14, 2026

    @Nakagawa-master

    A second acceptance boundary is visible in current Codex source (source review only; I have not run the reporter's Codex fixture).

    The report correctly separates the documented flat error shape from nested response.failed. Fixing only the flat JSON decoding would still leave the retry classification problem:

    1. In ResponsesStreamEvent, the "error" branch passes event.error only. The top-level code/message fields in the reported official event are not represented, so that event is currently ignored.
    2. In parse_terminal_provider_error, an unfamiliar validation_error returns None; the response.failed fallback instead maps an unclassified error to ApiError::Retryable (current responses_error.rs:100-103). A successful flat-shape parse alone therefore need not prevent the repeated POSTs.
    3. A separate source-predicted failure of the same terminality boundary: process_sse stores non-whitelisted errors in response_error for EOF, but emits ResponseEvent::Completed immediately if a later response.completed arrives. A stream with response.failed(validation_error) followed by response.completed can therefore appear successful rather than failed. I have not reproduced this exact sequence with the binary; it follows from the current branches.

    A focused regression matrix could run the existing scripted provider's flat and nested validation_error cases and assert one POST + visible provider message, then feed response.failed(validation_error) -> response.completed and assert error wins, no Completed. Opposite controls: a known deliberate retryable condition such as rate_limit_exceeded retains its configured retry behavior; ordinary transport disconnects remain distinguishable from explicit provider rejection; a genuinely successful stream still completes. Existing terminal_failure_with_retry_header_ends_stream_immediately tests only a recognized set of terminal codes, so it does not exercise the unrecognized-code branch.

    The implementation choice is to normalize both documented error shapes and classify an explicit provider-declared terminal failure separately from a transport disconnect; treating every unknown error as a retryable disconnect is what the two boundaries have in common. This is a source-based proposed test and classification, not a claim of running the integration suite.

  3. r266-tech commented on Nov 14, 2026

    @r266-tech

    I ran the failed-then-completed case from the preceding comment against the released codex-cli 0.169.0 on macOS arm64. It does report success. This is also related to the already-tested terminality defect in #43140; I am not claiming a new underlying bug.

    Using a scripted loopback Responses provider, isolated CODEX_HOME, no credentials, stream_max_retries=0, and stream_idle_timeout_ms=500:

    Events after response.created Exit Final CLI event / diagnostic
    ordinary response.completed 0 turn.completed
    response.failed(validation_error) → EOF 1 turn.failed, original fixture message preserved
    same failure → response.completed 0 turn.completed; failure message absent
    same failure → held-open stream 1 idle timeout waiting for SSE; failure message absent
    response.failed(context_length_exceeded) → response.completed 1 context-window error; no turn.completed

    For the success-after-failure row, append this event after the reporter's existing failed ending, then end the chunked body:

    event: response.completed
    data: {"type":"response.completed","response":{"id":"resp_1","object":"response","model":"probe-model","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":0,"total_tokens":1}}}
    
    

    For the held-open row, send only the failure, flush, and leave the chunked body unfinished beyond the configured idle timeout. These are deliberately scripted transport cases: the two-terminal-events sequence is inconsistent provider output, not evidence that a production provider emits it.

    The current source at 81b995a6c9a4c978f399775cfa5ce50702368749 still stores unhandled errors, returns a new error on idle timeout, and emits a later completion without consulting that saved error. The relevant control flow also exists in the release source.

    AI-only offline verification: 16 shape/EOF/completion/hold-open cases, one unauthenticated localhost POST each; no model service requests, current-main build, or production-incident attribution. This turns the earlier source prediction into an executable release-level observation; #43140 already describes the broader immediate-terminal-failure requirement.

  4. r266-tech commented on Nov 15, 2026

    @r266-tech

    I checked the event-kind boundary already proposed in #43140 against current main ee344ca9458351a6ea102795fa73110ad3ede5dc, using native spawn_response_stream tests rather than only the error parser.

    After response.failed(validation_error) Unmodified main Narrow local event-kind change
    EOF Original provider message Same
    Held-open body No error before a 1s virtual test deadline (idle timeout: 60s) Original provider error, stream closes
    Later response.completed Emits Completed Original provider error; no Completed
    Later transport error Original provider error is lost Original provider error preserved

    The new native fixture has 3 passes / 5 failures on unmodified main; all 206 existing library tests pass. Including event.kind == "response.failed" in the existing send-error-and-return condition gives 214 passes / 0 failures. A decoded failed event with malformed error fields also terminates with response.failed event received. Completion-first and ordinary transport-error controls stay unchanged.

    The transient controls pass through map_api_error: both rate_limit_exceeded and server_is_overloaded retain Retry-After: 3 and retry_delay(1) == Some(3s). This tests stream termination separately from request retry policy. validation_error still has its current retryable classification; the documented flat error shape and invalid-request retry suppression remain unresolved.

    Rust 1.99.1, macOS arm64. I reduced the local workspace to this crate's path-dependency closure to avoid unrelated V8 fetches; every selected package's version/source/checksum matches the upstream lock. These are native library checks, not a current-main CLI build or production-provider verification. AI-assisted local verification; no model/provider calls.

    Native regression fixture and commands

    Add this test module beside error_tests in codex-rs/codex-api/src/sse/responses.rs:

    #[cfg(test)]
    #[path = "responses_terminal_tests.rs"]
    mod terminal_tests;

    Save the following as codex-rs/codex-api/src/sse/responses_terminal_tests.rs:

    //! Explicit response termination and request retry policy are separate boundaries.
    
    use super::spawn_response_stream;
    use crate::api_bridge::map_api_error;
    use crate::common::ResponseEvent;
    use crate::common::ResponseStream;
    use crate::error::ApiError;
    use bytes::Bytes;
    use codex_client::ByteStream;
    use codex_client::StreamResponse;
    use codex_client::TransportError;
    use codex_http_client::RetryAfter;
    use codex_protocol::protocol::CodexErrorInfo;
    use futures::StreamExt;
    use futures::stream;
    use http::HeaderMap;
    use http::StatusCode;
    use serde_json::Value;
    use serde_json::json;
    use std::time::Duration;
    use tokio::time::timeout;
    
    enum Ending {
        Eof,
        HeldOpen,
        TransportError,
    }
    
    fn response_stream(events: &[Value], ending: Ending) -> ResponseStream {
        let body = events
            .iter()
            .map(|event| format!("data: {event}\n\n"))
            .collect::<String>();
        let mut chunks = vec![Ok(Bytes::from(body))];
        if matches!(ending, Ending::TransportError) {
            chunks.push(Err(TransportError::Network(
                "later connection reset".into(),
            )));
        }
        let bytes: ByteStream = if matches!(ending, Ending::HeldOpen) {
            Box::pin(stream::iter(chunks).chain(stream::pending()))
        } else {
            Box::pin(stream::iter(chunks))
        };
        spawn_response_stream(
            StreamResponse {
                status: StatusCode::OK,
                headers: HeaderMap::new(),
                bytes,
            },
            Duration::from_secs(60),
            None,
            None,
        )
    }
    
    fn failed() -> Value {
        json!({"type": "response.failed", "response": {"error": {
            "code": "validation_error", "message": "provider rejected this request"
        }}})
    }
    
    fn completed() -> Value {
        json!({"type": "response.completed", "response": {"id": "resp_test"}})
    }
    
    async fn expect_failure(mut stream: ResponseStream) -> ApiError {
        let event = timeout(Duration::from_secs(1), next_response_event(&mut stream))
            .await
            .expect("response.failed waited for EOF or the 60-second idle timeout");
        let error = match event {
            Some(Err(error)) => error,
            other => panic!("expected the provider failure, got {other:?}"),
        };
        assert!(
            timeout(Duration::from_secs(1), stream.next())
                .await
                .expect("failed response stream did not close")
                .is_none()
        );
        error
    }
    
    async fn next_response_event(
        stream: &mut ResponseStream,
    ) -> Option<Result<ResponseEvent, ApiError>> {
        loop {
            match stream.next().await {
                Some(Ok(ResponseEvent::RateLimits(_))) => {}
                event => return event,
            }
        }
    }
    
    fn assert_provider_failure(error: ApiError) {
        assert!(matches!(
            error,
            ApiError::Retryable { message, retry_after: None }
                if message == "provider rejected this request"
        ));
    }
    
    #[tokio::test(start_paused = true)]
    async fn failed_response_eof_preserves_provider_message() {
        assert_provider_failure(expect_failure(response_stream(&[failed()], Ending::Eof)).await);
    }
    
    #[tokio::test(start_paused = true)]
    async fn failed_response_held_open_ends_before_idle_timeout() {
        assert_provider_failure(expect_failure(response_stream(&[failed()], Ending::HeldOpen)).await);
    }
    
    #[tokio::test(start_paused = true)]
    async fn failed_response_stops_before_later_completion() {
        assert_provider_failure(
            expect_failure(response_stream(&[failed(), completed()], Ending::HeldOpen)).await,
        );
    }
    
    #[tokio::test(start_paused = true)]
    async fn failed_response_stops_before_transport_error() {
        assert_provider_failure(
            expect_failure(response_stream(&[failed()], Ending::TransportError)).await,
        );
    }
    
    #[tokio::test(start_paused = true)]
    async fn failed_response_preserves_transient_retry_policy() {
        for (code, expected_code) in [
            ("rate_limit_exceeded", CodexErrorInfo::RateLimitExceeded),
            ("server_is_overloaded", CodexErrorInfo::ServerOverloaded),
        ] {
            let failure = json!({"type": "response.failed", "response": {"error": {
                "code": code, "message": "Try again in 35 seconds.",
                "headers": {"Retry-After": "3"}
            }}});
            let error =
                map_api_error(expect_failure(response_stream(&[failure], Ending::HeldOpen)).await);
            assert_eq!(error.to_codex_protocol_error(), expected_code);
            assert_eq!(
                error.retry_after(),
                RetryAfter::from_delay(Duration::from_secs(3))
            );
            assert_eq!(error.retry_delay(1), Some(Duration::from_secs(3)));
        }
    }
    
    #[tokio::test(start_paused = true)]
    async fn failed_response_malformed_payload_is_an_immediate_stream_error() {
        let failure = json!({"type": "response.failed", "response": {"error": {"code": 42}}});
        let error = expect_failure(response_stream(&[failure], Ending::HeldOpen)).await;
        assert!(
            matches!(error, ApiError::Stream(message) if message == "response.failed event received")
        );
    }
    
    #[tokio::test(start_paused = true)]
    async fn completed_response_is_the_first_terminal_outcome() {
        let mut stream = response_stream(&[completed(), failed()], Ending::HeldOpen);
        assert!(matches!(
            next_response_event(&mut stream).await,
            Some(Ok(ResponseEvent::Completed { .. }))
        ));
        assert!(stream.next().await.is_none());
    }
    
    #[tokio::test(start_paused = true)]
    async fn disconnect_without_failed_response_preserves_transport_error() {
        let error = expect_failure(response_stream(&[], Ending::TransportError)).await;
        assert!(
            matches!(error, ApiError::Stream(message) if message.contains("later connection reset"))
        );
    }

    From codex-rs, the focused baseline command is:

    cargo +1.99.1 test --locked --profile dev-small -p codex-api --lib terminal_tests -- --nocapture

    After the local event-kind change, the full library command is:

    cargo +1.99.1 test --locked --profile dev-small -p codex-api --lib
  5. Thalrion commented on Nov 21, 2026

    @Thalrion

    A loopback-only regression check on Linux x86_64 narrows the release boundary for a policy-error variant of this issue. The fixture returns HTTP 200 with Content-Type: text/event-stream, sends event: error with {"type":"error","sequence_number":0,"error":{"code":"cyber_policy","type":"invalid_request","message":"Synthetic terminal policy refusal"}}, and closes. request_max_retries = 0, stream_max_retries = 2, empty CODEX_HOME, no credentials or external inference.

    • 0.156.1 and stable 0.171.0: 3 POSTs (initial + 2 retries), terminal stream closed before response.completed rather than the refusal.
    • 0.173.0-alpha.4: 1 POST, process exits nonzero and reports the synthetic policy refusal.
    • On all three versions, response.failed with the same error and ordinary HTTP 400 stop after one POST; an empty SSE stream still retries.

    This is consistent with the terminal handling in #62354 / #62356. No change to policy enforcement is requested. Please retain this statusless nested-error case in stable-release coverage; the released stable client still treats it like a disconnect.

  6. HengYangDS commented on Nov 25, 2026

    @HengYangDS
    Author

    Thanks for the release comparison. I checked the current stable tag, rust-v0.172.0. It includes #62356. The tagged decoder still has a nested error field, and the event handler still reads that field for an error event. The documented flat event from the opening report therefore still lacks a decoding path in this source. I have not run a new CLI reproduction for this tag.

    Please keep the original acceptance case alongside the nested-event coverage. A flat provider validation error should surface its original message and end the turn without retries. A genuinely transient response should retain its retry behavior.

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

    CLIbugconnectivitycustom-model

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions