Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
55b1d3c
fix(aimux): fail a model stream that goes idle
yyhhyyyyyy Nov 24, 2026
4608538
test(aimux): pin the idle allowance on a stalled stream
yyhhyyyyyy Nov 24, 2026
0d3c585
test(model): pin the idle failure's recovery paths
yyhhyyyyyy Nov 24, 2026
b107f6c
feat(aimux): let the model configuration state the connection network
yyhhyyyyyy Nov 24, 2026
5022a11
test(aimux): pin the failure of a wait for response headers
yyhhyyyyyy Nov 24, 2026
d406058
fix(aimux): bound the wait for the response headers
yyhhyyyyyy Nov 24, 2026
9582572
fix(aimux): name the safe integer bound in the network timeout message
yyhhyyyyyy Nov 24, 2026
c346caa
fix(aimux): name the whole request in the response-header bound
yyhhyyyyyy Nov 24, 2026
94c0607
test(aimux): pin the header and first-event deadlines apart
yyhhyyyyyy Nov 24, 2026
97a0901
fix(aimux): bound the header, first-event and error-body waits apart
yyhhyyyyyy Nov 24, 2026
6e412a6
docs(model-failures): state each idle wait and the keep-alive limit
yyhhyyyyyy Nov 24, 2026
2abb1d2
style(aimux): keep the idle failure within the line limit
yyhhyyyyyy Nov 24, 2026
92ff042
test(aimux): pin the first-event allowance
yyhhyyyyyy Nov 24, 2026
ea4b63b
style(aimux): tidy the header wait comment
yyhhyyyyyy Nov 24, 2026
4a0f220
test(aimux): drive the wait deadlines through a scripted transport
yyhhyyyyyy Nov 24, 2026
223d513
test(aimux): pin the header report instant and the Responses stream s…
yyhhyyyyyy Nov 24, 2026
7384149
fix(aimux): judge the waits by the instant the headers were produced
yyhhyyyyyy Nov 24, 2026
4f88668
docs(model-failures): state the reported instant and the Responses start
yyhhyyyyyy Nov 24, 2026
c78ad3f
test(aimux): pin the stream allowance to the report instant
yyhhyyyyyy Nov 24, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/dim-agent-aimux/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 5 additions & 1 deletion crates/dim-agent-aimux/src/config.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -42,6 +42,10 @@ pub struct ProviderConfig {
pub kind: ProviderKind,
pub api_key_env: Option<String>,
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<String, String>,
pub compatible: Option<CompatibleConfig>,
Expand Down
196 changes: 173 additions & 23 deletions crates/dim-agent-aimux/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -250,6 +250,66 @@ fn anthropic_base_url(base_url: &str) -> String {
}
}

/// What the transport saw when it produced the response headers.
struct ResponseReport {
status: http::StatusCode,
/// The clock reading at which the exchange produced the headers. A
/// deadline is judged against this reading, not against the next poll.
received: tokio::time::Instant,
}

/// The transport of one model call, watched by its driver.
///
/// The driver cannot see how far a provider has got inside `do_stream`: some
/// providers (OpenAI Chat, Anthropic, Gemini, xAI Responses) read one stream
/// event after the headers before they return, the OpenAI Responses provider
/// reads until its SDK's startup scan finds output, and the compatible and
/// Bedrock providers return at the headers, so a deadline around the whole
/// call cannot tell a late set of headers from a late stream start. The driver
/// only sees the events the stream produces, so this decorator reports the
/// status and the instant the transport produced it.
///
/// It also bounds a non-2xx body: the provider reads that body before it
/// returns the failure, and a stalled body would otherwise outlive the
/// request. The read is a short diagnostic, so it gets the allowance once in
/// total rather than per chunk: an idle bound would let a trickle extend it.
/// When the allowance expires the body ends, and the provider reports the HTTP
/// status it already received with the bytes that arrived.
struct ResponseWatch {
inner: FetchFunction,
status: Mutex<Option<tokio::sync::oneshot::Sender<ResponseReport>>>,
}

#[async_trait::async_trait]
impl Fetch for ResponseWatch {
async fn fetch(&self, request: FetchRequest) -> Result<FetchResponse, FetchError> {
let response = self.inner.fetch(request).await?;
let received = tokio::time::Instant::now();
if let Some(status) = self.status.lock().unwrap().take() {
let _ = status.send(ResponseReport {
status: response.status(),
received,
});
}
if response.status().is_success() {
return Ok(response);
}
let FetchResponse {
status,
headers,
url,
body,
} = response;
let deadline = Box::pin(tokio::time::sleep(stream::STREAM_IDLE_TIMEOUT));
Ok(FetchResponse {
status,
headers,
url,
body: body.take_until(deadline).boxed(),
})
}
}

/// The transport a non-conversational call uses: the same client, redirect
/// policy and connection facts as a chat call to the same model.
///
Expand Down Expand Up @@ -514,6 +574,22 @@ fn build_model(
}
}

