ServerSentEventsCodec::decode does not loop over buffered lines, causing mid-stream stalls and dropped SSE events at EOF #5

Closed
opened 2026-10-19 16:15:25 +01:00 by andreban · 1 comment
Owner

Summary

`GeminiClient::stream_generate_content` uses `FramedRead<_, ServerSentEventsCodec>` (`src/network/event_source.rs`). Because `ServerSentEventsCodec::decode` reads only a **single line** per `decode()` call and returns `Ok(None)` 

for non-empty lines (data: ...), FramedRead stalls when a full SSE frame arrives in a single network chunk and drops trailing SSE frames at EOF.

## Root Cause                                                                                                                                                                                                                        
                                                                                                                                                                                                                                     
### 1. `ServerSentEventsCodec::decode` returns `Ok(None)` while complete lines remain in `src`                                                                                                                                       
In `tokio_util::codec::Decoder`, returning `Ok(None)` from `decode(src)` signals to `FramedRead` that `src` does **not** contain enough bytes to produce a complete frame, instructing `FramedRead` to stop calling `decode` and     

block on AsyncRead::poll_read for more bytes from the network.

Currently in `src/network/event_source.rs`:                                                                                                                                                                                          
```rust                                                                                                                                                                                                                              
impl Decoder for ServerSentEventsCodec {                                                                                                                                                                                             
    type Item = ServerSentEvent;                                                                                                                                                                                                     
    type Error = LinesCodecError;                                                                                                                                                                                                    
                                                                                                                                                                                                                                     
    fn decode(                                                                                                                                                                                                                       
        &mut self,                                                                                                                                                                                                                   
        src: &mut tokio_util::bytes::BytesMut,                                                                                                                                                                                       
    ) -> Result<Option<Self::Item>, Self::Error> {                                                                                                                                                                                   
        let Some(mut line) = self.lines_codec.decode(src)? else {                                                                                                                                                                    
            return Ok(None);                                                                                                                                                                                                         
        };                                                                                                                                                                                                                           
                                                                                                                                                                                                                                     
        if line.is_empty() {                                                                                                                                                                                                         
            return Ok(Some(mem::take(&mut self.next)));                                                                                                                                                                              
        }                                                                                                                                                                                                                            
        // ... parses `data: `, `event: `, etc. into `self.next` ...                                                                                                                                                                 
        Ok(None)                                                                                                                                                                                                                     
    }                                                                                                                                                                                                                                
}                                                                                                                                                                                                                                    
```                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                     
When Vertex AI sends a complete SSE frame (`"data: {...}\r\n\r\n"`) in a single HTTP chunk:                                                                                                                                          
1. `FramedRead` reads `"data: {...}\r\n\r\n"` into `src` and calls `decode(src)`.                                                                                                                                                    
2. `self.lines_codec.decode(src)` consumes only the first line (`"data: {...}\r\n"`), leaving `"\r\n"` in `src`.                                                                                                                     
3. `ServerSentEventsCodec::decode` stores `self.next.data` and returns `Ok(None)`.                                                                                                                                                   
4. Because `decode` returned `Ok(None)`, `FramedRead` will **not** call `decode` again to consume the trailing `"\r\n"` until another network read wakes it up—stalling mid-stream if the server is waiting on the client or between 

chunks.

### 2. Trailing SSE frames (such as `functionCall`) are dropped at EOF                                                                                                                                                               
When the HTTP response reaches EOF while a complete SSE frame (`"data: {...}\r\n\r\n"`) is still in `src` (for example, when Vertex AI flushes a `thought` SSE frame and a `functionCall` SSE frame in the final read):              
1. `FramedRead` enters EOF mode and calls `Decoder::decode_eof(src)`.                                                                                                                                                                
2. The default `Decoder::decode_eof` calls `self.decode(src)` **once**.                                                                                                                                                              
3. `decode(src)` consumes `"data: {...}\r\n"` and returns `Ok(None)` while `"\r\n"` is still left in `src`.                                                                                                                          
4. `Decoder::decode_eof` sees `Ok(None)` with `!src.is_empty()` and immediately errors with `LinesCodecError::Io(ErrorKind::Other, "bytes remaining on stream")`, aborting the stream before the final event is emitted.             
                                                                                                                                                                                                                                     
