From 55b1d3ce4ee3b53c1eee743a9f4220a415a58d77 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 20:16:45 +0800 Subject: [PATCH 01/19] fix(aimux): fail a model stream that goes idle A request waited for the next stream part with no deadline, so a provider that stopped delivering without closing held the turn until an external deadline ended the process. Each wait now has a five-minute allowance, and an expired one fails the request as a network failure so the retry policy can replace the attempt while nothing was committed. The allowance is per wait, not per request: a reply that keeps streaming is never cut. Cancelling the request outranks the deadline, and the deadline outranks a part that is ready at the same moment. --- crates/dim-agent-aimux/src/stream.rs | 50 +++++++++++++++++++++++++++- docs/design/model-failures.md | 8 +++++ docs/zh/design/model-failures.md | 2 ++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/crates/dim-agent-aimux/src/stream.rs b/crates/dim-agent-aimux/src/stream.rs index 221dbd1670..d6a8b7183a 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,16 @@ use tokio_util::sync::CancellationToken; use crate::request::ToolNames; +/// How long a request waits for the next part of its stream before the +/// connection counts as lost. +/// +/// Five minutes matches the allowance other harnesses give a slow model step. +/// It bounds only the wait between parts: a reply that keeps streaming 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. The same +/// failure is retried in place while the attempt committed nothing. +const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(300); + pub(crate) fn convert( result: StreamResult, tool_names: ToolNames, @@ -81,6 +94,9 @@ 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())); + } next = stream.next() => next, } }; @@ -527,6 +543,38 @@ fn empty_reply() -> HostError { ) } +/// The failure of a stream that delivered nothing for [`STREAM_IDLE_TIMEOUT`]. +/// +/// 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. +fn idle_failure() -> HostError { + let reason = format!( + "the stream delivered nothing for {} seconds", + STREAM_IDLE_TIMEOUT.as_secs() + ); + 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/docs/design/model-failures.md b/docs/design/model-failures.md index 3c0e35f501..4e5d511602 100644 --- a/docs/design/model-failures.md +++ b/docs/design/model-failures.md @@ -30,6 +30,14 @@ 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 wait between stream parts: 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. The +connection's optional total timeout is unchanged and is still separate from this +idle bound. + 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..d43bd97c30 100644 --- a/docs/zh/design/model-failures.md +++ b/docs/zh/design/model-failures.md @@ -23,6 +23,8 @@ aimux 桥接层是唯一持有提供方结构化错误、并看得到完整响 HTTP 连接或流的超时以传输 `ApiCall` 到达桥接层,是 `network`。`AiMuxError::Timeout` 在聊天调用中没有产生者;若它到达桥接层,是 `unknown`,且不重试。 +桥接层自己也给两次流事件之间的等待设上限:连续五分钟没有任何事件是 `network`,reason 为 `the stream delivered nothing for 300 seconds`。这个上限按每次等待计,不按整个请求计,所以持续有事件的回复不会被截断;上限到点时它优先于同时就绪的事件,取消请求又优先于两者。连接原来可选的整请求超时不变,与这个空闲上限是两件事。 + code 比较前先 trim 并转 ASCII 小写。 ### 提供方字符串的两种角色 From 4608538acf3ff70a26939d29b0485e4135cf502f Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 20:16:49 +0800 Subject: [PATCH 02/19] test(aimux): pin the idle allowance on a stalled stream The stream fixture now lets a test feed parts after the idle wait is armed, so virtual time can pass inside one wait. The cases cover the failure's kind and reason, parts that keep the stream open, and an expired deadline that outranks a part ready at the same moment. --- crates/dim-agent-aimux/Cargo.toml | 1 + crates/dim-agent-aimux/src/stream/tests.rs | 163 ++++++++++++++++++++- 2 files changed, 163 insertions(+), 1 deletion(-) 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/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)); +} From 0d3c585127f749a9f298edf872e3e792359fc823 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 20:16:52 +0800 Subject: [PATCH 03/19] test(model): pin the idle failure's recovery paths An idle failure is a network failure, so an attempt that committed nothing is replaced in place under one request, while one that already committed text ends the turn without replaying it. Both outcomes are scripted with the failure the aimux stream builds. --- .../tests/model_stream_recovery_flow.rs | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) 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 { From b107f6cd14ead21a5de6ff87027c9376f044b969 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 20:16:58 +0800 Subject: [PATCH 04/19] feat(aimux): let the model configuration state the connection network The development model configuration could not state the facts the transport already reads from a product provider record, so a development run could not set a proxy or a total request timeout. A provider now takes an optional network block with the rules the product record applies: an HTTP or HTTPS root proxy URL and a positive safe-integer timeout. The block sets the connection the catalog resolves for every request of that provider. The streaming idle allowance stays a fixed bound of its own, not a connection setting. --- crates/dim-agent-aimux/src/config.rs | 6 +- crates/dim-agent-aimux/src/models.rs | 37 +++++++- crates/dim-agent-aimux/src/plugin.rs | 2 +- crates/dim-agent-aimux/tests/model_flow.rs | 88 +++++++++++++++++++ .../dim-app-server/tests/read_image_flow.rs | 1 + crates/dim-cli/README.md | 2 + 6 files changed, 133 insertions(+), 3 deletions(-) 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/models.rs b/crates/dim-agent-aimux/src/models.rs index ff3033bcfc..bcf7c64568 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 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/tests/model_flow.rs b/crates/dim-agent-aimux/tests/model_flow.rs index ac40094567..a0300ac138 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 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 { 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..4ec457cad4 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 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 From 5022a1188270b86f8c61b4f8265af6ed923cc43b Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 20:47:37 +0800 Subject: [PATCH 05/19] test(aimux): pin the failure of a wait for response headers A provider that reads the request and never sends the response headers holds the turn with no deadline. The case keeps a raw listener at that point after its request head arrives, moves the clock five minutes, and expects the network failure the bridge reports for an idle stream, with the reason naming the response headers. Without the bound the wait never ends; the test's guard reports it, and the assertions on the failure's kind and reason cannot be reached. --- crates/dim-agent-aimux/tests/model_flow.rs | 73 ++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/crates/dim-agent-aimux/tests/model_flow.rs b/crates/dim-agent-aimux/tests/model_flow.rs index a0300ac138..0ce128b4d4 100644 --- a/crates/dim-agent-aimux/tests/model_flow.rs +++ b/crates/dim-agent-aimux/tests/model_flow.rs @@ -1737,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("the response headers did not arrive within 300 seconds") + ); + server.abort(); + root.shutdown().await.unwrap(); +} + #[path = "model_flow/native.rs"] mod native; From d406058105821c2a3890d24c08dc59e770270ec6 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 20:48:08 +0800 Subject: [PATCH 06/19] fix(aimux): bound the wait for the response headers The idle allowance started only after the response headers arrived, so a provider that accepted the request and never answered held the turn until an external deadline whenever the connection's optional total timeout was unset, which is the default. The wait for the headers now carries the same five-minute allowance and fails as a network failure with the reason naming the headers, so the retry policy replaces the attempt in place while nothing was committed. The connection's optional total timeout is unchanged: this bounds one wait, not the whole request. Cancelling the request still outranks the deadline. --- crates/dim-agent-aimux/src/driver.rs | 9 +++++++++ crates/dim-agent-aimux/src/stream.rs | 27 ++++++++++++++------------- docs/design/model-failures.md | 7 ++++--- docs/zh/design/model-failures.md | 2 +- 4 files changed, 28 insertions(+), 17 deletions(-) diff --git a/crates/dim-agent-aimux/src/driver.rs b/crates/dim-agent-aimux/src/driver.rs index f95e795400..580b696d4f 100644 --- a/crates/dim-agent-aimux/src/driver.rs +++ b/crates/dim-agent-aimux/src/driver.rs @@ -732,6 +732,15 @@ impl ModelDriver for AimuxDriver { if let Some(pending) = pending.as_mut() { pending.cancelled(); } return Err(HostError::Cancelled("Model invocation cancelled".into())); } + _ = tokio::time::sleep(stream::STREAM_IDLE_TIMEOUT) => { + abort.abort(); + let error = stream::idle_failure(format!( + "the response headers did not arrive within {} seconds", + stream::STREAM_IDLE_TIMEOUT.as_secs() + )); + if let Some(pending) = pending.as_mut() { pending.failed(&error.to_string()); } + return Err(error); + } result = async { match &recording { Some(capture) => capture.scope(model.do_stream(&options)).await, diff --git a/crates/dim-agent-aimux/src/stream.rs b/crates/dim-agent-aimux/src/stream.rs index d6a8b7183a..954275299b 100644 --- a/crates/dim-agent-aimux/src/stream.rs +++ b/crates/dim-agent-aimux/src/stream.rs @@ -28,15 +28,16 @@ use tokio_util::sync::CancellationToken; use crate::request::ToolNames; -/// How long a request waits for the next part of its stream before the +/// How long a request waits for the reply to start or continue before the /// connection counts as lost. /// /// Five minutes matches the allowance other harnesses give a slow model step. -/// It bounds only the wait between parts: a reply that keeps streaming 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. The same -/// failure is retried in place while the attempt committed nothing. -const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(300); +/// It bounds the wait for the response headers and, once they arrive, the wait +/// between parts: a reply that keeps streaming 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. The same failure is retried in +/// place while the attempt committed nothing. +pub(crate) const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(300); pub(crate) fn convert( result: StreamResult, @@ -95,7 +96,10 @@ pub(crate) fn convert( break Some(Err(HostError::Cancelled("Model request cancelled".into()))); } _ = tokio::time::sleep(STREAM_IDLE_TIMEOUT) => { - break Some(Err(idle_failure())); + break Some(Err(idle_failure(format!( + "the stream delivered nothing for {} seconds", + STREAM_IDLE_TIMEOUT.as_secs() + )))); } next = stream.next() => next, } @@ -543,17 +547,14 @@ fn empty_reply() -> HostError { ) } -/// The failure of a stream that delivered nothing for [`STREAM_IDLE_TIMEOUT`]. +/// 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. -fn idle_failure() -> HostError { - let reason = format!( - "the stream delivered nothing for {} seconds", - STREAM_IDLE_TIMEOUT.as_secs() - ); +pub(crate) fn idle_failure(reason: String) -> HostError { HostError::Failed { message: ModelFailureKind::Network.line(Some(&reason)), budget: None, diff --git a/docs/design/model-failures.md b/docs/design/model-failures.md index 4e5d511602..a5b62a179c 100644 --- a/docs/design/model-failures.md +++ b/docs/design/model-failures.md @@ -34,9 +34,10 @@ The bridge also bounds its own wait between stream parts: 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. The -connection's optional total timeout is unchanged and is still separate from this -idle bound. +ready at the same moment, and cancelling the request outranks both. The wait for +the response headers carries the same bound and the reason `the response headers +did not arrive within 300 seconds`. The connection's optional total timeout is +unchanged and is still separate from this idle bound. Codes are compared trimmed and ASCII-lowercased. diff --git a/docs/zh/design/model-failures.md b/docs/zh/design/model-failures.md index d43bd97c30..43dc9859f8 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`。这个上限按每次等待计,不按整个请求计,所以持续有事件的回复不会被截断;上限到点时它优先于同时就绪的事件,取消请求又优先于两者。连接原来可选的整请求超时不变,与这个空闲上限是两件事。 +桥接层自己也给两次流事件之间的等待设上限:连续五分钟没有任何事件是 `network`,reason 为 `the stream delivered nothing for 300 seconds`。这个上限按每次等待计,不按整个请求计,所以持续有事件的回复不会被截断;上限到点时它优先于同时就绪的事件,取消请求又优先于两者。等响应头的等待用同一个上限,reason 为 `the response headers did not arrive within 300 seconds`。连接原来可选的整请求超时不变,与这个空闲上限是两件事。 code 比较前先 trim 并转 ASCII 小写。 From 9582572fe2e92957ce4cb7e597727d1d8a827867 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 20:48:15 +0800 Subject: [PATCH 07/19] fix(aimux): name the safe integer bound in the network timeout message The development configuration's network check also refuses a timeout above the largest safe JSON integer, but its message and the CLI README asked for a positive integer, which such a value satisfies. Both now ask for a positive safe integer, and the load-failure case asserts that wording. --- crates/dim-agent-aimux/src/models.rs | 2 +- crates/dim-agent-aimux/tests/model_flow.rs | 2 +- crates/dim-cli/README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/dim-agent-aimux/src/models.rs b/crates/dim-agent-aimux/src/models.rs index bcf7c64568..ca75fb5501 100644 --- a/crates/dim-agent-aimux/src/models.rs +++ b/crates/dim-agent-aimux/src/models.rs @@ -248,7 +248,7 @@ fn validate_network(network: &ModelNetwork, provider: &str) -> Result<(), HostEr .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 integer is required" + "Invalid network timeout for {provider}: a positive safe integer is required" ))); } Ok(()) diff --git a/crates/dim-agent-aimux/tests/model_flow.rs b/crates/dim-agent-aimux/tests/model_flow.rs index 0ce128b4d4..3b50bca4e1 100644 --- a/crates/dim-agent-aimux/tests/model_flow.rs +++ b/crates/dim-agent-aimux/tests/model_flow.rs @@ -908,7 +908,7 @@ fn a_network_block_refuses_values_the_transport_cannot_use() { .expect_err("a timeout outside the safe integer range"); assert_eq!( error.to_string(), - "Invalid network timeout for local: a positive integer is required", + "Invalid network timeout for local: a positive safe integer is required", "{network}" ); } diff --git a/crates/dim-cli/README.md b/crates/dim-cli/README.md index 4ec457cad4..a81391e211 100644 --- a/crates/dim-cli/README.md +++ b/crates/dim-cli/README.md @@ -377,7 +377,7 @@ 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 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. +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 From c346caa8a9832a027b7bd0fa1b2af99be89a4627 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 21:02:22 +0800 Subject: [PATCH 08/19] fix(aimux): name the whole request in the response-header bound The five-minute bound starts when the request is sent and covers its body and any redirects, so the failure reason, the constant's documentation and the design pages now name the whole exchange instead of only the wait for the response headers. The retry budget is unchanged: eight attempts of five minutes each bound a half-open connection to roughly 42 minutes before the turn fails. --- crates/dim-agent-aimux/src/driver.rs | 2 +- crates/dim-agent-aimux/src/stream.rs | 11 ++++++----- crates/dim-agent-aimux/tests/model_flow.rs | 2 +- docs/design/model-failures.md | 8 +++++--- docs/zh/design/model-failures.md | 2 +- 5 files changed, 14 insertions(+), 11 deletions(-) diff --git a/crates/dim-agent-aimux/src/driver.rs b/crates/dim-agent-aimux/src/driver.rs index 580b696d4f..dd7d0280f6 100644 --- a/crates/dim-agent-aimux/src/driver.rs +++ b/crates/dim-agent-aimux/src/driver.rs @@ -735,7 +735,7 @@ impl ModelDriver for AimuxDriver { _ = tokio::time::sleep(stream::STREAM_IDLE_TIMEOUT) => { abort.abort(); let error = stream::idle_failure(format!( - "the response headers did not arrive within {} seconds", + "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()); } diff --git a/crates/dim-agent-aimux/src/stream.rs b/crates/dim-agent-aimux/src/stream.rs index 954275299b..9df4f0f911 100644 --- a/crates/dim-agent-aimux/src/stream.rs +++ b/crates/dim-agent-aimux/src/stream.rs @@ -32,11 +32,12 @@ use crate::request::ToolNames; /// connection counts as lost. /// /// Five minutes matches the allowance other harnesses give a slow model step. -/// It bounds the wait for the response headers and, once they arrive, the wait -/// between parts: a reply that keeps streaming 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. The same failure is retried in -/// place while the attempt committed nothing. +/// It bounds one exchange from sending the request until the response headers +/// arrive (the request body and any redirects count against it) and, once they +/// arrive, the wait between parts: a reply that keeps streaming 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. The same +/// failure is retried in place while the attempt committed nothing. pub(crate) const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(300); pub(crate) fn convert( diff --git a/crates/dim-agent-aimux/tests/model_flow.rs b/crates/dim-agent-aimux/tests/model_flow.rs index 3b50bca4e1..e10675ca3a 100644 --- a/crates/dim-agent-aimux/tests/model_flow.rs +++ b/crates/dim-agent-aimux/tests/model_flow.rs @@ -1804,7 +1804,7 @@ async fn a_wait_for_response_headers_past_the_idle_allowance_fails_as_a_network_ assert_eq!(model.kind, ModelFailureKind::Network); assert_eq!( model.reason.as_deref(), - Some("the response headers did not arrive within 300 seconds") + Some("no response headers arrived within 300 seconds of sending the request") ); server.abort(); root.shutdown().await.unwrap(); diff --git a/docs/design/model-failures.md b/docs/design/model-failures.md index a5b62a179c..cd472374fd 100644 --- a/docs/design/model-failures.md +++ b/docs/design/model-failures.md @@ -35,9 +35,11 @@ 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. The wait for -the response headers carries the same bound and the reason `the response headers -did not arrive within 300 seconds`. The connection's optional total timeout is -unchanged and is still separate from this idle bound. +the response headers carries the same bound and the reason `no response headers +arrived within 300 seconds of sending the request`; it starts when the request +is sent, so sending the body and following redirects count against it. The +connection's optional total timeout is unchanged and is still separate from +this idle bound. Codes are compared trimmed and ASCII-lowercased. diff --git a/docs/zh/design/model-failures.md b/docs/zh/design/model-failures.md index 43dc9859f8..0ee502b93b 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`。这个上限按每次等待计,不按整个请求计,所以持续有事件的回复不会被截断;上限到点时它优先于同时就绪的事件,取消请求又优先于两者。等响应头的等待用同一个上限,reason 为 `the response headers did not arrive within 300 seconds`。连接原来可选的整请求超时不变,与这个空闲上限是两件事。 +桥接层自己也给两次流事件之间的等待设上限:连续五分钟没有任何事件是 `network`,reason 为 `the stream delivered nothing for 300 seconds`。这个上限按每次等待计,不按整个请求计,所以持续有事件的回复不会被截断;上限到点时它优先于同时就绪的事件,取消请求又优先于两者。等响应头的等待用同一个上限,从发出请求开始计,发送请求体和跟随重定向都算在内,reason 为 `no response headers arrived within 300 seconds of sending the request`。连接原来可选的整请求超时不变,与这个空闲上限是两件事。 code 比较前先 trim 并转 ASCII 小写。 From 94c0607fad5689976e864e20fa23f7cbd35e97de Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 21:24:42 +0800 Subject: [PATCH 09/19] test(aimux): pin the header and first-event deadlines apart A reply whose headers arrive inside the allowance must still get its own allowance for the first event, and a stalled non-2xx body must keep the HTTP status instead of becoming an idle network failure. Both cases fail on the current driver by assertion. --- crates/dim-agent-aimux/tests/model_flow.rs | 186 +++++++++++++++++++++ 1 file changed, 186 insertions(+) diff --git a/crates/dim-agent-aimux/tests/model_flow.rs b/crates/dim-agent-aimux/tests/model_flow.rs index e10675ca3a..c330a8fed2 100644 --- a/crates/dim-agent-aimux/tests/model_flow.rs +++ b/crates/dim-agent-aimux/tests/model_flow.rs @@ -1810,5 +1810,191 @@ async fn a_wait_for_response_headers_past_the_idle_allowance_fails_as_a_network_ root.shutdown().await.unwrap(); } +/// Accepts one connection and reads its request head, so a test can answer +/// with bytes the provider has to interpret itself. +async fn accept_request(listener: tokio::net::TcpListener) -> tokio::net::TcpStream { + use tokio::io::AsyncReadExt; + + 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") { + return socket; + } + } +} + +/// Waits in real time while the test clock stands still. The blocking task +/// keeps the runtime from auto-advancing the paused clock, so the client can +/// read bytes the server already wrote. +async fn real_delay() { + tokio::task::spawn_blocking(|| std::thread::sleep(Duration::from_millis(100))) + .await + .unwrap(); +} + +/// A reply whose headers arrive inside the allowance and whose first event +/// arrives after the whole-request allowance has passed still starts: the wait +/// for the headers and the wait for the first event are bounded separately. +#[tokio::test] +async fn a_delayed_header_reply_still_gets_its_first_event_allowance() { + use tokio::io::AsyncWriteExt; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let (read, received) = tokio::sync::oneshot::channel(); + let (headers, answer) = tokio::sync::oneshot::channel(); + let (first, event) = tokio::sync::oneshot::channel(); + let server = tokio::spawn(async move { + let mut socket = accept_request(listener).await; + read.send(()).unwrap(); + answer.await.unwrap(); + socket + .write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\n") + .await + .unwrap(); + event.await.unwrap(); + socket + .write_all(frame(json!({"content":"hello"}), Value::Null).as_bytes()) + .await + .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::OpenaiChat, + 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(299)).await; + headers.send(()).unwrap(); + real_delay().await; + tokio::time::advance(Duration::from_secs(2)).await; + tokio::task::yield_now().await; + if invoke.is_finished() { + match invoke.await.unwrap() { + Ok(_) => panic!("the reply started before its first event"), + Err(error) => panic!("the reply failed before its first event: {error:?}"), + } + } + first.send(()).unwrap(); + real_delay().await; + let stream = tokio::time::timeout(Duration::from_secs(2), invoke) + .await + .expect("the first event must start the reply") + .expect("the request must not panic") + .expect("the reply must start after the first event"); + let mut stream = stream; + let start = tokio::time::timeout(Duration::from_secs(2), stream.next()) + .await + .expect("the reply must deliver its start") + .expect("the reply must not end before its start") + .expect("the reply must start"); + assert!(matches!(start, ModelChunk::MessageStart { .. })); + let text = tokio::time::timeout(Duration::from_secs(2), stream.next()) + .await + .expect("the reply must deliver its text") + .expect("the reply must not end before its text") + .expect("the first event must deliver text"); + assert!(matches!(text, ModelChunk::Text(text) if text == "hello")); + drop(stream); + server.abort(); + root.shutdown().await.unwrap(); +} + +/// 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] +async fn a_stalled_error_body_keeps_the_response_status() { + use tokio::io::AsyncWriteExt; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let (read, received) = tokio::sync::oneshot::channel(); + let server = tokio::spawn(async move { + let mut socket = accept_request(listener).await; + socket + .write_all( + b"HTTP/1.1 401 Unauthorized\r\ncontent-type: application/json\r\ncontent-length: 1024\r\n\r\n{\"error\":{\"message\":\"Expired credential\"", + ) + .await + .unwrap(); + read.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(); + // Real time lets the client read the headers and start waiting for the + // body before the clock is paused. + real_delay().await; + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(300)).await; + let error = match tokio::time::timeout(Duration::from_secs(2), invoke) + .await + .expect("a stalled error body must not hold the request open") + .expect("the request must not panic") + { + Ok(_) => panic!("a 401 response must fail the request"), + Err(error) => error, + }; + 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)); + server.abort(); + root.shutdown().await.unwrap(); +} + #[path = "model_flow/native.rs"] mod native; From 97a09019c68befded587cd396ee4a8fd12353eec Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 21:31:33 +0800 Subject: [PATCH 10/19] fix(aimux): bound the header, first-event and error-body waits apart The wait for the response headers raced the whole do_stream call, so a reply whose headers arrive inside the allowance but whose first event follows after it was failed as a missing header. The transport now reports the response status, the deadline moves to the first event when the headers arrive, and a non-2xx body is read under its own total allowance so a stalled error body keeps the HTTP status and its kind. --- crates/dim-agent-aimux/src/driver.rs | 155 +++++++++++++++++++++------ crates/dim-agent-aimux/src/stream.rs | 21 ++-- 2 files changed, 136 insertions(+), 40 deletions(-) diff --git a/crates/dim-agent-aimux/src/driver.rs b/crates/dim-agent-aimux/src/driver.rs index dd7d0280f6..faeef9773d 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,53 @@ fn anthropic_base_url(base_url: &str) -> String { } } +/// The transport of one model call, watched by its driver. +/// +/// The driver cannot see how far a provider has got inside `do_stream`: the +/// OpenAI Chat provider reads one stream event after the headers and before it +/// returns, while the compatible provider returns at the headers, so a +/// deadline around the whole call cannot tell a late set of headers from a +/// late first event. The driver only sees the events the stream produces, so +/// this decorator reports the status as soon as the transport produces a +/// response. +/// +/// 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?; + if let Some(status) = self.status.lock().unwrap().take() { + let _ = status.send(response.status()); + } + 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. /// @@ -632,6 +679,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,43 +772,82 @@ 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())); - } - _ = tokio::time::sleep(stream::STREAM_IDLE_TIMEOUT) => { - 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); - } - result = async { + // Three waits carry the idle allowance: sending the request until + // the response headers, the headers until the first stream event, + // and one part until the next. `do_stream` ends only after the + // headers and the first event, so `ResponseWatch` reports the + // headers here and the deadline moves to the first event. + let result = { + let mut awaiting_headers = true; + let mut headers_arrived = false; + let mut bounded = true; + let mut deadline = Box::pin(tokio::time::sleep(stream::STREAM_IDLE_TIMEOUT)); + 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())); } - return Err(error); + _ = &mut deadline, if bounded => { + abort.abort(); + let error = stream::idle_failure(if headers_arrived { + format!( + "the response headers arrived, but no stream event followed within {} seconds", + stream::STREAM_IDLE_TIMEOUT.as_secs() + ) + } 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); + } + status = &mut response, if awaiting_headers => { + awaiting_headers = false; + if let Ok(status) = status { + headers_arrived = true; + if status.is_success() { + deadline.as_mut().reset( + tokio::time::Instant::now() + stream::STREAM_IDLE_TIMEOUT, + ); + } 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) => { diff --git a/crates/dim-agent-aimux/src/stream.rs b/crates/dim-agent-aimux/src/stream.rs index 9df4f0f911..6ac1c59cc2 100644 --- a/crates/dim-agent-aimux/src/stream.rs +++ b/crates/dim-agent-aimux/src/stream.rs @@ -28,16 +28,21 @@ use tokio_util::sync::CancellationToken; use crate::request::ToolNames; -/// How long a request waits for the reply to start or continue before the -/// connection counts as lost. +/// 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 one exchange from sending the request until the response headers -/// arrive (the request body and any redirects count against it) and, once they -/// arrive, the wait between parts: a reply that keeps streaming 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. The same -/// failure is retried in place while the attempt committed nothing. +/// 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 first stream event (the provider reads one event before +/// it returns the stream), and from one stream part to the next. 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( From 6e412a646b171ebb460eee0f1e1c401ac8663db3 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 21:31:36 +0800 Subject: [PATCH 11/19] docs(model-failures): state each idle wait and the keep-alive limit The design document now names the three waits the idle allowance bounds, the separate total allowance for a non-2xx body, and the limitation that only decoded stream parts renew the wait between parts. --- docs/design/model-failures.md | 34 ++++++++++++++++++++++---------- docs/zh/design/model-failures.md | 6 +++++- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/docs/design/model-failures.md b/docs/design/model-failures.md index cd472374fd..e4562145bc 100644 --- a/docs/design/model-failures.md +++ b/docs/design/model-failures.md @@ -30,16 +30,30 @@ 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 wait between stream parts: 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. The wait for -the response headers carries the same bound and the reason `no response headers -arrived within 300 seconds of sending the request`; it starts when the request -is sent, so sending the body and following redirects count against it. The -connection's optional total timeout is unchanged and is still separate from -this idle bound. +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. + +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 first stream event starts when the +response headers arrive and expires with the reason `the response headers +arrived, but no stream event followed within 300 seconds`. The wait between +stream parts 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. diff --git a/docs/zh/design/model-failures.md b/docs/zh/design/model-failures.md index 0ee502b93b..01c1a15d94 100644 --- a/docs/zh/design/model-failures.md +++ b/docs/zh/design/model-failures.md @@ -23,7 +23,11 @@ aimux 桥接层是唯一持有提供方结构化错误、并看得到完整响 HTTP 连接或流的超时以传输 `ApiCall` 到达桥接层,是 `network`。`AiMuxError::Timeout` 在聊天调用中没有产生者;若它到达桥接层,是 `unknown`,且不重试。 -桥接层自己也给两次流事件之间的等待设上限:连续五分钟没有任何事件是 `network`,reason 为 `the stream delivered nothing for 300 seconds`。这个上限按每次等待计,不按整个请求计,所以持续有事件的回复不会被截断;上限到点时它优先于同时就绪的事件,取消请求又优先于两者。等响应头的等待用同一个上限,从发出请求开始计,发送请求体和跟随重定向都算在内,reason 为 `no response headers arrived within 300 seconds of sending the request`。连接原来可选的整请求超时不变,与这个空闲上限是两件事。 +桥接层自己也给几段等待设上限:连续五分钟没有任何事件是 `network`,reason 为 `the stream delivered nothing for 300 seconds`。这个上限按每次等待计,不按整个请求计,所以持续有事件的回复不会被截断;上限到点时它优先于同时就绪的事件,取消请求又优先于两者。 + +带上限的等待有三段。等响应头从发出请求开始计,发送请求体和跟随重定向都算在内,reason 为 `no response headers arrived within 300 seconds of sending the request`。等第一个流事件从收到响应头开始计,reason 为 `the response headers arrived, but no stream event followed within 300 seconds`。两次流事件之间的等待,reason 为 `the stream delivered nothing for 300 seconds`。非 2xx 响应另算:它的响应体是短的诊断信息,读取单独有总计五分钟的上限,卡住的错误体不能拖住请求,请求仍然按 HTTP 状态和该状态对应的类别失败,而不是变成空闲的网络失败。连接原来可选的整请求超时不变,和这几段上限是两件事。 + +只有解码出的流事件才续上两次事件之间的等待。提供方的解析器在事件到达桥接层之前就丢掉了 SSE 注释和 Anthropic 的 `ping` 事件,所以只靠 keep-alive 保活的连接仍然会在没有事件五分钟后失败。 code 比较前先 trim 并转 ASCII 小写。 From 2abb1d241b550ef6dedb09cf7631330672f13997 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 21:32:25 +0800 Subject: [PATCH 12/19] style(aimux): keep the idle failure within the line limit --- crates/dim-agent-aimux/src/driver.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/dim-agent-aimux/src/driver.rs b/crates/dim-agent-aimux/src/driver.rs index faeef9773d..222818af71 100644 --- a/crates/dim-agent-aimux/src/driver.rs +++ b/crates/dim-agent-aimux/src/driver.rs @@ -815,7 +815,9 @@ impl ModelDriver for AimuxDriver { stream::STREAM_IDLE_TIMEOUT.as_secs() ) }); - if let Some(pending) = pending.as_mut() { pending.failed(&error.to_string()); } + if let Some(pending) = pending.as_mut() { + pending.failed(&error.to_string()); + } return Err(error); } status = &mut response, if awaiting_headers => { From 92ff0426c86760fc2ecc7525a7f2860c251f0232 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 21:35:43 +0800 Subject: [PATCH 13/19] test(aimux): pin the first-event allowance A reply whose headers arrive and whose first event never does fails as a network failure that names the missing event, so the window that starts at the headers is both extended and bounded. --- crates/dim-agent-aimux/tests/model_flow.rs | 70 ++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/crates/dim-agent-aimux/tests/model_flow.rs b/crates/dim-agent-aimux/tests/model_flow.rs index c330a8fed2..ee925802d6 100644 --- a/crates/dim-agent-aimux/tests/model_flow.rs +++ b/crates/dim-agent-aimux/tests/model_flow.rs @@ -1921,6 +1921,76 @@ async fn a_delayed_header_reply_still_gets_its_first_event_allowance() { root.shutdown().await.unwrap(); } +/// 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] +async fn a_first_event_past_its_own_allowance_fails_as_a_network_failure() { + use tokio::io::AsyncWriteExt; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let (read, received) = tokio::sync::oneshot::channel(); + let server = tokio::spawn(async move { + let mut socket = accept_request(listener).await; + socket + .write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\n") + .await + .unwrap(); + read.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::OpenaiChat, + 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(); + // Real time lets the client read the headers and start waiting for the + // first event before the clock is paused. + real_delay().await; + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(300)).await; + let error = match tokio::time::timeout(Duration::from_secs(2), invoke) + .await + .expect("a missing first event must not hold the request open") + .expect("the request must not panic") + { + Ok(_) => panic!("a reply without a first event 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("the response headers arrived, but no stream event followed within 300 seconds") + ); + server.abort(); + root.shutdown().await.unwrap(); +} + /// 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. From ea4b63b3a0f0beb87e2a03dc8c0fb44453e8cded Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 21:38:47 +0800 Subject: [PATCH 14/19] style(aimux): tidy the header wait comment --- crates/dim-agent-aimux/src/driver.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/dim-agent-aimux/src/driver.rs b/crates/dim-agent-aimux/src/driver.rs index 222818af71..26bd68e404 100644 --- a/crates/dim-agent-aimux/src/driver.rs +++ b/crates/dim-agent-aimux/src/driver.rs @@ -773,10 +773,10 @@ impl ModelDriver for AimuxDriver { capture.pending() }); // Three waits carry the idle allowance: sending the request until - // the response headers, the headers until the first stream event, - // and one part until the next. `do_stream` ends only after the - // headers and the first event, so `ResponseWatch` reports the - // headers here and the deadline moves to the first event. + // the response headers, the headers until the first stream event + // (a provider may read one before it returns the stream), and one + // part until the next. `ResponseWatch` reports the headers here + // and the deadline moves to the first event. let result = { let mut awaiting_headers = true; let mut headers_arrived = false; @@ -804,7 +804,7 @@ impl ModelDriver for AimuxDriver { } _ = &mut deadline, if bounded => { abort.abort(); - let error = stream::idle_failure(if headers_arrived { + let error = stream::idle_failure(if headers_arrived { format!( "the response headers arrived, but no stream event followed within {} seconds", stream::STREAM_IDLE_TIMEOUT.as_secs() From 4a0f220f3741d7468478e1a58c1ef7974d1d49d9 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 22:42:00 +0800 Subject: [PATCH 15/19] test(aimux): drive the wait deadlines through a scripted transport The three deadline tests answered over a real listener and held the call in real time with a blocking sleep before the virtual clock moved, so a scheduler slower than the sleep failed them without a product defect. They now build the driver in the crate, answer each exchange from a scripted transport, and poll the call until it has no ready work before the clock moves, so the same assertions hold with no real waiting. The flow suite keeps the real-transport case for the response headers. --- crates/dim-agent-aimux/src/driver.rs | 3 + crates/dim-agent-aimux/src/driver/tests.rs | 308 +++++++++++++++++++++ crates/dim-agent-aimux/tests/model_flow.rs | 256 ----------------- 3 files changed, 311 insertions(+), 256 deletions(-) create mode 100644 crates/dim-agent-aimux/src/driver/tests.rs diff --git a/crates/dim-agent-aimux/src/driver.rs b/crates/dim-agent-aimux/src/driver.rs index 26bd68e404..da2ecd1806 100644 --- a/crates/dim-agent-aimux/src/driver.rs +++ b/crates/dim-agent-aimux/src/driver.rs @@ -923,3 +923,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..d5fe6b74de --- /dev/null +++ b/crates/dim-agent-aimux/src/driver/tests.rs @@ -0,0 +1,308 @@ +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 => {} + } + } +} + +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)); +} diff --git a/crates/dim-agent-aimux/tests/model_flow.rs b/crates/dim-agent-aimux/tests/model_flow.rs index ee925802d6..e10675ca3a 100644 --- a/crates/dim-agent-aimux/tests/model_flow.rs +++ b/crates/dim-agent-aimux/tests/model_flow.rs @@ -1810,261 +1810,5 @@ async fn a_wait_for_response_headers_past_the_idle_allowance_fails_as_a_network_ root.shutdown().await.unwrap(); } -/// Accepts one connection and reads its request head, so a test can answer -/// with bytes the provider has to interpret itself. -async fn accept_request(listener: tokio::net::TcpListener) -> tokio::net::TcpStream { - use tokio::io::AsyncReadExt; - - 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") { - return socket; - } - } -} - -/// Waits in real time while the test clock stands still. The blocking task -/// keeps the runtime from auto-advancing the paused clock, so the client can -/// read bytes the server already wrote. -async fn real_delay() { - tokio::task::spawn_blocking(|| std::thread::sleep(Duration::from_millis(100))) - .await - .unwrap(); -} - -/// A reply whose headers arrive inside the allowance and whose first event -/// arrives after the whole-request allowance has passed still starts: the wait -/// for the headers and the wait for the first event are bounded separately. -#[tokio::test] -async fn a_delayed_header_reply_still_gets_its_first_event_allowance() { - use tokio::io::AsyncWriteExt; - - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let base = format!("http://{}", listener.local_addr().unwrap()); - let (read, received) = tokio::sync::oneshot::channel(); - let (headers, answer) = tokio::sync::oneshot::channel(); - let (first, event) = tokio::sync::oneshot::channel(); - let server = tokio::spawn(async move { - let mut socket = accept_request(listener).await; - read.send(()).unwrap(); - answer.await.unwrap(); - socket - .write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\n") - .await - .unwrap(); - event.await.unwrap(); - socket - .write_all(frame(json!({"content":"hello"}), Value::Null).as_bytes()) - .await - .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::OpenaiChat, - 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(299)).await; - headers.send(()).unwrap(); - real_delay().await; - tokio::time::advance(Duration::from_secs(2)).await; - tokio::task::yield_now().await; - if invoke.is_finished() { - match invoke.await.unwrap() { - Ok(_) => panic!("the reply started before its first event"), - Err(error) => panic!("the reply failed before its first event: {error:?}"), - } - } - first.send(()).unwrap(); - real_delay().await; - let stream = tokio::time::timeout(Duration::from_secs(2), invoke) - .await - .expect("the first event must start the reply") - .expect("the request must not panic") - .expect("the reply must start after the first event"); - let mut stream = stream; - let start = tokio::time::timeout(Duration::from_secs(2), stream.next()) - .await - .expect("the reply must deliver its start") - .expect("the reply must not end before its start") - .expect("the reply must start"); - assert!(matches!(start, ModelChunk::MessageStart { .. })); - let text = tokio::time::timeout(Duration::from_secs(2), stream.next()) - .await - .expect("the reply must deliver its text") - .expect("the reply must not end before its text") - .expect("the first event must deliver text"); - assert!(matches!(text, ModelChunk::Text(text) if text == "hello")); - drop(stream); - server.abort(); - root.shutdown().await.unwrap(); -} - -/// 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] -async fn a_first_event_past_its_own_allowance_fails_as_a_network_failure() { - use tokio::io::AsyncWriteExt; - - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let base = format!("http://{}", listener.local_addr().unwrap()); - let (read, received) = tokio::sync::oneshot::channel(); - let server = tokio::spawn(async move { - let mut socket = accept_request(listener).await; - socket - .write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\n") - .await - .unwrap(); - read.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::OpenaiChat, - 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(); - // Real time lets the client read the headers and start waiting for the - // first event before the clock is paused. - real_delay().await; - tokio::time::pause(); - tokio::time::advance(Duration::from_secs(300)).await; - let error = match tokio::time::timeout(Duration::from_secs(2), invoke) - .await - .expect("a missing first event must not hold the request open") - .expect("the request must not panic") - { - Ok(_) => panic!("a reply without a first event 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("the response headers arrived, but no stream event followed within 300 seconds") - ); - server.abort(); - root.shutdown().await.unwrap(); -} - -/// 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] -async fn a_stalled_error_body_keeps_the_response_status() { - use tokio::io::AsyncWriteExt; - - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let base = format!("http://{}", listener.local_addr().unwrap()); - let (read, received) = tokio::sync::oneshot::channel(); - let server = tokio::spawn(async move { - let mut socket = accept_request(listener).await; - socket - .write_all( - b"HTTP/1.1 401 Unauthorized\r\ncontent-type: application/json\r\ncontent-length: 1024\r\n\r\n{\"error\":{\"message\":\"Expired credential\"", - ) - .await - .unwrap(); - read.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(); - // Real time lets the client read the headers and start waiting for the - // body before the clock is paused. - real_delay().await; - tokio::time::pause(); - tokio::time::advance(Duration::from_secs(300)).await; - let error = match tokio::time::timeout(Duration::from_secs(2), invoke) - .await - .expect("a stalled error body must not hold the request open") - .expect("the request must not panic") - { - Ok(_) => panic!("a 401 response must fail the request"), - Err(error) => error, - }; - 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)); - server.abort(); - root.shutdown().await.unwrap(); -} - #[path = "model_flow/native.rs"] mod native; From 223d5131e78ce4a51125b1ec21cec5746175a882 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 23:30:12 +0800 Subject: [PATCH 16/19] test(aimux): pin the header report instant and the Responses stream start The transport reports the response headers at 299 seconds of virtual time and the task is not polled again until 301: the reply must still start, and a 401 in the same position must still keep its status instead of becoming a header timeout. The OpenAI Responses startup scan can decode response metadata before it returns the stream, so a stream that never starts must name the stream start rather than a missing event, and a reply whose metadata arrives before its output must still deliver that output. All four fail on the current driver by assertion, except the last, which pins the path the fix must keep working. --- crates/dim-agent-aimux/src/driver/tests.rs | 233 +++++++++++++++++++++ 1 file changed, 233 insertions(+) diff --git a/crates/dim-agent-aimux/src/driver/tests.rs b/crates/dim-agent-aimux/src/driver/tests.rs index d5fe6b74de..9949363be3 100644 --- a/crates/dim-agent-aimux/src/driver/tests.rs +++ b/crates/dim-agent-aimux/src/driver/tests.rs @@ -148,6 +148,13 @@ fn poll_until_idle(mut future: Pin<&mut F>) -> Option(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() @@ -306,3 +313,229 @@ async fn a_stalled_error_body_keeps_the_response_status() { 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 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"); +} From 738414947583226fc3ab926a5548b02ba201adcc Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 23:30:24 +0800 Subject: [PATCH 17/19] fix(aimux): judge the waits by the instant the headers were produced The transport now reports when it produced the response headers, and the wait after them starts at that instant, so a report written inside the header allowance is on time even when the driver next polls after the deadline. The deadline arm still runs before the report and the exchange: it reads the report there and treats an on-time non-2xx reply as a reply whose status must survive, instead of declaring that no headers arrived. The wait after the headers is named by what the provider does with it. The OpenAI Responses SDK reads response metadata before it returns the stream, so that wait ends at the stream's start and its expiry says so, while the providers that read one event keep the reason that names the missing event. --- crates/dim-agent-aimux/src/driver.rs | 93 +++++++++++++++++++++------- crates/dim-agent-aimux/src/stream.rs | 20 +++--- 2 files changed, 80 insertions(+), 33 deletions(-) diff --git a/crates/dim-agent-aimux/src/driver.rs b/crates/dim-agent-aimux/src/driver.rs index da2ecd1806..6de11c8f39 100644 --- a/crates/dim-agent-aimux/src/driver.rs +++ b/crates/dim-agent-aimux/src/driver.rs @@ -250,15 +250,24 @@ 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`: the -/// OpenAI Chat provider reads one stream event after the headers and before it -/// returns, while the compatible provider returns at the headers, so a -/// deadline around the whole call cannot tell a late set of headers from a -/// late first event. The driver only sees the events the stream produces, so -/// this decorator reports the status as soon as the transport produces a -/// response. +/// 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 @@ -268,15 +277,19 @@ fn anthropic_base_url(base_url: &str) -> String { /// status it already received with the bytes that arrived. struct ResponseWatch { inner: FetchFunction, - status: Mutex>>, + 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(response.status()); + let _ = status.send(ResponseReport { + status: response.status(), + received, + }); } if response.status().is_success() { return Ok(response); @@ -561,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 @@ -773,15 +802,17 @@ impl ModelDriver for AimuxDriver { capture.pending() }); // Three waits carry the idle allowance: sending the request until - // the response headers, the headers until the first stream event - // (a provider may read one before it returns the stream), and one - // part until the next. `ResponseWatch` reports the headers here - // and the deadline moves to the first event. + // 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 = Box::pin(tokio::time::sleep(stream::STREAM_IDLE_TIMEOUT)); + 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, @@ -803,12 +834,27 @@ impl ModelDriver for AimuxDriver { 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 { - format!( - "the response headers arrived, but no stream event followed within {} seconds", - stream::STREAM_IDLE_TIMEOUT.as_secs() - ) + headers_arrived_reason(protocol) } else { format!( "no response headers arrived within {} seconds of sending the request", @@ -820,14 +866,13 @@ impl ModelDriver for AimuxDriver { } return Err(error); } - status = &mut response, if awaiting_headers => { + report = &mut response, if awaiting_headers => { awaiting_headers = false; - if let Ok(status) = status { + if let Ok(report) = report { headers_arrived = true; - if status.is_success() { - deadline.as_mut().reset( - tokio::time::Instant::now() + stream::STREAM_IDLE_TIMEOUT, - ); + 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 diff --git a/crates/dim-agent-aimux/src/stream.rs b/crates/dim-agent-aimux/src/stream.rs index 6ac1c59cc2..94376ac1e8 100644 --- a/crates/dim-agent-aimux/src/stream.rs +++ b/crates/dim-agent-aimux/src/stream.rs @@ -34,15 +34,17 @@ use crate::request::ToolNames; /// 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 first stream event (the provider reads one event before -/// it returns the stream), and from one stream part to the next. 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. +/// 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( From 4f88668836c940ba244c372cb07b0b293fe75ec2 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 23:30:27 +0800 Subject: [PATCH 18/19] docs(model-failures): state the reported instant and the Responses start The design document now states that a wait with a producer-reported instant is judged against that instant, so the header wait and the wait after it meet where the transport produced the headers rather than where the driver next polls. It also states that the OpenAI Responses provider's wait ends at the stream's start because its SDK reads response metadata first, and which providers leave the first event to the wait between parts. --- docs/design/model-failures.md | 33 +++++++++++++++++++++----------- docs/zh/design/model-failures.md | 4 ++-- 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/docs/design/model-failures.md b/docs/design/model-failures.md index e4562145bc..c22c40604a 100644 --- a/docs/design/model-failures.md +++ b/docs/design/model-failures.md @@ -34,21 +34,32 @@ 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. +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 first stream event starts when the -response headers arrive and expires with the reason `the response headers -arrived, but no stream event followed within 300 seconds`. The wait between -stream parts 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. +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 diff --git a/docs/zh/design/model-failures.md b/docs/zh/design/model-failures.md index 01c1a15d94..acf302b892 100644 --- a/docs/zh/design/model-failures.md +++ b/docs/zh/design/model-failures.md @@ -23,9 +23,9 @@ aimux 桥接层是唯一持有提供方结构化错误、并看得到完整响 HTTP 连接或流的超时以传输 `ApiCall` 到达桥接层,是 `network`。`AiMuxError::Timeout` 在聊天调用中没有产生者;若它到达桥接层,是 `unknown`,且不重试。 -桥接层自己也给几段等待设上限:连续五分钟没有任何事件是 `network`,reason 为 `the stream delivered nothing for 300 seconds`。这个上限按每次等待计,不按整个请求计,所以持续有事件的回复不会被截断;上限到点时它优先于同时就绪的事件,取消请求又优先于两者。 +桥接层自己也给几段等待设上限:连续五分钟没有任何事件是 `network`,reason 为 `the stream delivered nothing for 300 seconds`。这个上限按每次等待计,不按整个请求计,所以持续有事件的回复不会被截断;上限到点时它优先于同时就绪的事件,取消请求又优先于两者。事件有生产者上报时刻的等待按那个时刻判定:传输层上报它产生响应头的时刻,所以在上限内写下的响应头,即使 driver 之后再 poll 也算按时。没有这种时刻的等待(provider 返回流、两个流分片之间)仍以上限优先。 -带上限的等待有三段。等响应头从发出请求开始计,发送请求体和跟随重定向都算在内,reason 为 `no response headers arrived within 300 seconds of sending the request`。等第一个流事件从收到响应头开始计,reason 为 `the response headers arrived, but no stream event followed within 300 seconds`。两次流事件之间的等待,reason 为 `the stream delivered nothing for 300 seconds`。非 2xx 响应另算:它的响应体是短的诊断信息,读取单独有总计五分钟的上限,卡住的错误体不能拖住请求,请求仍然按 HTTP 状态和该状态对应的类别失败,而不是变成空闲的网络失败。连接原来可选的整请求超时不变,和这几段上限是两件事。 +带上限的等待有三段。等响应头从发出请求开始计,发送请求体和跟随重定向都算在内,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 保活的连接仍然会在没有事件五分钟后失败。 From c78ad3f646ed5514d925e108bd0bee47657840da Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 23:35:32 +0800 Subject: [PATCH 19/19] test(aimux): pin the stream allowance to the report instant Headers reported at 299 seconds and read at 301 must end the stream-start allowance at 599 seconds, three hundred seconds after the report, not at 601 seconds after the poll that read it. The case fails on the driver that starts the window at the poll. --- crates/dim-agent-aimux/src/driver/tests.rs | 56 ++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/crates/dim-agent-aimux/src/driver/tests.rs b/crates/dim-agent-aimux/src/driver/tests.rs index 9949363be3..c2f4b4db1a 100644 --- a/crates/dim-agent-aimux/src/driver/tests.rs +++ b/crates/dim-agent-aimux/src/driver/tests.rs @@ -428,6 +428,62 @@ async fn a_header_report_read_past_its_allowance_keeps_the_response_status() { 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.