{"record":{"id":"94e2402dcf6b76c8","repo":"unslothai/unsloth","slug":"chatgpt-returned-a-malformed-stream","errorCode":null,"errorMessage":"ChatGPT returned a malformed stream.","messagePattern":"ChatGPT returned a malformed stream\\.","errorType":"exception","errorClass":"CodexTransportError","httpStatus":null,"severity":"error","filePath":"studio/backend/core/inference/openai_codex_client.py","lineNumber":577,"sourceCode":"                    async for line in response.aiter_lines():\n                        if cancel_event is not None and cancel_event.is_set():\n                            return\n                        if not line:\n                            event_name = \"\"\n                            continue\n                        if line.startswith(\"event:\"):\n                            event_name = line[6:].strip()\n                            continue\n                        if not line.startswith(\"data:\"):\n                            continue\n                        raw = line[5:].strip()\n                        if raw == \"[DONE]\":\n                            break\n                        try:\n                            event = json.loads(raw)\n                            kind = response_event_type(event, event_name)\n                        except (ValueError, json.JSONDecodeError) as exc:\n                            raise CodexTransportError(\n                                \"ChatGPT returned a malformed stream.\"\n                            ) from exc\n                        if kind in (\"response.created\", \"response.in_progress\"):\n                            continue\n                        if kind in (\"response.output_text.delta\", \"response.refusal.delta\"):\n                            delta = event.get(\"delta\")\n                            if not isinstance(delta, str):\n                                raise CodexTransportError(\"ChatGPT returned a malformed stream.\")\n                            yield _chunk(completion_id, model, {\"content\": delta})\n                        elif kind in (\n                            \"response.reasoning_summary_text.delta\",\n                            \"response.reasoning_text.delta\",\n                        ):\n                            delta = event.get(\"delta\")\n                            if isinstance(delta, str):\n                                yield _chunk(completion_id, model, {\"reasoning_content\": delta})\n                        elif kind == \"response.output_item.added\":\n                            item = event.get(\"item\")","sourceCodeStart":559,"sourceCodeEnd":595,"githubUrl":"https://github.com/unslothai/unsloth/blob/203007d19051dcd2ae33876786d117c99f6b0368/studio/backend/core/inference/openai_codex_client.py#L559-L595","documentation":"Raised while parsing the SSE stream from the Codex responses endpoint: a 'data:' line's payload failed json.loads or produced an event whose type could not be classified by response_event_type. The upstream contract (each data line is a JSON event) was violated mid-stream.","triggerScenarios":"A data: line containing invalid JSON (truncated by a proxy, injected HTML error page, partial chunk), or a JSON body whose shape response_event_type cannot map to a known kind, or [DONE] not terminating cleanly.","commonSituations":"Intercepting proxy or buffer that truncates long SSE lines; upstream briefly emitting a malformed keep-alive; API contract change adding an event shape the parser does not recognize; proxy injecting a 502 HTML page into the stream.","solutions":["Retry the generation — single malformed events are usually transient","Capture the raw line that failed (add logging of `raw` before the raise) to identify whether it is HTML/truncation","If reproducible for a specific request, reduce response size or check proxy buffering settings","Update the parser if OpenAI added a new event kind (version change)"],"exampleFix":null,"handlingStrategy":"retry","validationCode":null,"typeGuard":null,"tryCatchPattern":"try:\n    collect(stream)\nexcept CodexTransportError as exc:\n    if 'malformed stream' in str(exc):\n        result = collect(await client.stream(request))  # one retry, no partial reuse\n    else:\n        raise","preventionTips":["Disable proxy body rewriting/buffering for SSE endpoints","Log the raw data line on parse failure to distinguish truncation from schema change","Pin expectations to the documented event set and add tests with fixtures of real streams"],"tags":["sse","streaming","codex","json","parsing"],"backgroundTag":null,"analyzedSha":"203007d19051dcd2ae33876786d117c99f6b0368","analyzedAt":"2026-08-15T02:48:39.846Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}