From 37f30cd6772ed24e65558b805c2b7672cd059df0 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 00:38:28 +0800 Subject: [PATCH 1/5] test(aimux): pin the header report against the timer tick that ends its allowance The header allowance is a timer, so a report written after the allowance can still be read before the timer fires: the report arm accepts it and starts a fresh window from it, while the same report read after the tick ends the wait as missing headers. A virtual-time test writes the report 0.2 ms after the allowance with the clock half a tick off the grid, and a second one reads the same report after the tick; both must end the wait as missing headers. A third writes the report exactly at the allowance and must still start the reply. The first fails on the current driver by assertion; the other two pin the orders the fix must keep. --- crates/dim-agent-aimux/src/driver/tests.rs | 158 +++++++++++++++++++++ 1 file changed, 158 insertions(+) diff --git a/crates/dim-agent-aimux/src/driver/tests.rs b/crates/dim-agent-aimux/src/driver/tests.rs index c2f4b4db1a..b0eb6044c1 100644 --- a/crates/dim-agent-aimux/src/driver/tests.rs +++ b/crates/dim-agent-aimux/src/driver/tests.rs @@ -595,3 +595,161 @@ async fn a_responses_start_inside_its_allowance_delivers_the_output() { } assert_eq!(text, "hello"); } + +/// The timer that ends the header allowance fires on its next millisecond +/// tick, so a report written just after the allowance can be read before the +/// timer fires. It is late by its own instant there too: the wait ends as +/// missing headers instead of starting a fresh window from a late report. +#[tokio::test(start_paused = true)] +async fn a_header_report_written_after_its_allowance_is_late() { + let (fetch, reply) = scripted(); + let driver = driver(fetch); + // Half a tick puts the allowance between two ticks, so the timer fires up + // to one tick after it. + tokio::time::advance(Duration::from_micros(500)).await; + let mut invoke = driver.invoke( + Arc::new(request()), + connection(ModelProtocol::OpenaiChat), + CancellationToken::new(), + ); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the request must wait for its response headers" + ); + // The exchange is polled 0.2 ms after the allowance, before its timer. + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT + Duration::from_micros(200)).await; + reply + .send(ScriptedReply { + status: http::StatusCode::OK, + headers: headers("text/event-stream"), + body: ScriptedBody::default(), + }) + .unwrap(); + assert!( + poll_once(invoke.as_mut()).is_pending(), + "the exchange must stop after the report" + ); + tokio::time::advance(Duration::from_micros(100)).await; + let error = match poll_until_idle(invoke.as_mut()) { + Some(Err(error)) => error, + Some(Ok(_)) => panic!("a reply must not start from a late report"), + None => panic!("a report written after the allowance must fail before the timer fires"), + }; + let HostError::Failed { + kind, + model: Some(model), + .. + } = &error + else { + panic!("{error:?}"); + }; + assert_eq!(*kind, HostErrorKind::Transport); + assert_eq!(model.kind, ModelFailureKind::Network); + assert_eq!( + model.reason.as_deref(), + Some("no response headers arrived within 300 seconds of sending the request") + ); +} + +/// The same late report read after the timer tick: the deadline arm rejects a +/// report stamped after the allowance, so a report's classification does not +/// depend on which arm polls it first. +#[tokio::test(start_paused = true)] +async fn a_header_report_written_after_its_allowance_is_late_after_the_tick() { + let (fetch, reply) = scripted(); + let driver = driver(fetch); + tokio::time::advance(Duration::from_micros(500)).await; + let mut invoke = driver.invoke( + Arc::new(request()), + connection(ModelProtocol::OpenaiChat), + CancellationToken::new(), + ); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the request must wait for its response headers" + ); + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT + Duration::from_micros(200)).await; + reply + .send(ScriptedReply { + status: http::StatusCode::OK, + headers: headers("text/event-stream"), + body: ScriptedBody::default(), + }) + .unwrap(); + assert!( + poll_once(invoke.as_mut()).is_pending(), + "the exchange must stop after the report" + ); + tokio::time::advance(Duration::from_micros(600)).await; + let error = match poll_until_idle(invoke.as_mut()) { + Some(Err(error)) => error, + Some(Ok(_)) => panic!("a reply must not start from a late report"), + None => panic!("the deadline arm must fail a late report"), + }; + let HostError::Failed { + kind, + model: Some(model), + .. + } = &error + else { + panic!("{error:?}"); + }; + assert_eq!(*kind, HostErrorKind::Transport); + assert_eq!(model.kind, ModelFailureKind::Network); + assert_eq!( + model.reason.as_deref(), + Some("no response headers arrived within 300 seconds of sending the request") + ); +} + +/// A report written exactly at the allowance is on time in either arm: the +/// comparison includes the instant, and the reply starts from it. +#[tokio::test(start_paused = true)] +async fn a_header_report_written_at_the_allowance_stays_on_time() { + let (fetch, reply) = scripted(); + let body = ScriptedBody::default(); + let driver = driver(fetch); + tokio::time::advance(Duration::from_micros(500)).await; + let mut invoke = driver.invoke( + Arc::new(request()), + connection(ModelProtocol::OpenaiChat), + CancellationToken::new(), + ); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the request must wait for its response headers" + ); + // The exchange is polled exactly at the allowance, still before its timer. + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT).await; + reply + .send(ScriptedReply { + status: http::StatusCode::OK, + headers: headers("text/event-stream"), + body: body.clone(), + }) + .unwrap(); + assert!( + poll_once(invoke.as_mut()).is_pending(), + "the exchange must stop after the report" + ); + tokio::time::advance(Duration::from_micros(100)).await; + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "a report written at the allowance must not be read as late" + ); + body.push(format!( + "data: {}\n\n", + json!({"id": "remote-id", "choices": [{"index": 0, "delta": {"content": "hello"}, "finish_reason": Value::Null}]}) + )); + let mut stream = poll_until_idle(invoke.as_mut()) + .expect("the report must start the reply") + .expect("the reply must start after the report"); + let start = next_chunk(&mut stream) + .expect("the reply must deliver its start") + .expect("the reply must not fail before its start"); + assert!(matches!(start, ModelChunk::MessageStart { .. })); + let text = next_chunk(&mut stream) + .expect("the reply must deliver its text") + .expect("the first event must deliver text"); + assert!(matches!(text, ModelChunk::Text(text) if text == "hello")); +} From f56ede45eafdda8bcbe62a2b304204ee1faa2baa Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 00:39:14 +0800 Subject: [PATCH 2/5] fix(aimux): judge a header report by its instant in the report arm The header allowance is a timer, and it fires on its next millisecond tick, so the report arm could read a report stamped after the allowance while its timer was still pending: the arm accepted the report and started a fresh stream window from it, while the same report read after the tick ended the wait as missing headers. The report arm now compares the allowed instant with the report and ends the wait as missing headers, so a report's class no longer depends on which arm reads it first. The select order is unchanged: the deadline still runs before the report and the exchange, and a part that is ready with an expired deadline still loses to it. The model failure document states the two sides of the rule: a header written inside the allowance is on time when it is read later, and a header written after the allowance is late when it is read before the timer fires. --- crates/dim-agent-aimux/src/driver.rs | 13 +++++++++++++ docs/design/model-failures.md | 4 +++- docs/zh/design/model-failures.md | 2 +- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/dim-agent-aimux/src/driver.rs b/crates/dim-agent-aimux/src/driver.rs index 6de11c8f39..6953e49a90 100644 --- a/crates/dim-agent-aimux/src/driver.rs +++ b/crates/dim-agent-aimux/src/driver.rs @@ -869,6 +869,19 @@ impl ModelDriver for AimuxDriver { report = &mut response, if awaiting_headers => { awaiting_headers = false; if let Ok(report) = report { + // A report written after the allowance is late + // here as well: its timer may not have fired. + if report.received > deadline_at { + abort.abort(); + let error = stream::idle_failure(format!( + "no response headers arrived within {} seconds of sending the request", + stream::STREAM_IDLE_TIMEOUT.as_secs() + )); + if let Some(pending) = pending.as_mut() { + pending.failed(&error.to_string()); + } + return Err(error); + } headers_arrived = true; if report.status.is_success() { deadline_at = report.received + stream::STREAM_IDLE_TIMEOUT; diff --git a/docs/design/model-failures.md b/docs/design/model-failures.md index c22c40604a..c8b40beab6 100644 --- a/docs/design/model-failures.md +++ b/docs/design/model-failures.md @@ -37,7 +37,9 @@ streaming is never cut; an expired bound outranks a part that is ready at the same moment, and cancelling the request outranks both. A wait whose event has a producer-reported instant is judged against that instant: the transport reports the moment it produced the response headers, so headers written inside the -allowance are on time even when the driver next polls after it. A wait with no +allowance are on time even when the driver next polls after it, and headers +written after the allowance are late even when the report is read before the +timer that ends it fires. A wait with no such instant, the provider returning the stream and one stream part, keeps the deadline-first order. diff --git a/docs/zh/design/model-failures.md b/docs/zh/design/model-failures.md index acf302b892..588ac727b7 100644 --- a/docs/zh/design/model-failures.md +++ b/docs/zh/design/model-failures.md @@ -23,7 +23,7 @@ aimux 桥接层是唯一持有提供方结构化错误、并看得到完整响 HTTP 连接或流的超时以传输 `ApiCall` 到达桥接层,是 `network`。`AiMuxError::Timeout` 在聊天调用中没有产生者;若它到达桥接层,是 `unknown`,且不重试。 -桥接层自己也给几段等待设上限:连续五分钟没有任何事件是 `network`,reason 为 `the stream delivered nothing for 300 seconds`。这个上限按每次等待计,不按整个请求计,所以持续有事件的回复不会被截断;上限到点时它优先于同时就绪的事件,取消请求又优先于两者。事件有生产者上报时刻的等待按那个时刻判定:传输层上报它产生响应头的时刻,所以在上限内写下的响应头,即使 driver 之后再 poll 也算按时。没有这种时刻的等待(provider 返回流、两个流分片之间)仍以上限优先。 +桥接层自己也给几段等待设上限:连续五分钟没有任何事件是 `network`,reason 为 `the stream delivered nothing for 300 seconds`。这个上限按每次等待计,不按整个请求计,所以持续有事件的回复不会被截断;上限到点时它优先于同时就绪的事件,取消请求又优先于两者。事件有生产者上报时刻的等待按那个时刻判定:传输层上报它产生响应头的时刻,所以在上限内写下的响应头,即使 driver 之后再 poll 也算按时;超过上限写下的响应头,即使在这个上限的计时器触发之前被读到,也算迟到。没有这种时刻的等待(provider 返回流、两个流分片之间)仍以上限优先。 带上限的等待有三段。等响应头从发出请求开始计,发送请求体和跟随重定向都算在内,reason 为 `no response headers arrived within 300 seconds of sending the request`。等流启动从传输层产生响应头时开始计。先读一个流事件再返回流的 provider(OpenAI Chat、Anthropic、Gemini、xAI Responses),reason 为 `the response headers arrived, but no stream event followed within 300 seconds`。OpenAI Responses 的 provider 固定版本的 SDK 在返回流之前会读取响应元数据,它的 reason 为 `the response headers arrived, but the stream did not start within 300 seconds`:这段等待结束于流的启动,而不是 driver 看得到的事件。OpenAI 兼容和 Bedrock 的 provider 在响应头处就返回,它们的第一个事件落在两次事件之间的等待里,reason 为 `the stream delivered nothing for 300 seconds`。非 2xx 响应另算:它的响应体是短的诊断信息,读取单独有总计五分钟的上限,卡住的错误体不能拖住请求,请求仍然按 HTTP 状态和该状态对应的类别失败,而不是变成空闲的网络失败。连接原来可选的整请求超时不变,和这几段上限是两件事。 From 134b9f4d67f467c53e2ca99d04e2b749ba785965 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 00:59:30 +0800 Subject: [PATCH 3/5] test(aimux): pin a late error report to the missing-headers failure A report written after the header allowance must be classified the same way whichever arm reads it, and a non-2xx status must not change that class. This case writes a 401 at the boundary instant and asserts the missing-headers network failure the deadline arm gives the same report, with no status carried. The classification comes from the previous commit, so this case pins it rather than reproducing an old failure. --- crates/dim-agent-aimux/src/driver/tests.rs | 55 ++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/crates/dim-agent-aimux/src/driver/tests.rs b/crates/dim-agent-aimux/src/driver/tests.rs index b0eb6044c1..78219c6e45 100644 --- a/crates/dim-agent-aimux/src/driver/tests.rs +++ b/crates/dim-agent-aimux/src/driver/tests.rs @@ -702,6 +702,61 @@ async fn a_header_report_written_after_its_allowance_is_late_after_the_tick() { ); } +/// A 401 written after the header allowance is late as well: read before the +/// timer fires, it ends the wait as missing headers, the failure the deadline +/// arm gives the same report, and it does not keep its status. +#[tokio::test(start_paused = true)] +async fn a_late_error_report_fails_as_a_network_failure() { + let (fetch, reply) = scripted(); + let driver = driver(fetch); + // Half a tick puts the allowance between two ticks, so the timer fires up + // to one tick after it. + tokio::time::advance(Duration::from_micros(500)).await; + let mut invoke = driver.invoke( + Arc::new(request()), + connection(ModelProtocol::OpenaiChat), + CancellationToken::new(), + ); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the request must wait for its response headers" + ); + // The exchange is polled 0.2 ms after the allowance, before its timer. + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT + Duration::from_micros(200)).await; + reply + .send(ScriptedReply { + status: http::StatusCode::UNAUTHORIZED, + headers: headers("application/json"), + body: ScriptedBody::default(), + }) + .unwrap(); + assert!( + poll_once(invoke.as_mut()).is_pending(), + "the exchange must stop after the report" + ); + tokio::time::advance(Duration::from_micros(100)).await; + let error = match poll_until_idle(invoke.as_mut()) { + Some(Err(error)) => error, + Some(Ok(_)) => panic!("a reply must not start from a late error report"), + None => panic!("a report written after the allowance must fail before the timer fires"), + }; + let HostError::Failed { + kind, + model: Some(model), + .. + } = &error + else { + panic!("{error:?}"); + }; + assert_eq!(*kind, HostErrorKind::Transport); + assert_eq!(model.kind, ModelFailureKind::Network); + assert_eq!(model.status, None); + assert_eq!( + model.reason.as_deref(), + Some("no response headers arrived within 300 seconds of sending the request") + ); +} + /// A report written exactly at the allowance is on time in either arm: the /// comparison includes the instant, and the reply starts from it. #[tokio::test(start_paused = true)] From df6c0b9675264bf32bb2b6ac4e77a89685e0c8af Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 10:12:07 +0800 Subject: [PATCH 4/5] test(aimux): pin an exchange that completes after the header allowance The exchange can publish the header report and finish in the same poll, after the report arm was polled while the channel was still empty: the compatible provider returns its stream at the headers, and a non-2xx body that has already ended lets the exchange fail in that poll. Pin a late report in both cases, an exchange failure with no report keeping its own classification, and a report written exactly at the allowance still starting the reply. --- crates/dim-agent-aimux/src/driver/tests.rs | 258 +++++++++++++++++++++ 1 file changed, 258 insertions(+) diff --git a/crates/dim-agent-aimux/src/driver/tests.rs b/crates/dim-agent-aimux/src/driver/tests.rs index 78219c6e45..7589949d8c 100644 --- a/crates/dim-agent-aimux/src/driver/tests.rs +++ b/crates/dim-agent-aimux/src/driver/tests.rs @@ -98,6 +98,69 @@ fn driver(fetch: Arc) -> AimuxDriver { } } +fn driver_with(fetch: FetchFunction) -> AimuxDriver { + AimuxDriver { + files: None, + identity: ModelIdentity::default(), + transport: ReqwestFetch::default(), + fetch, + generation: CancellationToken::new(), + tasks: TaskTracker::new(), + streams: Mutex::new(Vec::new()), + requests: tokio::sync::Semaphore::new(4), + } +} + +/// A transport whose reply body is already closed: an exchange that reads a +/// non-2xx body completes in the poll that produced the headers. +struct EndedBodyFetch { + reply: Mutex>>, +} + +#[derive(Debug)] +struct EndedBodyReply { + status: http::StatusCode, + headers: http::HeaderMap, +} + +#[async_trait::async_trait] +impl Fetch for EndedBodyFetch { + async fn fetch(&self, _: FetchRequest) -> Result { + let reply = self + .reply + .lock() + .unwrap() + .take() + .expect("one scripted reply per exchange"); + let reply = reply.await.expect("the scripted reply is released"); + Ok(FetchResponse { + status: reply.status, + headers: reply.headers, + url: url::Url::parse("http://aimux.test/v1").unwrap(), + body: futures_util::stream::empty::>().boxed(), + }) + } +} + +/// A transport the test fails itself: the exchange reports the error the test +/// releases, and no response headers were produced to report. +struct FailingFetch { + reply: Mutex>>, +} + +#[async_trait::async_trait] +impl Fetch for FailingFetch { + async fn fetch(&self, _: FetchRequest) -> Result { + let error = self + .reply + .lock() + .unwrap() + .take() + .expect("one scripted failure per exchange"); + Err(error.await.expect("the scripted failure is released")) + } +} + fn request() -> ModelRequest { ModelRequest::new("local", "test-model", vec![Message::text(Role::User, "hi")]) } @@ -808,3 +871,198 @@ async fn a_header_report_written_at_the_allowance_stays_on_time() { .expect("the first event must deliver text"); assert!(matches!(text, ModelChunk::Text(text) if text == "hello")); } + +/// The compatible provider returns its stream at the headers, so the exchange +/// completes in the poll that publishes a report written after the allowance: +/// the exchange arm must judge that report before it returns the stream. +#[tokio::test(start_paused = true)] +async fn a_compatible_exchange_completing_after_its_allowance_is_late() { + let (fetch, reply) = scripted(); + let driver = driver(fetch); + // Half a tick puts the allowance between two ticks, so the timer fires up + // to one tick after it. + tokio::time::advance(Duration::from_micros(500)).await; + let mut invoke = driver.invoke( + Arc::new(request()), + connection(ModelProtocol::OpenaiCompatible), + CancellationToken::new(), + ); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the request must wait for its response headers" + ); + // The exchange is polled 0.2 ms after the allowance, before its timer. + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT + Duration::from_micros(200)).await; + reply + .send(ScriptedReply { + status: http::StatusCode::OK, + headers: headers("text/event-stream"), + body: ScriptedBody::default(), + }) + .unwrap(); + // One poll reports the headers and returns the stream: there is no second + // exchange poll to read the report in. + let error = match poll_once(invoke.as_mut()) { + Poll::Ready(Err(error)) => error, + Poll::Ready(Ok(_)) => panic!("a reply must not start from a late report"), + Poll::Pending => panic!("the exchange completion must be judged in the same poll"), + }; + let HostError::Failed { + kind, + model: Some(model), + .. + } = &error + else { + panic!("{error:?}"); + }; + assert_eq!(*kind, HostErrorKind::Transport); + assert_eq!(model.kind, ModelFailureKind::Network); + assert_eq!( + model.reason.as_deref(), + Some("no response headers arrived within 300 seconds of sending the request") + ); +} + +/// A non-2xx reply whose error body is already at EOF reads that body and +/// fails in the poll that publishes its report: while still awaiting headers, +/// the late report ends the wait as missing headers even though the exchange +/// is ready in that same poll. +#[tokio::test(start_paused = true)] +async fn a_late_error_report_with_a_finished_body_fails_as_missing_headers() { + let (sender, receiver) = tokio::sync::oneshot::channel(); + let driver = driver_with(Arc::new(EndedBodyFetch { + reply: Mutex::new(Some(receiver)), + })); + tokio::time::advance(Duration::from_micros(500)).await; + let mut invoke = driver.invoke( + Arc::new(request()), + connection(ModelProtocol::OpenaiChat), + CancellationToken::new(), + ); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the request must wait for its response headers" + ); + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT + Duration::from_micros(200)).await; + sender + .send(EndedBodyReply { + status: http::StatusCode::UNAUTHORIZED, + headers: headers("application/json"), + }) + .unwrap(); + let error = match poll_once(invoke.as_mut()) { + Poll::Ready(Err(error)) => error, + Poll::Ready(Ok(_)) => panic!("a reply must not start from a late error report"), + Poll::Pending => panic!("the completed error body must fail the request in this poll"), + }; + let HostError::Failed { + kind, + model: Some(model), + .. + } = &error + else { + panic!("{error:?}"); + }; + assert_eq!(*kind, HostErrorKind::Transport); + assert_eq!(model.kind, ModelFailureKind::Network); + assert_eq!(model.status, None); + assert_eq!( + model.reason.as_deref(), + Some("no response headers arrived within 300 seconds of sending the request") + ); +} + +/// An exchange failure with no header report keeps its own classification: +/// while the task still awaits headers, a transport failure released after the +/// allowance is not mistaken for missing headers. +#[tokio::test(start_paused = true)] +async fn an_exchange_failure_without_a_report_keeps_its_error() { + let (sender, receiver) = tokio::sync::oneshot::channel(); + let driver = driver_with(Arc::new(FailingFetch { + reply: Mutex::new(Some(receiver)), + })); + tokio::time::advance(Duration::from_micros(500)).await; + let mut invoke = driver.invoke( + Arc::new(request()), + connection(ModelProtocol::OpenaiChat), + CancellationToken::new(), + ); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the request must wait for its transport" + ); + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT + Duration::from_micros(200)).await; + sender + .send(FetchError::Connect( + "the connection was refused".to_string().into(), + )) + .unwrap(); + let error = match poll_once(invoke.as_mut()) { + Poll::Ready(Err(error)) => error, + Poll::Ready(Ok(_)) => panic!("a failed exchange must not start a stream"), + Poll::Pending => panic!("a transport failure must end the request without a report"), + }; + let HostError::Failed { + kind, + model: Some(model), + .. + } = &error + else { + panic!("{error:?}"); + }; + assert_eq!( + *kind, + HostErrorKind::Http { + status: None, + code: None, + } + ); + assert_eq!(model.kind, ModelFailureKind::Network); + assert_eq!(model.reason.as_deref(), Some("the connection was refused")); +} + +/// A compatible exchange that completes exactly at the allowance is on time: +/// the comparison includes the instant, so the reply still starts and delivers +/// its text. +#[tokio::test(start_paused = true)] +async fn a_compatible_exchange_completing_at_the_allowance_starts() { + let (fetch, reply) = scripted(); + let body = ScriptedBody::default(); + let driver = driver(fetch); + tokio::time::advance(Duration::from_micros(500)).await; + let mut invoke = driver.invoke( + Arc::new(request()), + connection(ModelProtocol::OpenaiCompatible), + CancellationToken::new(), + ); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the request must wait for its response headers" + ); + // The exchange is polled exactly at the allowance, still before its timer. + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT).await; + reply + .send(ScriptedReply { + status: http::StatusCode::OK, + headers: headers("text/event-stream"), + body: body.clone(), + }) + .unwrap(); + let mut stream = match poll_once(invoke.as_mut()) { + Poll::Ready(Ok(stream)) => stream, + Poll::Ready(Err(error)) => panic!("a report at the allowance must not be late: {error:?}"), + Poll::Pending => panic!("the exchange completion must be judged in the same poll"), + }; + body.push(format!( + "data: {}\n\n", + json!({"id": "remote-id", "choices": [{"index": 0, "delta": {"content": "hello"}, "finish_reason": Value::Null}]}) + )); + let start = next_chunk(&mut stream) + .expect("the reply must deliver its start") + .expect("the reply must not fail before its start"); + assert!(matches!(start, ModelChunk::MessageStart { .. })); + let text = next_chunk(&mut stream) + .expect("the reply must deliver its text") + .expect("the first event must deliver text"); + assert!(matches!(text, ModelChunk::Text(text) if text == "hello")); +} From 5e40aa45af3f884d65dbd79e1c6fbadd75e28319 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 10:13:05 +0800 Subject: [PATCH 5/5] fix(aimux): judge a queued header report when the exchange completes The exchange can publish the header report and finish in the same poll, after the report arm saw an empty channel, so a late report could start a stream or keep the HTTP status of a non-2xx reply. While the headers are still awaited, consume a queued report in the exchange arm and judge it by the instant the transport reported it, with the comparison the deadline and report arms use; an exchange failure with no report is returned unchanged. The select order is unchanged. --- crates/dim-agent-aimux/src/driver.rs | 33 +++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/crates/dim-agent-aimux/src/driver.rs b/crates/dim-agent-aimux/src/driver.rs index 6953e49a90..fddbec471e 100644 --- a/crates/dim-agent-aimux/src/driver.rs +++ b/crates/dim-agent-aimux/src/driver.rs @@ -895,17 +895,38 @@ impl ModelDriver for AimuxDriver { } } } - result = &mut exchange => match result - .map_err(|error| stream::error(name_redirect_target(error), &cancel)) - { - Ok(result) => break result, - Err(error) => { + result = &mut exchange => { + // The exchange can publish the headers and complete + // in this poll, after the report arm found the + // channel empty: while the headers are still + // awaited, judge a queued report by its instant + // here too. + if awaiting_headers + && let Ok(report) = response.try_recv() + && report.received > deadline_at + { + abort.abort(); + let error = stream::idle_failure(format!( + "no response headers arrived within {} seconds of sending the request", + stream::STREAM_IDLE_TIMEOUT.as_secs() + )); if let Some(pending) = pending.as_mut() { pending.failed(&error.to_string()); } return Err(error); } - }, + match result.map_err(|error| { + stream::error(name_redirect_target(error), &cancel) + }) { + Ok(result) => break result, + Err(error) => { + if let Some(pending) = pending.as_mut() { + pending.failed(&error.to_string()); + } + return Err(error); + } + } + } } } };