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:
andrea.difonzo
2026-11-16 17:59:12 +01:00
parent 437c6b7f5a
commit 4e1f551b84
26 changed files with 504 additions and 114 deletions

View File

@@ -79,6 +79,10 @@ pub fn read_managed_residency_requirement() -> Option<ResidencyRequirement> {
}
const DEFAULT_STREAM_IDLE_TIMEOUT_MS: u64 = 300_000;
/// Local servers (loopback, private network, `.local`/`.lan`) read long prompts on CPU: a cold
/// prompt of 15k tokens took more than 3 minutes before the first byte. They get a generous
/// default, still overridable with `stream_idle_timeout_ms`.
const DEFAULT_LOCAL_STREAM_IDLE_TIMEOUT_MS: u64 = 1_800_000;
const DEFAULT_STREAM_MAX_RETRIES: u64 = 5;
const DEFAULT_REQUEST_MAX_RETRIES: u64 = 4;
const DEFAULT_CREDENTIAL_EXPORT_TIMEOUT_MS: u64 = 30_000;
@@ -198,7 +202,9 @@ pub struct ModelProviderInfo {
/// Number of times to retry reconnecting a dropped streaming response before failing.
pub stream_max_retries: Option<u64>,
/// Idle timeout (in milliseconds) to wait for activity on a streaming response before treating
/// the connection as lost.
/// the connection as lost. It also bounds the wait for the first response (headers). Any
/// bytes count as activity, including SSE comments and progress events. Defaults to 5
/// minutes, or 30 minutes for local servers.
pub stream_idle_timeout_ms: Option<u64>,
/// Maximum time (in milliseconds) to wait for a websocket connection attempt before treating
/// it as failed.
@@ -521,11 +527,23 @@ impl ModelProviderInfo {
.min(MAX_STREAM_MAX_RETRIES)
}
/// Effective idle timeout for streaming responses.
/// Effective idle timeout for streaming responses (and for the first response).
pub fn stream_idle_timeout(&self) -> Duration {
self.stream_idle_timeout_ms
.map(Duration::from_millis)
.unwrap_or(Duration::from_millis(DEFAULT_STREAM_IDLE_TIMEOUT_MS))
.unwrap_or_else(|| {
Duration::from_millis(if self.is_local_endpoint() {
DEFAULT_LOCAL_STREAM_IDLE_TIMEOUT_MS
} else {
DEFAULT_STREAM_IDLE_TIMEOUT_MS
})
})
}
/// Whether `base_url` points to this machine or the local network: loopback, private IPv4,
/// `localhost`, `.localhost`, `.local`, `.lan`.
pub fn is_local_endpoint(&self) -> bool {
self.base_url.as_deref().is_some_and(is_local_base_url)
}
/// Effective timeout for websocket connect attempts.
@@ -656,3 +674,25 @@ pub fn create_oss_provider_with_base_url(base_url: &str, wire_api: WireApi) -> M
#[cfg(test)]
#[path = "model_provider_info_tests.rs"]
mod tests;
/// See [`ModelProviderInfo::is_local_endpoint`].
pub fn is_local_base_url(base_url: &str) -> bool {
let Ok(uri) = base_url.trim().parse::<http::Uri>() else {
return false;
};
let Some(host) = uri.host() else {
return false;
};
let host = host.trim_start_matches('[').trim_end_matches(']');
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
return match ip {
std::net::IpAddr::V4(ip) => ip.is_loopback() || ip.is_private(),
std::net::IpAddr::V6(ip) => ip.is_loopback(),
};
}
let host = host.trim_end_matches('.').to_ascii_lowercase();
host == "localhost"
|| host.ends_with(".localhost")
|| host.ends_with(".local")
|| host.ends_with(".lan")
}

View File

@@ -505,3 +505,30 @@ display_name = "Flint"
assert_eq!(settings.display_name.as_deref(), Some("Flint"));
assert!(provider.model_settings("other").is_none());
}
#[test]
fn local_providers_get_a_generous_idle_timeout() {
let provider = |base_url: &str| -> ModelProviderInfo {
toml::from_str(&format!("name = \"x\"\nbase_url = \"{base_url}\"\n")).expect("provider")
};
for local in [
"http://192.168.40.25:8080/v1",
"http://127.0.0.1:8080/v1",
"http://localhost:11434/v1",
"http://[::1]:1234/v1",
"http://imeai.lan/v1",
] {
assert_eq!(
provider(local).stream_idle_timeout(),
Duration::from_secs(30 * 60),
"{local}"
);
}
assert_eq!(
provider("https://openrouter.ai/api/v1").stream_idle_timeout(),
Duration::from_secs(5 * 60)
);
let mut configured = provider("http://192.168.40.25:8080/v1");
configured.stream_idle_timeout_ms = Some(90_000);
assert_eq!(configured.stream_idle_timeout(), Duration::from_secs(90));
}