/// Why the wait after the response headers expired: the headers are in, but
/// the stream has not started. Providers that peek at the stream read one
/// event before they return it; the OpenAI Responses SDK reads response
/// metadata first, so its wait ends at the stream's start, not at an event
/// the driver can see.
fn headers_arrived_reason(protocol: ModelProtocol) -> String {
let ended = match protocol {
ModelProtocol::OpenaiResponses => "the stream did not start",
_ => "no stream event followed",
};
format!(
"the response headers arrived, but {ended} within {} seconds",
stream::STREAM_IDLE_TIMEOUT.as_secs()
)
}

pub(crate) struct AimuxDriver {
files: Option<Arc<dim_agent_capabilities::host::SessionFiles>>,
/// The identity this driver's model requests carry, owned by the Aimux
Expand Down Expand Up @@ -632,6 +708,11 @@ impl ModelDriver for AimuxDriver {
} else {
fetch(&self.transport, network, query)
};
let (report, mut response) = tokio::sync::oneshot::channel();
let fetch: FetchFunction = Arc::new(ResponseWatch {
inner: fetch,
status: Mutex::new(Some(report)),
});
if preset == Some(OPENAI_CODEX_PRESET) && protocol != ModelProtocol::OpenaiResponses {
return Err(HostError::classified(
HostErrorKind::InvalidRequest,
Expand Down Expand Up @@ -720,34 +801,100 @@ impl ModelDriver for AimuxDriver {
capture.input(&options, model.provider(), &request.model_id);
capture.pending()
});
let result = tokio::select! {
biased;
_ = self.generation.cancelled() => {
abort.abort();
if let Some(pending) = pending.as_mut() { pending.cancelled(); }
return Err(HostError::classified(HostErrorKind::OwnerClosed, "Aimux owner is closed"));
}
_ = cancel.cancelled() => {
abort.abort();
if let Some(pending) = pending.as_mut() { pending.cancelled(); }
return Err(HostError::Cancelled("Model invocation cancelled".into()));
}
result = async {
// Three waits carry the idle allowance: sending the request until
// the response headers, the headers until the stream starts (a
// provider may read the stream before it returns it, and the
// Responses SDK reads response metadata first), and one part
// until the next. `ResponseWatch` reports the headers with the
// instant it produced them, so the second wait runs from receipt.
let result = {
let mut awaiting_headers = true;
let mut headers_arrived = false;
let mut bounded = true;
let mut deadline_at = tokio::time::Instant::now() + stream::STREAM_IDLE_TIMEOUT;
let mut deadline = Box::pin(tokio::time::sleep_until(deadline_at));
let exchange = async {
match &recording {
Some(capture) => capture.scope(model.do_stream(&options)).await,
None => model.do_stream(&options).await,
}
} => match result
.map_err(|error| stream::error(name_redirect_target(error), &cancel))
{
Ok(result) => result,
Err(error) => {
if let Some(pending) = pending.as_mut() {
pending.failed(&error.to_string());
};
tokio::pin!(exchange);
loop {
tokio::select! {
biased;
_ = self.generation.cancelled() => {
abort.abort();
if let Some(pending) = pending.as_mut() { pending.cancelled(); }
return Err(HostError::classified(HostErrorKind::OwnerClosed, "Aimux owner is closed"));
}
_ = cancel.cancelled() => {
abort.abort();
if let Some(pending) = pending.as_mut() { pending.cancelled(); }
return Err(HostError::Cancelled("Model invocation cancelled".into()));
}
_ = &mut deadline, if bounded => {
// A report the transport wrote before the deadline
// is on time even when this poll is late.
if awaiting_headers
&& let Ok(report) = response.try_recv()
&& report.received <= deadline_at
{
awaiting_headers = false;
headers_arrived = true;
if report.status.is_success() {
deadline_at = report.received + stream::STREAM_IDLE_TIMEOUT;
deadline.as_mut().reset(deadline_at);
continue;
}
// A non-2xx reply fails with the status it
// carries; the exchange reports it.
bounded = false;
continue;
}
abort.abort();
let error = stream::idle_failure(if headers_arrived {
headers_arrived_reason(protocol)
} else {
format!(
"no response headers arrived within {} seconds of sending the request",
stream::STREAM_IDLE_TIMEOUT.as_secs()
)
});
if let Some(pending) = pending.as_mut() {
pending.failed(&error.to_string());
}
return Err(error);
}
return Err(error);
report = &mut response, if awaiting_headers => {
awaiting_headers = false;
if let Ok(report) = report {
headers_arrived = true;
if report.status.is_success() {
deadline_at = report.received + stream::STREAM_IDLE_TIMEOUT;
deadline.as_mut().reset(deadline_at);
} else {
// A non-2xx reply fails with the status it
// carries; its body is bounded by the
// transport, and an idle failure here would
// discard that status.
bounded = false;
}
}
}
result = &mut exchange => match result
.map_err(|error| stream::error(name_redirect_target(error), &cancel))
{
Ok(result) => break result,
Err(error) => {
if let Some(pending) = pending.as_mut() {
pending.failed(&error.to_string());
}
return Err(error);
}
},
}
},
}
};
let result = match recording {
Some(capture) => {
Expand Down Expand Up @@ -821,3 +968,6 @@ impl Stream for OwnedStream {
result
}
}

#[cfg(test)]
mod tests;
Loading