### 3. `parse_sse_event` silently swallows `LinesCodecError`                                                                                                                                                                         
In `src/client.rs`:                                                                                                                                                                                                                  
```rust                                                                                                                                                                                                                              
fn parse_sse_event(                                                                                                                                                                                                                  
    event_result: std::result::Result<ServerSentEvent, tokio_util::codec::LinesCodecError>,                                                                                                                                          
) -> Option<Result<GenerateContentResponseResult>> {                                                                                                                                                                                 
    let data = event_result.map_err(Error::from).ok()?.data?;                                                                                                                                                                        
```                                                                                                                                                                                                                                  
Because `.ok()?` converts `Err(LinesCodecError)` into `None` inside `.filter_map(...)`, stream/codec errors (including `"bytes remaining on stream"`) are silently discarded instead of being surfaced to the caller as              

Some(Err(Error::from(err))). Also, heartbeats/empty SSE frames (data: None) are emitted by decode on any blank line even when self.next is empty.

## Minimal Reproduction                                                                                                                                                                                                              
```rust                                                                                                                                                                                                                              
#[tokio::test]                                                                                                                                                                                                                       
async fn test_multiple_sse_events_in_single_buffer() {                                                                                                                                                                               
    use tokio_stream::StreamExt;                                                                                                                                                                                                     
    use tokio_util::codec::FramedRead;                                                                                                                                                                                               
                                                                                                                                                                                                                                     
    let payload = b"data: {\"chunk\":1}\r\n\r\ndata: {\"chunk\":2}\r\n\r\n";                                                                                                                                                         
    let mut stream = FramedRead::new(&payload[..], ServerSentEventsCodec::new());                                                                                                                                                    
                                                                                                                                                                                                                                     
    let first = stream.next().await.unwrap().unwrap();                                                                                                                                                                               
    assert_eq!(first.data.as_deref(), Some("{\"chunk\":1}"));                                                                                                                                                                        
                                                                                                                                                                                                                                     
    // Fails with `Io(Custom { kind: Other, error: "bytes remaining on stream" })`                                                                                                                                                   
    // because `decode` only consumes one line per call during `decode_eof`.                                                                                                                                                         
    let second = stream.next().await.unwrap().unwrap();                                                                                                                                                                              
    assert_eq!(second.data.as_deref(), Some("{\"chunk\":2}"));                                                                                                                                                                       
}                                                                                                                                                                                                                                    
```                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                     
## Proposed Fix                                                                                                                                                                                                                      
                                                                                                                                                                                                                                     
