aKode: cache del prompt più stabile e attese lunghe dei server locali (punto 4, blocco A)
- Ordine fisso dei blocchi di contesto: le sezioni uguali in ogni sessione (skill, permessi) vengono prima, quelle delle estensioni (<code_map>, riepilogo della memoria) dopo; prima <code_map> stava subito dopo le istruzioni di sistema e cambiava da un repository all'altro. - Strumenti in ordine stabile (per nome, namespace dopo); nella sessione resta l'ordine della prima richiesta e i nuovi strumenti vanno in coda, mai in mezzo. - La prima richiesta aspetta fino a 5 s (prima 1 s) i server MCP in avvio. - Ogni byte ricevuto azzera il timer di inattività: commenti SSE ed eventi imeai.queue/imeai.prefill compresi. Il timeout vale anche per l'attesa delle intestazioni ed è di 30 minuti per i server locali (5 per gli altri). - Niente keepalive TCP nel client HTTP: reqwest sonda dopo 15 s e chiude dopo 3 sonde senza risposta; attraverso NetBird le sonde non passano e ogni risposta partita dopo 60 s veniva tagliata e richiesta da capo. - Test adattati al nuovo ordine degli strumenti (snapshot con soli riordini) e alla nuova attesa dei server MCP. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -132,9 +132,12 @@ impl<T: HttpTransport> ResponsesClient<T> {
|
||||
Compression::Zstd => RequestCompression::Zstd,
|
||||
};
|
||||
|
||||
let stream_response = self
|
||||
.session
|
||||
.stream_encoded_json_with(
|
||||
let idle_timeout = self.session.provider().stream_idle_timeout;
|
||||
// Local servers may send the headers only with the first token, after reading the whole
|
||||
// prompt: the wait is bounded by the same (generous, configurable) idle timeout.
|
||||
let stream_response = tokio::time::timeout(
|
||||
idle_timeout,
|
||||
self.session.stream_encoded_json_with(
|
||||
Method::POST,
|
||||
"/responses",
|
||||
extra_headers,
|
||||
@@ -146,12 +149,19 @@ impl<T: HttpTransport> ResponsesClient<T> {
|
||||
);
|
||||
req.compression = request_compression;
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ApiError::Stream(format!(
|
||||
"nessuna risposta dal server entro {} s (stream_idle_timeout_ms)",
|
||||
idle_timeout.as_secs()
|
||||
))
|
||||
})??;
|
||||
|
||||
Ok(spawn_response_stream(
|
||||
stream_response,
|
||||
self.session.provider().stream_idle_timeout,
|
||||
idle_timeout,
|
||||
self.sse_telemetry.clone(),
|
||||
turn_state,
|
||||
))
|
||||
|
||||
@@ -25,7 +25,6 @@ use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::Instant;
|
||||
use tokio::time::timeout;
|
||||
use tracing::debug;
|
||||
use tracing::trace;
|
||||
|
||||
@@ -536,6 +535,16 @@ async fn process_sse_with_treatment(
|
||||
telemetry: Option<Arc<dyn SseTelemetry>>,
|
||||
safety_buffering_treatment: SafetyBufferingTreatment,
|
||||
) {
|
||||
// Any bytes from the server are a sign of life: SSE comments (`: ...`) and events this
|
||||
// client does not use (`imeai.queue`, `imeai.prefill` while the server waits or reads the
|
||||
// prompt) restart the idle timer, even though the parser yields no event for comments.
|
||||
let last_activity = Arc::new(std::sync::Mutex::new(Instant::now()));
|
||||
let activity = Arc::clone(&last_activity);
|
||||
let stream = stream.inspect(move |chunk| {
|
||||
if chunk.is_ok() {
|
||||
*activity.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Instant::now();
|
||||
}
|
||||
});
|
||||
let mut stream = stream.eventsource();
|
||||
let mut response_error: Option<ApiError> = None;
|
||||
let mut last_server_model: Option<String> = None;
|
||||
@@ -545,7 +554,7 @@ async fn process_sse_with_treatment(
|
||||
let response = tokio::select! {
|
||||
biased;
|
||||
_ = tx_event.closed() => return,
|
||||
response = timeout(idle_timeout, stream.next()) => response,
|
||||
response = next_with_activity_timeout(&mut stream, &last_activity, idle_timeout) => response,
|
||||
};
|
||||
if let Some(t) = telemetry.as_ref() {
|
||||
t.on_sse_poll(&response, start.elapsed());
|
||||
@@ -580,6 +589,11 @@ async fn process_sse_with_treatment(
|
||||
|
||||
trace!("SSE event: {}", &sse.data);
|
||||
|
||||
if is_server_progress_event(&sse.event) {
|
||||
// Queue position and prompt-reading progress: only signs of life for this client.
|
||||
continue;
|
||||
}
|
||||
|
||||
let event: ResponsesStreamEvent = match serde_json::from_str(&sse.data) {
|
||||
Ok(event) => event,
|
||||
Err(e) => {
|
||||
@@ -656,6 +670,40 @@ async fn process_sse_with_treatment(
|
||||
}
|
||||
}
|
||||
|
||||
/// Progress events of local servers (imeAI gateway): `imeai.queue`, `imeai.prefill`, ...
|
||||
fn is_server_progress_event(event: &str) -> bool {
|
||||
event.starts_with("imeai.")
|
||||
}
|
||||
|
||||
/// Waits for the next SSE event; fails only after `idle_timeout` without any bytes at all, so
|
||||
/// keep-alive comments and progress events keep a long prompt read alive.
|
||||
async fn next_with_activity_timeout<S>(
|
||||
stream: &mut S,
|
||||
last_activity: &std::sync::Mutex<Instant>,
|
||||
idle_timeout: Duration,
|
||||
) -> Result<Option<S::Item>, tokio::time::error::Elapsed>
|
||||
where
|
||||
S: futures::Stream + Unpin,
|
||||
{
|
||||
loop {
|
||||
let since = *last_activity
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let deadline = since + idle_timeout;
|
||||
match tokio::time::timeout_at(deadline, stream.next()).await {
|
||||
Ok(item) => return Ok(item),
|
||||
Err(elapsed) => {
|
||||
let latest = *last_activity
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if latest == since {
|
||||
return Err(elapsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "responses_error_tests.rs"]
|
||||
mod error_tests;
|
||||
@@ -1049,6 +1097,62 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Byte stream that sends `chunks` with `gap` of silence before each one, then waits forever.
|
||||
fn paced_stream(chunks: Vec<&'static str>, gap: Duration) -> ByteStream {
|
||||
let stream = stream::iter(chunks).then(move |chunk| async move {
|
||||
tokio::time::sleep(gap).await;
|
||||
Ok::<Bytes, TransportError>(Bytes::from(chunk))
|
||||
});
|
||||
Box::pin(stream.chain(stream::pending()))
|
||||
}
|
||||
|
||||
async fn collect_until_closed(stream: ByteStream) -> Vec<Result<ResponseEvent, ApiError>> {
|
||||
let (tx, mut rx) = mpsc::channel::<Result<ResponseEvent, ApiError>>(16);
|
||||
tokio::spawn(process_sse(stream, tx, idle_timeout(), /*telemetry*/ None));
|
||||
let mut events = Vec::new();
|
||||
while let Some(ev) = rx.recv().await {
|
||||
events.push(ev);
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn keepalive_comments_and_progress_events_reset_the_idle_timer() {
|
||||
// 4 s of waiting and prompt reading with the 1 s idle timeout: each chunk arrives
|
||||
// after 600 ms, so only the bytes themselves keep the stream alive.
|
||||
let completed = r#"event: response.completed
|
||||
data: {"type":"response.completed","response":{"id":"resp1"}}
|
||||
|
||||
"#;
|
||||
let stream = paced_stream(
|
||||
vec![
|
||||
": in coda\n\n",
|
||||
"event: imeai.queue\ndata: {\"queued\":true,\"ahead\":1,\"position\":2}\n\n",
|
||||
": in coda\n\n",
|
||||
"event: imeai.prefill\ndata: {\"percent\":40,\"eta_s\":3.0}\n\n",
|
||||
"event: imeai.prefill\ndata: {\"percent\":90,\"eta_s\":0.5}\n\n",
|
||||
": attesa\n\n",
|
||||
completed,
|
||||
],
|
||||
Duration::from_millis(600),
|
||||
);
|
||||
|
||||
let events = collect_until_closed(stream).await;
|
||||
|
||||
assert_eq!(events.len(), 1, "{events:?}");
|
||||
assert_matches!(&events[0], Ok(ResponseEvent::Completed { response_id, .. }) if response_id == "resp1");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn silence_longer_than_idle_timeout_still_fails() {
|
||||
let stream = paced_stream(vec![": in coda\n\n"], Duration::from_millis(200));
|
||||
|
||||
let events = collect_until_closed(stream).await;
|
||||
|
||||
assert_eq!(events.len(), 1, "{events:?}");
|
||||
assert_matches!(&events[0], Err(ApiError::Stream(message)) if message.contains("idle timeout"));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn rate_limit_error_preserves_retry_delay() {
|
||||
let raw_error = r#"{"type":"response.failed","sequence_number":3,"response":{"id":"resp_689bcf18d7f08194bf3440ba62fe05d803fee0cdac429894","object":"response","created_at":1755041560,"status":"failed","background":false,"error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.1 in organization org-AAA on tokens per min (TPM): Limit 30000, Used 22999, Requested 12528. Please try again in 11.054s. Visit https://platform.openai.com/account/rate-limits to learn more."}, "usage":null,"user":null,"metadata":{}}}"#;
|
||||
|
||||
Reference in New Issue
Block a user