diff --git a/crates/dim-agent-aimux/Cargo.toml b/crates/dim-agent-aimux/Cargo.toml index e72476c627..095e5fe826 100644 --- a/crates/dim-agent-aimux/Cargo.toml +++ b/crates/dim-agent-aimux/Cargo.toml @@ -37,6 +37,7 @@ dim-agent-runtime = { workspace = true, features = ["testing"] } axum = { workspace = true, features = ["json"] } futures = "0.3" wiremock = "0.6" +tokio = { workspace = true, features = ["test-util"] } [lints] workspace = true diff --git a/crates/dim-agent-aimux/src/config.rs b/crates/dim-agent-aimux/src/config.rs index 6c2d931982..d512830495 100644 --- a/crates/dim-agent-aimux/src/config.rs +++ b/crates/dim-agent-aimux/src/config.rs @@ -1,4 +1,4 @@ -use dim_agent_capabilities::host::HostError; +use dim_agent_capabilities::host::{HostError, ModelNetwork}; use dim_agent_runtime::ModelId; use dim_agent_types::ModelConfig; use serde::Deserialize; @@ -42,6 +42,10 @@ pub struct ProviderConfig { pub kind: ProviderKind, pub api_key_env: Option, pub base_url: String, + /// The connection's transport facts: the proxy every request goes through, + /// and the total timeout one request may spend, its response body included. + #[serde(default)] + pub network: ModelNetwork, #[serde(default)] pub headers: HashMap, pub compatible: Option, diff --git a/crates/dim-agent-aimux/src/driver.rs b/crates/dim-agent-aimux/src/driver.rs index f95e795400..6de11c8f39 100644 --- a/crates/dim-agent-aimux/src/driver.rs +++ b/crates/dim-agent-aimux/src/driver.rs @@ -14,7 +14,7 @@ use aimux_providers::{ }; use dim_agent_capabilities::host::*; use dim_agent_types::ModelRequest; -use futures_util::Stream; +use futures_util::{Stream, StreamExt}; use std::{ collections::HashMap, pin::Pin, @@ -250,6 +250,66 @@ fn anthropic_base_url(base_url: &str) -> String { } } +/// What the transport saw when it produced the response headers. +struct ResponseReport { + status: http::StatusCode, + /// The clock reading at which the exchange produced the headers. A + /// deadline is judged against this reading, not against the next poll. + received: tokio::time::Instant, +} + +/// The transport of one model call, watched by its driver. +/// +/// The driver cannot see how far a provider has got inside `do_stream`: some +/// providers (OpenAI Chat, Anthropic, Gemini, xAI Responses) read one stream +/// event after the headers before they return, the OpenAI Responses provider +/// reads until its SDK's startup scan finds output, and the compatible and +/// Bedrock providers return at the headers, so a deadline around the whole +/// call cannot tell a late set of headers from a late stream start. The driver +/// only sees the events the stream produces, so this decorator reports the +/// status and the instant the transport produced it. +/// +/// It also bounds a non-2xx body: the provider reads that body before it +/// returns the failure, and a stalled body would otherwise outlive the +/// request. The read is a short diagnostic, so it gets the allowance once in +/// total rather than per chunk: an idle bound would let a trickle extend it. +/// When the allowance expires the body ends, and the provider reports the HTTP +/// status it already received with the bytes that arrived. +struct ResponseWatch { + inner: FetchFunction, + status: Mutex>>, +} + +#[async_trait::async_trait] +impl Fetch for ResponseWatch { + async fn fetch(&self, request: FetchRequest) -> Result { + let response = self.inner.fetch(request).await?; + let received = tokio::time::Instant::now(); + if let Some(status) = self.status.lock().unwrap().take() { + let _ = status.send(ResponseReport { + status: response.status(), + received, + }); + } + if response.status().is_success() { + return Ok(response); + } + let FetchResponse { + status, + headers, + url, + body, + } = response; + let deadline = Box::pin(tokio::time::sleep(stream::STREAM_IDLE_TIMEOUT)); + Ok(FetchResponse { + status, + headers, + url, + body: body.take_until(deadline).boxed(), + }) + } +} + /// The transport a non-conversational call uses: the same client, redirect /// policy and connection facts as a chat call to the same model. /// @@ -514,6 +574,22 @@ fn build_model( } } +/// Why the wait after the response headers expired: the headers are in, but +/// the stream has not started. Providers that peek at the stream read one +/// event before they return it; the OpenAI Responses SDK reads response +/// metadata first, so its wait ends at the stream's start, not at an event +/// the driver can see. +fn headers_arrived_reason(protocol: ModelProtocol) -> String { + let ended = match protocol { + ModelProtocol::OpenaiResponses => "the stream did not start", + _ => "no stream event followed", + }; + format!( + "the response headers arrived, but {ended} within {} seconds", + stream::STREAM_IDLE_TIMEOUT.as_secs() + ) +} + pub(crate) struct AimuxDriver { files: Option>, /// The identity this driver's model requests carry, owned by the Aimux @@ -632,6 +708,11 @@ impl ModelDriver for AimuxDriver { } else { fetch(&self.transport, network, query) }; + let (report, mut response) = tokio::sync::oneshot::channel(); + let fetch: FetchFunction = Arc::new(ResponseWatch { + inner: fetch, + status: Mutex::new(Some(report)), + }); if preset == Some(OPENAI_CODEX_PRESET) && protocol != ModelProtocol::OpenaiResponses { return Err(HostError::classified( HostErrorKind::InvalidRequest, @@ -720,34 +801,100 @@ impl ModelDriver for AimuxDriver { capture.input(&options, model.provider(), &request.model_id); capture.pending() }); - let result = tokio::select! { - biased; - _ = self.generation.cancelled() => { - abort.abort(); - if let Some(pending) = pending.as_mut() { pending.cancelled(); } - return Err(HostError::classified(HostErrorKind::OwnerClosed, "Aimux owner is closed")); - } - _ = cancel.cancelled() => { - abort.abort(); - if let Some(pending) = pending.as_mut() { pending.cancelled(); } - return Err(HostError::Cancelled("Model invocation cancelled".into())); - } - result = async { + // Three waits carry the idle allowance: sending the request until + // the response headers, the headers until the stream starts (a + // provider may read the stream before it returns it, and the + // Responses SDK reads response metadata first), and one part + // until the next. `ResponseWatch` reports the headers with the + // instant it produced them, so the second wait runs from receipt. + let result = { + let mut awaiting_headers = true; + let mut headers_arrived = false; + let mut bounded = true; + let mut deadline_at = tokio::time::Instant::now() + stream::STREAM_IDLE_TIMEOUT; + let mut deadline = Box::pin(tokio::time::sleep_until(deadline_at)); + let exchange = async { match &recording { Some(capture) => capture.scope(model.do_stream(&options)).await, None => model.do_stream(&options).await, } - } => match result - .map_err(|error| stream::error(name_redirect_target(error), &cancel)) - { - Ok(result) => result, - Err(error) => { - if let Some(pending) = pending.as_mut() { - pending.failed(&error.to_string()); + }; + tokio::pin!(exchange); + loop { + tokio::select! { + biased; + _ = self.generation.cancelled() => { + abort.abort(); + if let Some(pending) = pending.as_mut() { pending.cancelled(); } + return Err(HostError::classified(HostErrorKind::OwnerClosed, "Aimux owner is closed")); + } + _ = cancel.cancelled() => { + abort.abort(); + if let Some(pending) = pending.as_mut() { pending.cancelled(); } + return Err(HostError::Cancelled("Model invocation cancelled".into())); + } + _ = &mut deadline, if bounded => { + // A report the transport wrote before the deadline + // is on time even when this poll is late. + if awaiting_headers + && let Ok(report) = response.try_recv() + && report.received <= deadline_at + { + awaiting_headers = false; + headers_arrived = true; + if report.status.is_success() { + deadline_at = report.received + stream::STREAM_IDLE_TIMEOUT; + deadline.as_mut().reset(deadline_at); + continue; + } + // A non-2xx reply fails with the status it + // carries; the exchange reports it. + bounded = false; + continue; + } + abort.abort(); + let error = stream::idle_failure(if headers_arrived { + headers_arrived_reason(protocol) + } else { + 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); } - return Err(error); + report = &mut response, if awaiting_headers => { + awaiting_headers = false; + if let Ok(report) = report { + headers_arrived = true; + if report.status.is_success() { + deadline_at = report.received + stream::STREAM_IDLE_TIMEOUT; + deadline.as_mut().reset(deadline_at); + } else { + // A non-2xx reply fails with the status it + // carries; its body is bounded by the + // transport, and an idle failure here would + // discard that status. + bounded = false; + } + } + } + result = &mut exchange => 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); + } + }, } - }, + } }; let result = match recording { Some(capture) => { @@ -821,3 +968,6 @@ impl Stream for OwnedStream { result } } + +#[cfg(test)] +mod tests; diff --git a/crates/dim-agent-aimux/src/driver/tests.rs b/crates/dim-agent-aimux/src/driver/tests.rs new file mode 100644 index 0000000000..c2f4b4db1a --- /dev/null +++ b/crates/dim-agent-aimux/src/driver/tests.rs @@ -0,0 +1,597 @@ +use std::{ + collections::VecDeque, + future::Future, + sync::atomic::{AtomicBool, Ordering}, + task::{Wake, Waker}, +}; + +use axum::body::Bytes; +use dim_agent_types::{Message, ModelFailureKind, Role}; +use futures_util::stream::BoxStream; +use futures_util::{Stream, StreamExt}; +use serde_json::{Value, json}; + +use super::*; + +/// A transport the test answers itself: the exchange waits for the reply the +/// test releases, and the reply's body yields the bytes the test pushes. +struct ScriptedFetch { + reply: Mutex>>, +} + +#[derive(Debug)] +struct ScriptedReply { + status: http::StatusCode, + headers: http::HeaderMap, + body: ScriptedBody, +} + +#[async_trait::async_trait] +impl Fetch for ScriptedFetch { + 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: reply.body.stream(), + }) + } +} + +#[derive(Clone, Debug, Default)] +struct ScriptedBody { + chunks: Arc>>, +} + +impl ScriptedBody { + fn push(&self, chunk: impl Into) { + self.chunks.lock().unwrap().push_back(chunk.into()); + } + fn stream(self) -> BoxStream<'static, Result> { + Box::pin(ScriptedBodyStream(self)) + } +} + +struct ScriptedBodyStream(ScriptedBody); + +impl Stream for ScriptedBodyStream { + type Item = Result; + + fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + match self.get_mut().0.chunks.lock().unwrap().pop_front() { + Some(chunk) => Poll::Ready(Some(Ok(chunk))), + None => Poll::Pending, + } + } +} + +fn scripted() -> ( + Arc, + tokio::sync::oneshot::Sender, +) { + let (sender, receiver) = tokio::sync::oneshot::channel(); + ( + Arc::new(ScriptedFetch { + reply: Mutex::new(Some(receiver)), + }), + sender, + ) +} + +fn driver(fetch: Arc) -> 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), + } +} + +fn request() -> ModelRequest { + ModelRequest::new("local", "test-model", vec![Message::text(Role::User, "hi")]) +} + +fn connection(protocol: ModelProtocol) -> ModelConnection { + ModelConnection::Http(HttpModelConnection { + protocol, + base_url: "http://aimux.test/v1".into(), + network: Default::default(), + headers: Default::default(), + bearer: None, + api_key: None, + preset: None, + }) +} + +fn headers(content_type: &'static str) -> http::HeaderMap { + let mut headers = http::HeaderMap::new(); + headers.insert( + http::header::CONTENT_TYPE, + http::HeaderValue::from_static(content_type), + ); + headers +} + +struct WakeFlag(AtomicBool); + +impl Wake for WakeFlag { + fn wake(self: Arc) { + self.0.store(true, Ordering::SeqCst); + } +} + +/// Polls `future` the way an executor would and stops at the first `Pending` +/// poll that woke nothing: the future then waits only for the test's next +/// signal, so the clock can move without skipping work that was already ready. +fn poll_until_idle(mut future: Pin<&mut F>) -> Option { + let flag = Arc::new(WakeFlag(AtomicBool::new(false))); + let waker = Waker::from(flag.clone()); + let mut context = Context::from_waker(&waker); + loop { + flag.0.store(false, Ordering::SeqCst); + match future.as_mut().poll(&mut context) { + Poll::Ready(output) => return Some(output), + Poll::Pending if !flag.0.load(Ordering::SeqCst) => return None, + Poll::Pending => {} + } + } +} + +/// Polls `future` once and leaves any wake-up it registers to the next poll: +/// the task is not run again until the test says so. +fn poll_once(future: Pin<&mut F>) -> Poll { + let waker = Waker::from(Arc::new(WakeFlag(AtomicBool::new(false)))); + future.poll(&mut Context::from_waker(&waker)) +} + +fn next_chunk(stream: &mut ModelStream) -> Option> { + let mut next = Box::pin(stream.next()); + poll_until_idle(next.as_mut()).flatten() +} + +/// Headers inside the header allowance and a first event after the whole +/// request allowance still starts: the wait for the headers and the wait for +/// the first event are bounded separately. +#[tokio::test(start_paused = true)] +async fn a_delayed_header_reply_still_gets_its_first_event_allowance() { + let (fetch, reply) = scripted(); + let body = ScriptedBody::default(); + let driver = driver(fetch); + 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_secs(1)).await; + reply + .send(ScriptedReply { + status: http::StatusCode::OK, + headers: headers("text/event-stream"), + body: body.clone(), + }) + .unwrap(); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the reply must wait for its first event" + ); + tokio::time::advance(Duration::from_secs(2)).await; + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the first event gets its own allowance after the headers" + ); + 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 first event must start the reply") + .expect("the reply must start after the first event"); + 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")); +} + +/// Headers inside the allowance and no first event inside its own allowance: +/// the reply fails as a network failure naming the missing event, not the +/// headers. +#[tokio::test(start_paused = true)] +async fn a_first_event_past_its_own_allowance_fails_as_a_network_failure() { + let (fetch, reply) = scripted(); + let driver = driver(fetch); + 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" + ); + reply + .send(ScriptedReply { + status: http::StatusCode::OK, + headers: headers("text/event-stream"), + body: ScriptedBody::default(), + }) + .unwrap(); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the reply must wait for its first event" + ); + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT).await; + let error = match poll_until_idle(invoke.as_mut()) { + Some(Err(error)) => error, + Some(Ok(_)) => panic!("a reply without a first event must fail"), + None => panic!("a reply without a first event must fail within the allowance"), + }; + 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("the response headers arrived, but no stream event followed within 300 seconds") + ); +} + +/// A non-2xx response whose error body stalls is read under its own allowance: +/// the request fails with the HTTP status and the kind that status names, not +/// as an idle network failure that discards a known status. +#[tokio::test(start_paused = true)] +async fn a_stalled_error_body_keeps_the_response_status() { + let (fetch, reply) = scripted(); + let body = ScriptedBody::default(); + body.push(r#"{"error":{"message":"Expired credential""#); + let driver = driver(fetch); + 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" + ); + reply + .send(ScriptedReply { + status: http::StatusCode::UNAUTHORIZED, + headers: headers("application/json"), + body, + }) + .unwrap(); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the error body must hold the request open" + ); + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT).await; + let error = match poll_until_idle(invoke.as_mut()) { + Some(Err(error)) => error, + Some(Ok(_)) => panic!("a 401 response must fail the request"), + None => panic!("a stalled error body must fail within the allowance"), + }; + let HostError::Failed { + kind, + model: Some(model), + .. + } = &error + else { + panic!("{error:?}"); + }; + assert_eq!( + *kind, + HostErrorKind::Http { + status: Some(401), + code: None, + } + ); + assert_eq!(model.kind, ModelFailureKind::AuthRejected); + assert_eq!(model.status, Some(401)); +} + +/// The transport produces the headers at 299 seconds but the task is not +/// polled again until after the header allowance: the report carries the +/// instant it was written, so the reply starts and its first event is +/// measured from that instant. +#[tokio::test(start_paused = true)] +async fn a_header_report_read_past_its_allowance_is_on_time() { + let (fetch, reply) = scripted(); + let body = ScriptedBody::default(); + let driver = driver(fetch); + 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_secs(1)).await; + reply + .send(ScriptedReply { + status: http::StatusCode::OK, + headers: headers("text/event-stream"), + body: body.clone(), + }) + .unwrap(); + // One poll lets the transport report the headers at 299 seconds; the task + // is not polled again until 301, past the header allowance. + assert!( + poll_once(invoke.as_mut()).is_pending(), + "the exchange must stop after the headers" + ); + tokio::time::advance(Duration::from_secs(2)).await; + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "a report written inside the header 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 first event must start the reply") + .expect("the reply must start after the first event"); + 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")); +} + +/// A 401 produced at 299 seconds and read after the header allowance keeps +/// its status: the report is on time, and the stalled error body still ends +/// under its own allowance. +#[tokio::test(start_paused = true)] +async fn a_header_report_read_past_its_allowance_keeps_the_response_status() { + let (fetch, reply) = scripted(); + let body = ScriptedBody::default(); + body.push(r#"{"error":{"message":"Expired credential"#); + let driver = driver(fetch); + 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" + ); + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT - Duration::from_secs(1)).await; + reply + .send(ScriptedReply { + status: http::StatusCode::UNAUTHORIZED, + headers: headers("application/json"), + body, + }) + .unwrap(); + assert!( + poll_once(invoke.as_mut()).is_pending(), + "the exchange must stop after the headers" + ); + tokio::time::advance(Duration::from_secs(2)).await; + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "a report written inside the header allowance must not become a timeout" + ); + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT).await; + let error = match poll_until_idle(invoke.as_mut()) { + Some(Err(error)) => error, + Some(Ok(_)) => panic!("a 401 response must fail the request"), + None => panic!("a stalled error body must fail within its allowance"), + }; + let HostError::Failed { + kind, + model: Some(model), + .. + } = &error + else { + panic!("{error:?}"); + }; + assert_eq!( + *kind, + HostErrorKind::Http { + status: Some(401), + code: None, + } + ); + assert_eq!(model.kind, ModelFailureKind::AuthRejected); + assert_eq!(model.status, Some(401)); +} + +/// The stream allowance runs from the instant the transport reported the +/// headers, not from the poll that read the report: headers reported at 299 +/// seconds and read at 301 end the wait at 599, not at 601. +#[tokio::test(start_paused = true)] +async fn a_header_report_starts_the_stream_allowance_at_its_instant() { + let (fetch, reply) = scripted(); + let body = ScriptedBody::default(); + let driver = driver(fetch); + 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_secs(1)).await; + reply + .send(ScriptedReply { + status: http::StatusCode::OK, + headers: headers("text/event-stream"), + body, + }) + .unwrap(); + assert!( + poll_once(invoke.as_mut()).is_pending(), + "the exchange must stop after the headers" + ); + tokio::time::advance(Duration::from_secs(2)).await; + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "a report written inside the header allowance must not be read as late" + ); + tokio::time::advance(Duration::from_secs(298)).await; + let error = match poll_until_idle(invoke.as_mut()) { + Some(Err(error)) => error, + Some(Ok(_)) => panic!("a reply without a first event must fail"), + None => panic!("the stream allowance must end 300 seconds after the 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("the response headers arrived, but no stream event followed within 300 seconds") + ); +} + +/// The OpenAI Responses startup scan decodes response metadata before it +/// returns the stream. The wait after the headers ends when the stream +/// starts, and its failure says so instead of reporting a missing event. +#[tokio::test(start_paused = true)] +async fn a_responses_startup_past_its_allowance_names_the_stream_start() { + let (fetch, reply) = scripted(); + let body = ScriptedBody::default(); + let driver = driver(fetch); + let mut invoke = driver.invoke( + Arc::new(request()), + connection(ModelProtocol::OpenaiResponses), + CancellationToken::new(), + ); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the request must wait for its response headers" + ); + reply + .send(ScriptedReply { + status: http::StatusCode::OK, + headers: headers("text/event-stream"), + body: body.clone(), + }) + .unwrap(); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the reply must wait for the start of its stream" + ); + body.push(format!( + "data: {}\n\n", + json!({"type": "response.created", "response": {"id": "resp-1", "created_at": 1, "model": "test-model"}}) + )); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "decoded metadata must not start the stream" + ); + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT).await; + let error = match poll_until_idle(invoke.as_mut()) { + Some(Err(error)) => error, + Some(Ok(_)) => panic!("a stream that never starts must fail"), + None => panic!("a stream that never starts must fail within the allowance"), + }; + 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("the response headers arrived, but the stream did not start within 300 seconds") + ); +} + +/// A Responses reply that decodes metadata first and delivers output inside +/// the allowance starts and delivers that output. +#[tokio::test(start_paused = true)] +async fn a_responses_start_inside_its_allowance_delivers_the_output() { + let (fetch, reply) = scripted(); + let body = ScriptedBody::default(); + let driver = driver(fetch); + let mut invoke = driver.invoke( + Arc::new(request()), + connection(ModelProtocol::OpenaiResponses), + CancellationToken::new(), + ); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the request must wait for its response headers" + ); + reply + .send(ScriptedReply { + status: http::StatusCode::OK, + headers: headers("text/event-stream"), + body: body.clone(), + }) + .unwrap(); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "the reply must wait for the start of its stream" + ); + body.push(format!( + "data: {}\n\n", + json!({"type": "response.created", "response": {"id": "resp-1", "created_at": 1, "model": "test-model"}}) + )); + assert!( + poll_until_idle(invoke.as_mut()).is_none(), + "decoded metadata must not start the stream" + ); + tokio::time::advance(stream::STREAM_IDLE_TIMEOUT - Duration::from_secs(1)).await; + for event in [ + json!({"type": "response.output_item.added", "output_index": 0, "item": {"type": "message", "id": "msg-1", "role": "assistant", "content": []}}), + json!({"type": "response.output_text.delta", "item_id": "msg-1", "output_index": 0, "content_index": 0, "delta": "hello"}), + ] { + body.push(format!("data: {event}\n\n")); + } + let mut stream = poll_until_idle(invoke.as_mut()) + .expect("the output must start the reply") + .expect("the reply must start after the output"); + let mut text = String::new(); + while let Some(chunk) = next_chunk(&mut stream) { + if let ModelChunk::Text(part) = chunk.expect("the reply must not fail") { + text.push_str(&part); + } + } + assert_eq!(text, "hello"); +} diff --git a/crates/dim-agent-aimux/src/models.rs b/crates/dim-agent-aimux/src/models.rs index ff3033bcfc..ca75fb5501 100644 --- a/crates/dim-agent-aimux/src/models.rs +++ b/crates/dim-agent-aimux/src/models.rs @@ -1,6 +1,8 @@ use crate::config::{ModelConfigFile, ProviderKind}; use dim_agent_capabilities::context_model::{output_allowance, window_facts}; -use dim_agent_capabilities::host::{ContextModel, HostError, HostFuture, ResolveContextModel}; +use dim_agent_capabilities::host::{ + ContextModel, HostError, HostFuture, ModelNetwork, ResolveContextModel, +}; use dim_agent_runtime::ModelId; use dim_agent_types::{ModelCapabilities, ModelCapabilitySnapshot, ModelConfig, ModelRequest}; use std::collections::HashMap; @@ -13,6 +15,7 @@ pub(crate) struct Model { pub api_key_env: Option, pub defaults: ModelConfig, pub kind: ProviderKind, + pub network: ModelNetwork, pub preset: Option, pub context_window: u64, pub max_output_tokens: u64, @@ -47,6 +50,7 @@ impl AimuxModels { "Provider IDs must be nonempty and unique", )); } + validate_network(&provider.network, &provider.id)?; let url = url::Url::parse(&provider.base_url) .map_err(|_| HostError::failed(format!("Invalid baseUrl for {}", provider.id)))?; if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() { @@ -143,6 +147,7 @@ impl AimuxModels { api_key_env: provider.api_key_env.clone(), defaults, kind: provider.kind, + network: provider.network.clone(), preset: preset.clone(), context_window, max_output_tokens, @@ -219,6 +224,36 @@ impl AimuxModels { } } +/// The development file states the same connection facts a product record +/// does, with the same rules: an HTTP or HTTPS root proxy URL, and a positive +/// safe-integer timeout. A value the transport would refuse fails here, next to +/// the provider that states it. +fn validate_network(network: &ModelNetwork, provider: &str) -> Result<(), HostError> { + if let Some(proxy) = &network.proxy { + let root = url::Url::parse(proxy).is_ok_and(|url| { + matches!(url.scheme(), "http" | "https") + && url.host_str().is_some() + && url.query().is_none() + && url.fragment().is_none() + && matches!(url.path(), "" | "/") + }); + if !root { + return Err(HostError::failed(format!( + "Invalid proxy for {provider}: an HTTP or HTTPS root URL is required" + ))); + } + } + if network + .timeout_ms + .is_some_and(|value| value == 0 || value > dim_agent_types::JS_MAX_SAFE_INTEGER) + { + return Err(HostError::failed(format!( + "Invalid network timeout for {provider}: a positive safe integer is required" + ))); + } + Ok(()) +} + /// The model-file profile's window facts: the entry the request names, by /// provider and model id (ContextCompaction §5.1). impl ResolveContextModel for AimuxModels { diff --git a/crates/dim-agent-aimux/src/plugin.rs b/crates/dim-agent-aimux/src/plugin.rs index 450e6d9dac..981702f185 100644 --- a/crates/dim-agent-aimux/src/plugin.rs +++ b/crates/dim-agent-aimux/src/plugin.rs @@ -235,7 +235,7 @@ impl ResolveModelConnection for ConfiguredConnection { connection: ModelConnection::Http(HttpModelConnection { protocol: model.kind, base_url: model.base_url.clone(), - network: Default::default(), + network: model.network.clone(), headers: model.headers.clone(), bearer: if matches!( model.kind, diff --git a/crates/dim-agent-aimux/src/stream.rs b/crates/dim-agent-aimux/src/stream.rs index 221dbd1670..94376ac1e8 100644 --- a/crates/dim-agent-aimux/src/stream.rs +++ b/crates/dim-agent-aimux/src/stream.rs @@ -1,6 +1,9 @@ mod content; -use std::collections::{HashMap, HashSet}; +use std::{ + collections::{HashMap, HashSet}, + time::Duration, +}; use aimux_core::{ AbortSignal, AiMuxError, ApiCallErrorOrigin, ErrorCause, @@ -25,6 +28,25 @@ use tokio_util::sync::CancellationToken; use crate::request::ToolNames; +/// How long a request waits for each step of the reply before the connection +/// counts as lost. +/// +/// Five minutes matches the allowance other harnesses give a slow model step. +/// It bounds three waits: from sending the request until the response headers +/// arrive (the request body and any redirects count against it), from the +/// headers until the stream starts (a provider that peeks reads one stream +/// event before it returns; the OpenAI Responses SDK reads response metadata +/// first), and from one stream part to the next. The header wait ends, and the +/// second wait begins, at the instant the transport produces the headers, not +/// at the driver's next poll. Each wait gets the full allowance, so a slow +/// reply is never cut, however long it takes, while a half-open connection +/// fails as a network failure instead of holding the turn until an external +/// deadline; that failure is retried in place while the attempt committed +/// nothing. It also bounds reading the body of a non-2xx response, which is a +/// short diagnostic: that read gets the allowance once in total, because an +/// idle bound would let a trickle of bytes extend it. +pub(crate) const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(300); + pub(crate) fn convert( result: StreamResult, tool_names: ToolNames, @@ -81,6 +103,12 @@ pub(crate) fn convert( _ = cancel.cancelled() => { break Some(Err(HostError::Cancelled("Model request cancelled".into()))); } + _ = tokio::time::sleep(STREAM_IDLE_TIMEOUT) => { + break Some(Err(idle_failure(format!( + "the stream delivered nothing for {} seconds", + STREAM_IDLE_TIMEOUT.as_secs() + )))); + } next = stream.next() => next, } }; @@ -527,6 +555,35 @@ fn empty_reply() -> HostError { ) } +/// The failure of a request that waited [`STREAM_IDLE_TIMEOUT`] without the +/// reply starting or continuing. +/// +/// A connection that stays silent this long is treated as a lost transport, not +/// as a malformed reply: the request was never answered, so the retry policy +/// retries it like any other network failure while the attempt committed +/// nothing, and nothing published is replayed. +pub(crate) fn idle_failure(reason: String) -> HostError { + HostError::Failed { + message: ModelFailureKind::Network.line(Some(&reason)), + budget: None, + kind: HostErrorKind::Transport, + model: Some(Box::new(ModelFailureFacts { + kind: ModelFailureKind::Network, + reason: Some(reason), + status: None, + provider_code: None, + request_id: None, + cause: Vec::new(), + retry_after: None, + attempts: 1, + waited: Duration::ZERO, + retry_after_stop: None, + retry_forbidden: false, + })), + presentation: None, + } +} + fn content_filter_failure() -> HostError { reply_failure( ModelFailureKind::ContentFiltered, diff --git a/crates/dim-agent-aimux/src/stream/tests.rs b/crates/dim-agent-aimux/src/stream/tests.rs index 6b060408f5..e1d7e30b06 100644 --- a/crates/dim-agent-aimux/src/stream/tests.rs +++ b/crates/dim-agent-aimux/src/stream/tests.rs @@ -1,11 +1,13 @@ use std::{ collections::VecDeque, + future::Future, pin::Pin, sync::{ - Arc, + Arc, Mutex, atomic::{AtomicBool, Ordering}, }, task::{Context, Poll}, + time::Duration, }; use aimux_core::result::Source; @@ -102,6 +104,60 @@ async fn collect_or_stall(stream: ModelStream, case: &str) -> Vec (ModelStream, Feed) { + let parts = Arc::new(Mutex::new(VecDeque::new())); + let result = StreamResult { + stream: Box::pin(FeedStream { + parts: parts.clone(), + }), + request: None, + response: None, + }; + let stream = convert( + result, + ToolNames::default(), + ModelProtocol::OpenaiChat, + CancellationToken::new(), + AbortSignal::new(), + CancellationToken::new(), + tokio_util::task::TaskTracker::new().token(), + ); + (stream, Feed(parts)) +} + +struct Feed(Arc>>>); + +impl Feed { + fn push(&self, parts: Vec>) { + self.0.lock().unwrap().extend(parts); + } +} + +struct FeedStream { + parts: Arc>>>, +} + +impl Stream for FeedStream { + type Item = Result; + + fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + match self.parts.lock().unwrap().pop_front() { + Some(part) => Poll::Ready(Some(part)), + None => Poll::Pending, + } + } +} + +/// One poll of the next chunk, so a test can hold a wait open while it advances +/// the clock and feeds a part, then poll again where the idle deadline decides. +fn poll_once(stream: &mut ModelStream) -> Poll>> { + let mut next = Box::pin(stream.next()); + let mut context = Context::from_waker(futures_util::task::noop_waker_ref()); + next.as_mut().poll(&mut context) +} + fn start() -> StreamPart { StreamPart::StreamStart { warnings: vec![] } } @@ -1534,3 +1590,108 @@ async fn recorded_reasoning_tokens_reach_the_agent_usage() { "{recorded}" ); } + +/// The documented allowance: five minutes without a part is a lost connection. +const IDLE_ALLOWANCE: Duration = Duration::from_secs(300); + +/// A text block and one delta of it, as the parts a provider delivers. +fn text_part(delta: &str) -> Vec> { + vec![ + Ok(StreamPart::TextStart { + id: "text".into(), + provider_metadata: None, + }), + Ok(StreamPart::TextDelta { + id: "text".into(), + delta: delta.into(), + provider_metadata: None, + }), + ] +} + +/// The idle failure of one poll, asserted to carry the network kind and the +/// facts the retry policy reads. +fn idle_failure( + outcome: Poll>>, +) -> (String, ModelFailureFacts) { + let Poll::Ready(Some(Err(HostError::Failed { + kind, + message, + model, + .. + }))) = outcome + else { + panic!("a stream silent for the idle allowance fails"); + }; + assert_eq!(kind, HostErrorKind::Transport); + let facts = model.expect("the idle failure carries facts"); + assert_eq!(facts.kind, ModelFailureKind::Network); + (message, *facts) +} + +/// Five minutes without a part is a lost connection: the request fails as a +/// network failure, which the retry policy retries while nothing was committed. +#[tokio::test(start_paused = true)] +async fn a_stream_silent_for_the_idle_allowance_fails_as_a_network_failure() { + let (mut stream, feed) = feedable(); + feed.push(vec![Ok(start())]); + assert!(matches!( + poll_once(&mut stream), + Poll::Ready(Some(Ok(ModelChunk::MessageStart { .. }))) + )); + let mut waiting = Box::pin(stream.next()); + let mut context = Context::from_waker(futures_util::task::noop_waker_ref()); + assert!(waiting.as_mut().poll(&mut context).is_pending()); + tokio::time::advance(IDLE_ALLOWANCE).await; + let (message, facts) = idle_failure(waiting.as_mut().poll(&mut context)); + assert_eq!( + facts.reason.as_deref(), + Some("the stream delivered nothing for 300 seconds") + ); + assert!( + message.ends_with(ModelFailureKind::Network.action()), + "{message}" + ); +} + +/// A part that arrives inside the allowance restarts it, so a reply that keeps +/// streaming is never cut however long it takes. +#[tokio::test(start_paused = true)] +async fn a_part_inside_the_idle_allowance_keeps_the_stream_open() { + let (mut stream, feed) = feedable(); + feed.push(vec![Ok(start())]); + assert!(matches!( + poll_once(&mut stream), + Poll::Ready(Some(Ok(ModelChunk::MessageStart { .. }))) + )); + let mut context = Context::from_waker(futures_util::task::noop_waker_ref()); + let inside = IDLE_ALLOWANCE - Duration::from_millis(1); + for delta in ["first", "second"] { + let mut waiting = Box::pin(stream.next()); + assert!(waiting.as_mut().poll(&mut context).is_pending()); + tokio::time::advance(inside).await; + feed.push(text_part(delta)); + assert!(matches!( + waiting.as_mut().poll(&mut context), + Poll::Ready(Some(Ok(ModelChunk::Text(text)))) if text == delta + )); + } +} + +/// A deadline that has passed outranks a part ready at the same moment: the +/// connection was silent for the whole allowance even though data arrived. +#[tokio::test(start_paused = true)] +async fn an_idle_deadline_outranks_a_part_that_is_ready_at_the_same_time() { + let (mut stream, feed) = feedable(); + feed.push(vec![Ok(start())]); + assert!(matches!( + poll_once(&mut stream), + Poll::Ready(Some(Ok(ModelChunk::MessageStart { .. }))) + )); + let mut waiting = Box::pin(stream.next()); + let mut context = Context::from_waker(futures_util::task::noop_waker_ref()); + assert!(waiting.as_mut().poll(&mut context).is_pending()); + feed.push(text_part("ready")); + tokio::time::advance(IDLE_ALLOWANCE).await; + idle_failure(waiting.as_mut().poll(&mut context)); +} diff --git a/crates/dim-agent-aimux/tests/model_flow.rs b/crates/dim-agent-aimux/tests/model_flow.rs index ac40094567..e10675ca3a 100644 --- a/crates/dim-agent-aimux/tests/model_flow.rs +++ b/crates/dim-agent-aimux/tests/model_flow.rs @@ -872,6 +872,93 @@ fn configured_top_k_on_the_openai_chat_protocol_names_the_setting_and_the_altern AimuxModels::from_config(configuration("openai-compatible", Some(1.0))).unwrap(); } +/// The development file's `network` block states the same connection facts a +/// product record does, and refuses the values the transport cannot use. +#[test] +fn a_network_block_refuses_values_the_transport_cannot_use() { + let configuration = |network: Value| { + serde_json::from_value::(json!({ + "defaultModel": {"providerId": "local", "modelId": "test-model"}, + "providers": [{"id": "local", "kind": "openai-compatible", + "baseUrl": "http://127.0.0.1:9/v1", + "network": network, + "models": [{"id": "test-model", "contextWindow": 128_000, + "maxOutputTokens": 4096, "config": {"maxTokens": 4096}}]}] + })) + .unwrap() + }; + for network in [ + json!({"proxy": "socks5://localhost:1080"}), + json!({"proxy": "https://host/path"}), + json!({"proxy": "https://host?secret=value"}), + ] { + let error = AimuxModels::from_config(configuration(network.clone())) + .expect_err("a proxy the transport cannot use"); + assert_eq!( + error.to_string(), + "Invalid proxy for local: an HTTP or HTTPS root URL is required", + "{network}" + ); + } + for network in [ + json!({"timeoutMs": 0}), + json!({"timeoutMs": 9_007_199_254_740_992u64}), + ] { + let error = AimuxModels::from_config(configuration(network.clone())) + .expect_err("a timeout outside the safe integer range"); + assert_eq!( + error.to_string(), + "Invalid network timeout for local: a positive safe integer is required", + "{network}" + ); + } + for network in [ + json!({"proxy": "https://proxy.example.test/"}), + json!({"timeoutMs": 30_000}), + json!({}), + ] { + AimuxModels::from_config(configuration(network)).unwrap(); + } +} + +/// The block reaches the connection every request of the provider resolves, so +/// a development configuration can set the connection's proxy and timeout. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn the_network_block_reaches_the_connection_a_request_resolves() { + let server = TestServer::start().await; + let config: ModelConfigFile = serde_json::from_value(json!({ + "defaultModel": {"providerId": "local", "modelId": "test-model"}, + "providers": [{"id": "local", "kind": "openai-compatible", + "baseUrl": server.url, + "network": {"proxy": "http://127.0.0.1:9/", "timeoutMs": 45}, + "models": [{"id": "test-model", "contextWindow": 128_000, + "maxOutputTokens": 4096, "config": {"maxTokens": 4096}}]}] + })) + .unwrap(); + let agent = model_agent(Arc::new(AimuxModels::from_config(config).unwrap()), None).await; + let resolver = agent.root().get::().unwrap(); + let request = Arc::new(ModelRequest::new( + "local", + "test-model", + vec![Message::text(Role::User, "hi")], + )); + let resolved = resolver + .0 + .resolve(request, CancellationToken::new()) + .await + .unwrap(); + let ModelConnection::Http(connection) = resolved.connection else { + panic!("the development profile resolves an HTTP connection") + }; + assert_eq!( + connection.network.proxy.as_deref(), + Some("http://127.0.0.1:9/") + ); + assert_eq!(connection.network.timeout_ms, Some(45)); + agent.close().await.unwrap(); + server.close().await; +} + struct OverrideRequest { remove_tools: bool, timeline: rutis::host::Key, @@ -924,6 +1011,7 @@ async fn before_committed_request_controls_model_settings_and_tool_admission() { kind: dim_agent_aimux::config::ProviderKind::OpenaiCompatible, api_key_env: None, base_url: selected.url.clone(), + network: Default::default(), headers: Default::default(), compatible: None, models: vec![dim_agent_aimux::config::ModelEntry { @@ -1649,5 +1737,78 @@ async fn a_same_origin_redirect_chain_stops_at_the_limit() { .unwrap(); } +/// A provider that accepts the request and never sends the response headers +/// fails as a network failure once the idle allowance has passed, like a +/// stream that stops delivering parts. +#[tokio::test] +async fn a_wait_for_response_headers_past_the_idle_allowance_fails_as_a_network_failure() { + use tokio::io::AsyncReadExt; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let (accepted, received) = tokio::sync::oneshot::channel(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut head = Vec::new(); + let mut buffer = [0; 8192]; + loop { + let count = socket.read(&mut buffer).await.unwrap(); + assert_ne!(count, 0, "the client closed before sending its request"); + head.extend_from_slice(&buffer[..count]); + if head.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + accepted.send(()).unwrap(); + std::future::pending::<()>().await; + }); + let root = rutis::Ctx::root().unwrap(); + root.plugin(AimuxPlugin::default()).await.unwrap(); + let host = root.get::().unwrap(); + let driver = host.0.clone(); + let request = ModelRequest::new("local", "test-model", vec![Message::text(Role::User, "hi")]); + let connection = ModelConnection::Http(HttpModelConnection { + protocol: ModelProtocol::OpenaiCompatible, + base_url: base, + network: Default::default(), + headers: Default::default(), + bearer: None, + api_key: None, + preset: None, + }); + let invoke = tokio::spawn(async move { + driver + .invoke(Arc::new(request), connection, CancellationToken::new()) + .await + }); + received.await.unwrap(); + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(300)).await; + let outcome = tokio::time::timeout(Duration::from_secs(2), invoke) + .await + .expect("a request whose response headers never arrive must fail") + .expect("the request must not panic"); + let error = match outcome { + Ok(_) => panic!("the wait for the response headers must fail"), + Err(error) => error, + }; + 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") + ); + server.abort(); + root.shutdown().await.unwrap(); +} + #[path = "model_flow/native.rs"] mod native; diff --git a/crates/dim-agent-capabilities/tests/model_stream_recovery_flow.rs b/crates/dim-agent-capabilities/tests/model_stream_recovery_flow.rs index 0047fb7e62..c5581b8481 100644 --- a/crates/dim-agent-capabilities/tests/model_stream_recovery_flow.rs +++ b/crates/dim-agent-capabilities/tests/model_stream_recovery_flow.rs @@ -478,6 +478,151 @@ async fn a_usage_fact_before_a_cut_stops_the_retry() { .unwrap(); } +/// The failure the aimux stream builds when no part arrives inside its idle +/// allowance: a network failure with no provider response behind it. +fn idle_timeout() -> HostError { + let reason = "the stream delivered nothing for 300 seconds"; + HostError::Failed { + message: ModelFailureKind::Network.line(Some(reason)), + budget: None, + kind: HostErrorKind::Transport, + model: Some(Box::new(ModelFailureFacts { + kind: ModelFailureKind::Network, + reason: Some(reason.into()), + status: None, + provider_code: None, + request_id: None, + cause: Vec::new(), + retry_after: None, + attempts: 1, + waited: Duration::ZERO, + retry_after_stop: None, + retry_forbidden: false, + })), + presentation: None, + } +} + +/// An idle timeout before the attempt committed anything is replaced in place, +/// as any network failure is: one request, two attempts, one reply. +#[tokio::test(start_paused = true)] +async fn an_idle_timeout_before_any_committed_event_retries_in_place() { + tokio::time::timeout(Duration::from_secs(10), async { + let (cut, cut_stream) = mpsc::unbounded_channel(); + let (retry, retry_stream) = mpsc::unbounded_channel(); + let model = Arc::new(ScriptedModel::new(vec![cut_stream, retry_stream])); + let agent = MinimalHost::start(&builder(model.clone(), Arc::new(MockTools))) + .await + .unwrap(); + let session = agent + .create_session(SessionConfig::default()) + .await + .unwrap(); + session + .submit("go".into(), InputMode::Queue, "main") + .await + .unwrap(); + send( + &cut, + vec![ + Ok(ModelChunk::MessageStart { + message_id: "cut".into(), + }), + Ok(ModelChunk::Thinking("partial thought".into())), + Err(idle_timeout()), + ], + ); + drop(cut); + + let ended = tokio::select! { + _ = model.second_attempt.notified() => None, + outcome = turn_end(&session) => Some(outcome), + }; + assert!( + ended.is_none(), + "an idle timeout before any committed output retries in place; the turn ended with {ended:?}" + ); + + send(&retry, reply("retry")); + drop(retry); + model.release.notify_one(); + session.idle("main").await.unwrap(); + + assert_eq!(model.calls.load(Ordering::SeqCst), 2); + let events = chain_events(&session, "main", ..).await.unwrap(); + assert_eq!( + events + .iter() + .filter(|event| matches!(event.kind, EventKind::ModelCall(_))) + .count(), + 1, + "the retry belongs to the same request" + ); + assert_eq!(text_events(&events), ["answer"]); + assert!(events.iter().any(|event| matches!( + &event.kind, + EventKind::TurnEnd(TurnEndData { + outcome: TurnOutcome::Completed { .. }, + .. + }) + ))); + agent.close().await.unwrap(); + }) + .await + .unwrap(); +} + +/// An idle timeout after committed text is not replayed: the turn ends with the +/// network failure and resending is the user's call. +#[tokio::test(start_paused = true)] +async fn an_idle_timeout_after_a_committed_event_ends_the_turn_without_retrying() { + tokio::time::timeout(Duration::from_secs(10), async { + let (cut, cut_stream) = mpsc::unbounded_channel(); + let model = Arc::new(ScriptedModel::new(vec![cut_stream])); + let agent = MinimalHost::start(&builder(model.clone(), Arc::new(MockTools))) + .await + .unwrap(); + let session = agent + .create_session(SessionConfig::default()) + .await + .unwrap(); + session + .submit("go".into(), InputMode::Queue, "main") + .await + .unwrap(); + let committed = "x".repeat(4096); + send( + &cut, + vec![ + Ok(ModelChunk::MessageStart { + message_id: "cut".into(), + }), + Ok(ModelChunk::Text(committed.clone())), + Err(idle_timeout()), + ], + ); + drop(cut); + session.idle("main").await.unwrap(); + + assert_eq!(model.calls.load(Ordering::SeqCst), 1); + let events = chain_events(&session, "main", ..).await.unwrap(); + assert_eq!(text_events(&events), [committed]); + let failure = model_end_failure(&events); + assert_eq!(failure["kind"], "network", "{failure}"); + assert_eq!(failure["attempts"], 1, "committed text stops the retry"); + assert!(matches!( + events.iter().find_map(|event| match &event.kind { + EventKind::TurnEnd(data) => Some(&data.outcome), + _ => None, + }), + Some(TurnOutcome::Failed { .. }) + )); + agent.close().await.unwrap(); + }) + .await + .unwrap(); +} + #[tokio::test(start_paused = true)] async fn thinking_progress_is_shown_once_per_interval() { tokio::time::timeout(Duration::from_secs(10), async { diff --git a/crates/dim-app-server/tests/read_image_flow.rs b/crates/dim-app-server/tests/read_image_flow.rs index a369a04671..978b2abf78 100644 --- a/crates/dim-app-server/tests/read_image_flow.rs +++ b/crates/dim-app-server/tests/read_image_flow.rs @@ -218,6 +218,7 @@ async fn accumulated_user_and_read_images_follow_model_routing() { kind: ModelProtocol::OpenaiCompatible, api_key_env: None, base_url, + network: Default::default(), headers: Default::default(), compatible: None, models: [&vision, &text] diff --git a/crates/dim-cli/README.md b/crates/dim-cli/README.md index 3e7aa931f2..a81391e211 100644 --- a/crates/dim-cli/README.md +++ b/crates/dim-cli/README.md @@ -377,6 +377,8 @@ printf '%s\n' 'Explain this project' | target/debug/dimcode \ The configuration references credentials by environment-variable name. The shared daemon inherits the environment when it starts; changing the client's environment does not update an existing daemon. Use a separate home for a different explicit model configuration. The client matches the server's explicit product/configured/mock profile and the SHA-256 of the exact configured file bytes; it rejects a mock daemon or a different configuration without deleting the endpoint or stopping that daemon. A configured real model uses production workspace tools, not mock tools. +A provider may also state an optional `network` block: `proxy` is an HTTP or HTTPS root URL every request to that provider goes through, and `timeoutMs` is a positive safe integer for the total time one request may spend, its response body included. It carries the same connection facts a saved Provider record does, and an invalid value fails the load with the provider it belongs to. + `--cwd PATH` selects the workspace: the client resolves it once as UTF-8, and a command that names the workspace in a request refuses a path that is not valid UTF-8 before it connects to the daemon, showing the path with its invalid bytes diff --git a/docs/design/model-failures.md b/docs/design/model-failures.md index 3c0e35f501..c22c40604a 100644 --- a/docs/design/model-failures.md +++ b/docs/design/model-failures.md @@ -30,6 +30,42 @@ A timeout of the HTTP connection or of the stream reaches the bridge as a transport `ApiCall` and is `network`. `AiMuxError::Timeout` has no producer in a chat call; if it ever reaches the bridge it is `unknown` and is not retried. +The bridge also bounds its own waits: a stream that delivers nothing for five +minutes is `network`, with the reason `the stream delivered nothing for 300 +seconds`. The bound is per wait, not per request, so a reply that keeps +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 +such instant, the provider returning the stream and one stream part, keeps the +deadline-first order. + +Three waits carry the bound. The wait for the response headers starts when the +request is sent, so sending the body and following redirects count against it, +and expires with the reason `no response headers arrived within 300 seconds of +sending the request`. The wait for the stream to start begins when the +transport produces the response headers. It expires with the reason `the +response headers arrived, but no stream event followed within 300 seconds` for +a provider that reads one stream event before it returns the stream (OpenAI +Chat, Anthropic, Gemini, xAI Responses). It expires with the reason `the +response headers arrived, but the stream did not start within 300 seconds` for +the OpenAI Responses provider: its pinned SDK reads response metadata before it +returns the stream, so that wait ends at the stream's start, not at an event +the driver can see. The compatible and Bedrock providers return at the headers, +so their first event falls under the wait between parts. That wait expires with +the reason `the stream delivered nothing for 300 seconds`. A non-2xx response is +handled differently: its body is a short diagnostic, and its read has its own +total five-minute allowance, so a stalled error body cannot hold the request +open, and the request still fails with the HTTP status and the kind that status +names instead of an idle network failure. The connection's optional total +timeout is unchanged and is still separate from these bounds. + +Only decoded stream parts renew the wait between parts. The provider parser +drops SSE comments and Anthropic `ping` events before they reach the bridge, so +a connection kept alive only by keep-alives still fails after five minutes +without parts. + Codes are compared trimmed and ASCII-lowercased. ### The two roles of a provider string diff --git a/docs/zh/design/model-failures.md b/docs/zh/design/model-failures.md index 45a6fe697d..acf302b892 100644 --- a/docs/zh/design/model-failures.md +++ b/docs/zh/design/model-failures.md @@ -23,6 +23,12 @@ aimux 桥接层是唯一持有提供方结构化错误、并看得到完整响 HTTP 连接或流的超时以传输 `ApiCall` 到达桥接层,是 `network`。`AiMuxError::Timeout` 在聊天调用中没有产生者;若它到达桥接层,是 `unknown`,且不重试。 +桥接层自己也给几段等待设上限:连续五分钟没有任何事件是 `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 状态和该状态对应的类别失败,而不是变成空闲的网络失败。连接原来可选的整请求超时不变,和这几段上限是两件事。 + +只有解码出的流事件才续上两次事件之间的等待。提供方的解析器在事件到达桥接层之前就丢掉了 SSE 注释和 Anthropic 的 `ping` 事件,所以只靠 keep-alive 保活的连接仍然会在没有事件五分钟后失败。 + code 比较前先 trim 并转 ASCII 小写。 ### 提供方字符串的两种角色