Skip to content

fix(openai): end streaming at terminal event instead of waiting for u… - #6473

Merged
Wei-Shaw merged 2 commits into
Wei-Shaw:mainfrom
cxx-cod:pr/openai-stream-terminal-eof
Sep 22, 2026
Merged

Wei-Shaw merged 2 commits into
Wei-Shaw:mainfrom
cxx-cod:pr/openai-stream-terminal-eof

Conversation

@cxx-cod

@cxx-cod cxx-cod commented Sep 1, 2026

Copy link
Copy Markdown
 ### Problem                                                                                                                                                                                                                             
                                                                                                                                                                                                                                         
 When relaying a streaming OpenAI Responses request, the gateway treats                                                                                                                                                                  
 upstream connection EOF as the only normal end-of-stream condition.                                                                                                                                                                     
 `response.completed` (and `[DONE]`) only set an internal flag                                                                                                                                                                           
 (`sawTerminalEvent`); the read loop keeps waiting for the upstream to                                                                                                                                                                   
 close the connection.                                                                                                                                                                                                                   
                                                                                                                                                                                                                                         
 The gateway's upstream transport enables keep-alive / HTTP/2 connection                                                                                                                                                                 
 reuse (`backend/internal/repository/http_upstream.go`,                                                                                                                                                                                  
 `buildUpstreamTransport`). On such reused connections, some upstreams                                                                                                                                                                   
 (relays/reverse proxies in particular) do not close the stream promptly                                                                                                                                                                 
 after the terminal event. Observed in production with packet captures:                                                                                                                                                                  
                                                                                                                                                                                                                                         
 - Upstream sends `response.completed` at ~T+500ms; the response body is                                                                                                                                                                 
   fully delivered.                                                                                                                                                                                                                      
 - The gateway then emits SSE keepalive comments (`:` every                                                                                                                                                                              
   `gateway.stream_keepalive_interval`, default 10s) to the downstream                                                                                                                                                                   
   client for another **8–46s (non-deterministic)** until the upstream                                                                                                                                                                   
   finally closes the connection.                                                                                                                                                                                                        
 - Direct connection to the same upstream (single-use connection) EOFs                                                                                                                                                                   
   immediately after `response.completed`, so the delay only appears                                                                                                                                                                     
   behind the gateway.                                                                                                                                                                                                                   
                                                                                                                                                                                                                                         
 Impact per streaming request: 8–46s of dead time added to total latency,                                                                                                                                                                
 while holding the upstream connection, downstream connection, goroutine,                                                                                                                                                                
 and the account concurrency slot. Clients that treat stream close as                                                                                                                                                                    
 completion (scripts, agents, tool-call chains) see the full delay, and                                                                                                                                                                  
 clients with read timeouts may misjudge a successful request as failed                                                                                                                                                                  
 and retry. Billing is unaffected (usage is parsed from the terminal                                                                                                                                                                     
 event), but throughput under concurrency is eroded by the piled-up                                                                                                                                                                      
 half-finished requests.                                                                                                                                                                                                                 
                                                                                                                                                                                                                                         
 ### Root cause                                                                                                                                                                                                                          
                                                                                                                                                                                                                                         
 - `handleStreamingResponseWithReasoning`                                                                                                                                                                                                
   (`openai_gateway_response_handling.go`): the async select loop and the                                                                                                                                                                
   synchronous scan loop only return on events-channel close (EOF), scan                                                                                                                                                                 
   error, or timeout. Terminal events never break the loop.                                                                                                                                                                              
 - `handleStreamingResponsePassthrough`                                                                                                                                                                                                  
   (`openai_gateway_passthrough.go`): same pattern — `for                                                                                                                                                                                
   documentScanner.Scan()` runs until EOF.                                                                                                                                                                                               
 - The WS→HTTP bridge (`openai_ws_http_bridge.go`) already returns                                                                                                                                                                       
   immediately on the terminal event; this PR aligns the HTTP/SSE paths                                                                                                                                                                  
   with that behavior.                                                                                                                                                                                                                   
                                                                                                                                                                                                                                         
 ### Fix                                                                                                                                                                                                                                 
                                                                                                                                                                                                                                         
 Once the terminal event frame (`response.completed`, `response.done`,                                                                                                                                                                   
 `response.failed`, `response.incomplete`, `response.cancelled`,                                                                                                                                                                         
 `[DONE]`, …) has been fully written and flushed downstream, finalize the                                                                                                                                                                
 stream immediately instead of waiting for EOF:                                                                                                                                                                                          
                                                                                                                                                                                                                                         
 - Async loop: after processing a line, if `sawTerminalEvent &&                                                                                                                                                                          
   !eventInProgress`, close `resp.Body` (also unblocks the reader                                                                                                                                                                        
   goroutine) and `return finalizeStream()`.                                                                                                                                                                                             
 - Sync loop: same check after each scanned line.                                                                                                                                                                                        
 - Passthrough loop: `break` once a terminal/`[DONE]` event has been                                                                                                                                                                     
   flushed at its blank-line boundary.                                                                                                                                                                                                   
 - Guard: Codex bare-`error` sequences (`error` may be followed by                                                                                                                                                                       
   `response.failed`, or superseded by a later `response.completed`)                                                                                                                                                                     
   keep reading; early finalize is skipped while `codexFailureTerminal &&                                                                                                                                                                
   sawBareError`.                                                                                                                                                                                                                        
                                                                                                                                                                                                                                         
 Usage is already parsed from the terminal event itself                                                                                                                                                                                  
 (`parseSSEUsageBytes`), so nothing is lost by not draining the rest of                                                                                                                                                                  
 the stream.                                                                                                                                                                                                                             
                                                                                                                                                                                                                                         
 ### Tests                                                                                                                                                                                                                               
                                                                                                                                                                                                                                         
 - New regression test                                                                                                                                                                                                                   
   `TestOpenAIResponseFlush_TerminalEventEndsStreamWithoutEOF`: upstream                                                                                                                                                                 
   sends `response.completed` then hangs without EOF; asserts the handler                                                                                                                                                                
   returns promptly with correct usage and body (previously it would                                                                                                                                                                     
   block until the read timeout).                                                                                                                                                                                                        
 - All existing `OpenAIResponseFlush*` and stream/passthrough tests pass.                                                                                                                                                                
   (`TestForwardStreaming_ServiceTierPropagatedToResult` fails on a clean                                                                                                                                                                
   checkout of `main` too — pre-existing, unrelated to this change.)                                                                                                                                                                     
                                                                                                                                                                                                                                         
 ### Out of scope                                                                                                                                                                                                                        
                                                                                                                                                                                                                                         
 The WS passthrough relay                                                                                                                                                                                                                
 (`internal/service/openai_ws_v2/passthrough_relay.go`,                                                                                                                                                                                  
 `runUpstreamToClient`) has the same wait-for-EOF pattern. Left unchanged                                                                                                                                                                
 here to keep the PR focused; happy to follow up if wanted.  