1. Loop inside `ServerSentEventsCodec::decode` until either a blank line completes a non-empty event (`Ok(Some(event))`) or `self.lines_codec.decode(src)?` returns `Ok(None)` (no more complete lines in `src`):                    
```rust                                                                                                                                                                                                                              
impl Decoder for ServerSentEventsCodec {                                                                                                                                                                                             
    type Item = ServerSentEvent;                                                                                                                                                                                                     
    type Error = LinesCodecError;                                                                                                                                                                                                    
                                                                                                                                                                                                                                     
    fn decode(                                                                                                                                                                                                                       
        &mut self,                                                                                                                                                                                                                   
        src: &mut tokio_util::bytes::BytesMut,                                                                                                                                                                                       
    ) -> Result<Option<Self::Item>, Self::Error> {                                                                                                                                                                                   
        loop {                                                                                                                                                                                                                       
            let Some(mut line) = self.lines_codec.decode(src)? else {                                                                                                                                                                
                return Ok(None);                                                                                                                                                                                                     
            };                                                                                                                                                                                                                       
                                                                                                                                                                                                                                     
            if line.is_empty() {                                                                                                                                                                                                     
                if self.next.data.is_some()                                                                                                                                                                                          
                    || self.next.event.is_some()                                                                                                                                                                                     
                    || self.next.id.is_some()                                                                                                                                                                                        
                    || self.next.retry.is_some()                                                                                                                                                                                     
                {                                                                                                                                                                                                                    
                    return Ok(Some(mem::take(&mut self.next)));                                                                                                                                                                      
                }                                                                                                                                                                                                                    
                continue;                                                                                                                                                                                                            
            }                                                                                                                                                                                                                        
                                                                                                                                                                                                                                     
            if line.starts_with(EVENT) {                                                                                                                                                                                             
                line.drain(..EVENT.len());                                                                                                                                                                                           
                self.next.event = Some(line);                                                                                                                                                                                        
            } else if line.starts_with(DATA) {                                                                                                                                                                                       
                line.drain(..DATA.len());                                                                                                                                                                                            
                if let Some(ref mut existing) = self.next.data {                                                                                                                                                                     
                    existing.push('\n');                                                                                                                                                                                             
                    existing.push_str(&line);                                                                                                                                                                                        
                } else {                                                                                                                                                                                                             
                    self.next.data = Some(line);                                                                                                                                                                                     
                }                                                                                                                                                                                                                    
            } else if line.starts_with("#") {                                                                                                                                                                                        
                // SSE comment / keep-alive line; ignore.                                                                                                                                                                            
            } else if line.starts_with(ID) {                                                                                                                                                                                         
                line.drain(..ID.len());                                                                                                                                                                                              
                self.next.id = Some(line);                                                                                                                                                                                           
            } else if line.starts_with(RETRY) {                                                                                                                                                                                      
                line.drain(..RETRY.len());                                                                                                                                                                                           
                if let Ok(retry) = line.parse() {                                                                                                                                                                                    
                    self.next.retry = Some(retry);                                                                                                                                                                                   
                } else {                                                                                                                                                                                                             
                    warn!(line, "Received invalid retry value");                                                                                                                                                                     
                }                                                                                                                                                                                                                    
            }                                                                                                                                                                                                                        
        }                                                                                                                                                                                                                            
    }                                                                                                                                                                                                                                
}                                                                                                                                                                                                                                    
```                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                     
2. Propagate `LinesCodecError` in `GeminiClient::parse_sse_event` (`src/client.rs`) instead of swallowing it with `.ok()?`:                                                                                                          
```rust                                                                                                                                                                                                                              
fn parse_sse_event(                                                                                                                                                                                                                  
    event_result: std::result::Result<ServerSentEvent, tokio_util::codec::LinesCodecError>,                                                                                                                                          
) -> Option<Result<GenerateContentResponseResult>> {                                                                                                                                                                                 
    match event_result {                                                                                                                                                                                                             
        Ok(event) => {                                                                                                                                                                                                               
            let data = event.data?;                                                                                                                                                                                                  
            Some(                                                                                                                                                                                                                    
                serde_json::from_str::<GenerateContentResponse>(&data)                                                                                                                                                               
                    .map_err(Error::from)                                                                                                                                                                                            
                    .and_then(|r| r.into_result()),                                                                                                                                                                                  
            )                                                                                                                                                                                                                        
        }                                                                                                                                                                                                                            
        Err(err) => Some(Err(Error::from(err))),                                                                                                                                                                                     
    }                                                                                                                                                                                                                                
}                                                                                                                                                                                                                                    
```   
## Summary `GeminiClient::stream_generate_content` uses `FramedRead<_, ServerSentEventsCodec>` (`src/network/event_source.rs`). Because `ServerSentEventsCodec::decode` reads only a **single line** per `decode()` call and returns `Ok(None)` for non-empty lines (`data: ...`), `FramedRead` stalls when a full SSE frame arrives in a single network chunk and drops trailing SSE frames at EOF. ## Root Cause ### 1. `ServerSentEventsCodec::decode` returns `Ok(None)` while complete lines remain in `src` In `tokio_util::codec::Decoder`, returning `Ok(None)` from `decode(src)` signals to `FramedRead` that `src` does **not** contain enough bytes to produce a complete frame, instructing `FramedRead` to stop calling `decode` and block on `AsyncRead::poll_read` for more bytes from the network. Currently in `src/network/event_source.rs`: ```rust impl Decoder for ServerSentEventsCodec { type Item = ServerSentEvent; type Error = LinesCodecError; fn decode( &mut self, src: &mut tokio_util::bytes::BytesMut, ) -> Result<Option<Self::Item>, Self::Error> { let Some(mut line) = self.lines_codec.decode(src)? else { return Ok(None); }; if line.is_empty() { return Ok(Some(mem::take(&mut self.next))); } // ... parses `data: `, `event: `, etc. into `self.next` ... Ok(None) } } ``` When Vertex AI sends a complete SSE frame (`"data: {...}\r\n\r\n"`) in a single HTTP chunk: 1. `FramedRead` reads `"data: {...}\r\n\r\n"` into `src` and calls `decode(src)`. 2. `self.lines_codec.decode(src)` consumes only the first line (`"data: {...}\r\n"`), leaving `"\r\n"` in `src`. 3. `ServerSentEventsCodec::decode` stores `self.next.data` and returns `Ok(None)`. 4. Because `decode` returned `Ok(None)`, `FramedRead` will **not** call `decode` again to consume the trailing `"\r\n"` until another network read wakes it up—stalling mid-stream if the server is waiting on the client or between chunks. ### 2. Trailing SSE frames (such as `functionCall`) are dropped at EOF When the HTTP response reaches EOF while a complete SSE frame (`"data: {...}\r\n\r\n"`) is still in `src` (for example, when Vertex AI flushes a `thought` SSE frame and a `functionCall` SSE frame in the final read): 1. `FramedRead` enters EOF mode and calls `Decoder::decode_eof(src)`. 2. The default `Decoder::decode_eof` calls `self.decode(src)` **once**. 3. `decode(src)` consumes `"data: {...}\r\n"` and returns `Ok(None)` while `"\r\n"` is still left in `src`. 4. `Decoder::decode_eof` sees `Ok(None)` with `!src.is_empty()` and immediately errors with `LinesCodecError::Io(ErrorKind::Other, "bytes remaining on stream")`, aborting the stream before the final event is emitted. ### 3. `parse_sse_event` silently swallows `LinesCodecError` In `src/client.rs`: ```rust fn parse_sse_event( event_result: std::result::Result<ServerSentEvent, tokio_util::codec::LinesCodecError>, ) -> Option<Result<GenerateContentResponseResult>> { let data = event_result.map_err(Error::from).ok()?.data?; ``` Because `.ok()?` converts `Err(LinesCodecError)` into `None` inside `.filter_map(...)`, stream/codec errors (including `"bytes remaining on stream"`) are silently discarded instead of being surfaced to the caller as `Some(Err(Error::from(err)))`. Also, heartbeats/empty SSE frames (`data: None`) are emitted by `decode` on any blank line even when `self.next` is empty. ## Minimal Reproduction ```rust #[tokio::test] async fn test_multiple_sse_events_in_single_buffer() { use tokio_stream::StreamExt; use tokio_util::codec::FramedRead; let payload = b"data: {\"chunk\":1}\r\n\r\ndata: {\"chunk\":2}\r\n\r\n"; let mut stream = FramedRead::new(&payload[..], ServerSentEventsCodec::new()); let first = stream.next().await.unwrap().unwrap(); assert_eq!(first.data.as_deref(), Some("{\"chunk\":1}")); // Fails with `Io(Custom { kind: Other, error: "bytes remaining on stream" })` // because `decode` only consumes one line per call during `decode_eof`. let second = stream.next().await.unwrap().unwrap(); assert_eq!(second.data.as_deref(), Some("{\"chunk\":2}")); } ``` ## Proposed Fix 1. Loop inside `ServerSentEventsCodec::decode` until either a blank line completes a non-empty event (`Ok(Some(event))`) or `self.lines_codec.decode(src)?` returns `Ok(None)` (no more complete lines in `src`): ```rust impl Decoder for ServerSentEventsCodec { type Item = ServerSentEvent; type Error = LinesCodecError; fn decode( &mut self, src: &mut tokio_util::bytes::BytesMut, ) -> Result<Option<Self::Item>, Self::Error> { loop { let Some(mut line) = self.lines_codec.decode(src)? else { return Ok(None); }; if line.is_empty() { if self.next.data.is_some() || self.next.event.is_some() || self.next.id.is_some() || self.next.retry.is_some() { return Ok(Some(mem::take(&mut self.next))); } continue; } if line.starts_with(EVENT) { line.drain(..EVENT.len()); self.next.event = Some(line); } else if line.starts_with(DATA) { line.drain(..DATA.len()); if let Some(ref mut existing) = self.next.data { existing.push('\n'); existing.push_str(&line); } else { self.next.data = Some(line); } } else if line.starts_with("#") { // SSE comment / keep-alive line; ignore. } else if line.starts_with(ID) { line.drain(..ID.len()); self.next.id = Some(line); } else if line.starts_with(RETRY) { line.drain(..RETRY.len()); if let Ok(retry) = line.parse() { self.next.retry = Some(retry); } else { warn!(line, "Received invalid retry value"); } } } } } ``` 2. Propagate `LinesCodecError` in `GeminiClient::parse_sse_event` (`src/client.rs`) instead of swallowing it with `.ok()?`: ```rust fn parse_sse_event( event_result: std::result::Result<ServerSentEvent, tokio_util::codec::LinesCodecError>, ) -> Option<Result<GenerateContentResponseResult>> { match event_result { Ok(event) => { let data = event.data?; Some( serde_json::from_str::<GenerateContentResponse>(&data) .map_err(Error::from) .and_then(|r| r.into_result()), ) } Err(err) => Some(Err(Error::from(err))), } } ```
Author
Owner

Closed via #7

Closed via #7
Sign in to join this conversation.
No Label
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: andreban/gemini-rs#5