1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Streaming driver shared by every LLM provider: the producer side, raw wire
//! events -> shared [`StreamEvent`] vocabulary. [`crate::streaming`] is
//! the consumer side (`StreamEvent` -> `ChatResponse`).
//!
//! Each provider supplies only a [`StreamMapper`]; [`drive_stream`] owns the
//! termination policy. Idle timeouts belong at the transport boundary, before
//! SSE parsing or WebSocket control-frame handling can swallow keepalives.
use crate::error::LlmError;
use crate::types::{ChatResponseStream, StreamEvent};
use futures_util::{Stream, StreamExt};
use std::collections::VecDeque;
/// Translates one provider's raw wire stream into the shared [`StreamEvent`]
/// vocabulary. The only provider-specific part of streaming. `map` is sync:
/// making it async would force the per-event future to be `Send` for no gain.
pub(crate) trait StreamMapper: Send + 'static {
/// Providers decode their wire events before handing them to the driver, so
/// the trait only needs `Send + 'static` here.
type Raw: Send + 'static;
/// Map one raw event into zero or more normalized events. Stateful. May
/// classify a provider error *event* (e.g. `response.failed`) into an
/// [`LlmError`].
fn map(&mut self, raw: Self::Raw) -> Result<Vec<StreamEvent>, LlmError>;
/// Trailing events when the raw stream ends: a mapper with buffered state
/// flushes it here (e.g. a `MessageStop` synthesized from an already-seen
/// finish reason). Called at most once, on raw EOF; a stream ended by a
/// mid-stream `MessageStop` never reaches it. The driver, not the mapper,
/// fails a stream that still has no `MessageStop` after this flush.
fn on_end(&mut self) -> Result<Vec<StreamEvent>, LlmError> {
Ok(Vec::new())
}
}
enum Phase {
Streaming,
/// The raw stream reached EOF and `on_end` flushed. Drain `buf`; never
/// pull raw again. No `MessageStop` has been handed out yet.
Draining,
/// A `MessageStop` or an error ended the stream; nothing more to hand out.
Done,
}
/// Drive a provider's raw wire stream into a [`ChatResponseStream`].
///
/// Hands out mapped events, pulls the next raw event, and runs
/// `mapper.on_end()` once when the raw stream completes. `MessageStop` is
/// terminal on every wire (nothing is pulled after it); an end without one
/// surfaces as `UnexpectedEof`, not a complete response.
pub(crate) fn drive_stream<M, S>(raw: S, mapper: M) -> ChatResponseStream
where
M: StreamMapper,
S: Stream<Item = Result<M::Raw, LlmError>> + Send + Unpin + 'static,
{
let init = (raw, mapper, VecDeque::<StreamEvent>::new(), Phase::Streaming);
let s = futures_util::stream::unfold(
init,
move |(mut raw, mut mapper, mut buf, mut phase)| async move {
loop {
// 1. Hand out anything already mapped before pulling more.
if let Some(ev) = buf.pop_front() {
if matches!(ev, StreamEvent::MessageStop { .. }) {
// MessageStop is terminal on every wire: drop anything
// buffered behind it and stop pulling raw, so a server
// that holds the connection open after the final event
// cannot hang the stream.
buf.clear();
phase = Phase::Done;
}
return Some((Ok(ev), (raw, mapper, buf, phase)));
}
match phase {
Phase::Streaming => {}
// 2. Buffer drained after the stream ended.
Phase::Done => return None,
Phase::Draining => {
// The stream ended without its terminal MessageStop: a
// premature close (quiet EOF, proxy cut). Fail it so a
// truncated transcript is never passed off as a
// complete response.
phase = Phase::Done;
return Some((
Err(LlmError::unexpected_eof("stream ended before completion")),
(raw, mapper, buf, phase),
));
}
}
// 3. Pull the next raw event; transport reads own the idle timeout.
match raw.next().await {
// Idle timeout or producer-classified stream error: the
// consumer stops on the first Err.
Some(Err(err)) => return Some((Err(err), (raw, mapper, buf, phase))),
Some(Ok(item)) => match mapper.map(item) {
Ok(evs) => buf.extend(evs), // empty => loop pulls next raw
Err(e) => return Some((Err(e), (raw, mapper, buf, phase))), // classified err
},
None => match mapper.on_end() {
// called once: Streaming -> Draining
Ok(evs) => {
buf.extend(evs);
phase = Phase::Draining;
}
Err(e) => return Some((Err(e), (raw, mapper, buf, Phase::Done))),
},
}
}
},
);
Box::pin(s)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::client::with_idle_timeout;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
/// A `StreamMapper` over a `Vec`-backed raw stream. `Raw` is the exact list
/// of events `map` should emit, so tests control the per-raw output and the
/// trailing `on_end` output directly.
struct FakeMapper {
on_end_events: Vec<StreamEvent>,
on_end_calls: Arc<AtomicUsize>,
}
impl FakeMapper {
fn new() -> (Self, Arc<AtomicUsize>) {
let on_end_calls = Arc::new(AtomicUsize::new(0));
(Self { on_end_events: Vec::new(), on_end_calls: on_end_calls.clone() }, on_end_calls)
}
fn with_on_end(events: Vec<StreamEvent>) -> (Self, Arc<AtomicUsize>) {
let on_end_calls = Arc::new(AtomicUsize::new(0));
(Self { on_end_events: events, on_end_calls: on_end_calls.clone() }, on_end_calls)
}
}
impl StreamMapper for FakeMapper {
type Raw = Vec<StreamEvent>;
fn map(&mut self, raw: Vec<StreamEvent>) -> Result<Vec<StreamEvent>, LlmError> {
Ok(raw)
}
fn on_end(&mut self) -> Result<Vec<StreamEvent>, LlmError> {
self.on_end_calls.fetch_add(1, Ordering::SeqCst);
Ok(self.on_end_events.clone())
}
}
fn raw_stream(
items: Vec<Result<Vec<StreamEvent>, LlmError>>,
) -> impl Stream<Item = Result<Vec<StreamEvent>, LlmError>> + Send + Unpin + 'static {
futures_util::stream::iter(items)
}
fn text(s: &str) -> StreamEvent {
StreamEvent::TextDelta(s.to_string())
}
fn stop() -> StreamEvent {
StreamEvent::MessageStop { usage: Default::default(), stop_reason: None }
}
async fn collect(mut stream: ChatResponseStream) -> Vec<Result<StreamEvent, LlmError>> {
let mut out = Vec::new();
while let Some(ev) = stream.next().await {
out.push(ev);
}
out
}
/// (a) A multi-event `map` result is drained in order before the next raw.
#[tokio::test]
async fn multi_event_map_drains_in_order() {
let (mapper, _) = FakeMapper::new();
let raw = raw_stream(vec![Ok(vec![text("a"), text("b"), text("c"), stop()])]);
let out = collect(drive_stream(raw, mapper)).await;
let texts: Vec<String> = out
.iter()
.filter_map(|ev| match ev.as_ref().unwrap() {
StreamEvent::TextDelta(t) => Some(t.clone()),
StreamEvent::MessageStop { .. } => None,
other => panic!("expected TextDelta or MessageStop, got {other:?}"),
})
.collect();
assert_eq!(texts, vec!["a", "b", "c"]);
assert!(matches!(out.last().unwrap().as_ref().unwrap(), StreamEvent::MessageStop { .. }));
}
#[tokio::test(start_paused = true)]
async fn unmapped_events_keep_the_stream_alive_until_transport_silence() {
let (mapper, _) = FakeMapper::new();
let raw = futures_util::stream::iter([vec![], vec![], vec![], vec![text("pong")]])
.then(|events| async move {
tokio::time::sleep(Duration::from_secs(10)).await;
Ok(events)
})
.chain(futures_util::stream::pending());
let raw = with_idle_timeout(Box::pin(raw), Duration::from_secs(17));
let mut stream = drive_stream(Box::pin(raw), mapper);
let start = tokio::time::Instant::now();
assert!(
matches!(stream.next().await.unwrap().unwrap(), StreamEvent::TextDelta(text) if text == "pong")
);
assert_eq!(start.elapsed(), Duration::from_secs(40));
let err = stream.next().await.unwrap().unwrap_err();
assert_eq!(err.kind, crate::error::LlmErrorKind::UnexpectedEof);
assert_eq!(start.elapsed(), Duration::from_secs(57));
}
/// (c) `on_end` emits its events then the stream ends, and is called exactly
/// once (no double-emit on a premature close).
#[tokio::test]
async fn on_end_emits_once_then_terminates() {
let (mapper, calls) = FakeMapper::with_on_end(vec![StreamEvent::ContentStop, stop()]);
let raw = raw_stream(vec![Ok(vec![text("a")])]);
let out = collect(drive_stream(raw, mapper)).await;
assert!(matches!(out[0].as_ref().unwrap(), StreamEvent::TextDelta(t) if t == "a"));
assert!(matches!(out[1].as_ref().unwrap(), StreamEvent::ContentStop));
assert!(matches!(out[2].as_ref().unwrap(), StreamEvent::MessageStop { .. }));
assert_eq!(out.len(), 3, "on_end events must appear exactly once");
assert_eq!(calls.load(Ordering::SeqCst), 1, "on_end must be called exactly once");
}
/// (e) A raw stream `Err` is propagated. (A consumer that keeps polling
/// past it reaches EOF, which — having no MessageStop — also fails; the
/// real collector stops at the first Err.)
#[tokio::test]
async fn stream_error_is_propagated() {
let (mapper, _) = FakeMapper::new();
let raw = raw_stream(vec![Ok(vec![text("a")]), Err(LlmError::transport("boom"))]);
let out = collect(drive_stream(raw, mapper)).await;
assert!(matches!(out[0].as_ref().unwrap(), StreamEvent::TextDelta(t) if t == "a"));
let err = out[1].as_ref().unwrap_err();
assert_eq!(err.kind, crate::error::LlmErrorKind::Transport);
assert!(err.to_string().contains("boom"));
let err = out[2].as_ref().unwrap_err();
assert_eq!(err.kind, crate::error::LlmErrorKind::UnexpectedEof);
assert_eq!(out.len(), 3);
}
/// (f) A stream that ends without a terminal MessageStop is a premature
/// close: the events stream out, then the driver fails the stream instead
/// of passing the truncated transcript off as a complete response.
#[tokio::test]
async fn stream_without_message_stop_fails_as_unexpected_eof() {
let (mapper, _) = FakeMapper::new();
let raw = raw_stream(vec![Ok(vec![text("partial")])]);
let out = collect(drive_stream(raw, mapper)).await;
assert!(matches!(out[0].as_ref().unwrap(), StreamEvent::TextDelta(t) if t == "partial"));
let err = out[1].as_ref().unwrap_err();
assert_eq!(err.kind, crate::error::LlmErrorKind::UnexpectedEof);
assert_eq!(out.len(), 2, "the missing-stop error must be yielded exactly once");
}
/// (g) MessageStop is terminal: the driver stops pulling raw events, so a
/// server that holds the connection open after the final event (observed
/// on a Gemini bridge speaking the Anthropic wire) cannot hang the stream.
#[tokio::test]
async fn driver_stops_pulling_after_message_stop() {
let (mapper, _) = FakeMapper::new();
let raw = raw_stream(vec![Ok(vec![text("hi"), stop()])])
.chain(futures_util::stream::pending::<Result<Vec<StreamEvent>, LlmError>>());
let out = tokio::time::timeout(
std::time::Duration::from_secs(1),
collect(drive_stream(Box::pin(raw), mapper)),
)
.await
.expect("driver kept pulling after MessageStop instead of ending the stream");
assert!(matches!(out[0].as_ref().unwrap(), StreamEvent::TextDelta(t) if t == "hi"));
assert!(matches!(out[1].as_ref().unwrap(), StreamEvent::MessageStop { .. }));
assert_eq!(out.len(), 2);
}
}