@github-actions

github-actions Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

All contributors have signed the CLA. ✅
Posted by the CLA Assistant Lite bot.

…pstream EOF

The streaming forward loops treated upstream EOF as the only normal exit
condition; response.completed/[DONE] only set a flag. With keep-alive /
HTTP/2 connection reuse to the upstream, the upstream may hold the
stream open for 8-46s after the terminal event, during which the
gateway could only emit downstream keepalives, inflating tail latency.

Finish the stream as soon as the terminal event frame has been fully
written downstream (usage is already parsed from the terminal event),
and close the upstream body to unblock the reader goroutine. Applied
to the guarded/async, sync, and passthrough streaming paths. The WS
HTTP bridge already behaved this way.

Adds a regression test with an upstream that hangs after
response.completed.
@cxx-cod
cxx-cod force-pushed the pr/openai-stream-terminal-eof branch from d82f5d5 to 277aa14 Compare September 1, 2026 19:32
@cxx-cod

cxx-cod commented Sep 1, 2026

Copy link
Copy Markdown
Author

I have read the CLA Document and I hereby sign the CLA

@cxx-cod

cxx-cod commented Sep 1, 2026

Copy link
Copy Markdown
Author

recheck

github-actions Bot added a commit that referenced this pull request Sep 1, 2026
@Wei-Shaw
Wei-Shaw merged commit e26abae into Wei-Shaw:main Sep 22, 2026
9 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 22, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants