diff --git a/crates/dim-agent-aimux/src/driver.rs b/crates/dim-agent-aimux/src/driver.rs index 6de11c8f39..fddbec471e 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; @@ -882,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); + } + } + } } } }; diff --git a/crates/dim-agent-aimux/src/driver/tests.rs b/crates/dim-agent-aimux/src/driver/tests.rs index c2f4b4db1a..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")]) } @@ -595,3 +658,411 @@ 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 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)] +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")); +} + +/// 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")); +} 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 状态和该状态对应的类别失败,而不是变成空闲的网络失败。连接原来可选的整请求超时不变,和这几段上限是两件事。