From c61368e8ff26b886dc7ea25be6ca393b74d8385c Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:43:30 +0100 Subject: [PATCH] fix(llm): configurable call timeout; one failed triage call is not "model down" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prüfwerk gave up on every LLM call after a fixed 300 s while LiteLLM keeps a request for 600 s: under load (two scans, median 57 s, p95 235 s per call on prod) calls were dropped that the gateway was still working on, and the abandoned work kept the model busy. - LLM_TIMEOUT_SECS (default 600, the gateway's request timeout) sets the total time per call; LlmClient::with_timeout. - Triage takes the model as down only when at least two calls in flight fail at once. A small scan sends one call per try, so one timeout used to skip the retries, including the one-by-one try for critical and high findings (prod 03.11.: 4 critical/high findings left without a verdict). Co-Authored-By: Claude Opus 5.5 --- .env.example | 3 ++ compliance-agent/src/agent.rs | 15 ++++--- compliance-agent/src/config.rs | 4 ++ compliance-agent/src/llm/client.rs | 26 ++++++++--- compliance-agent/src/llm/triage.rs | 70 +++++++++++++++++++++++++----- compliance-core/src/config.rs | 5 +++ 6 files changed, 99 insertions(+), 24 deletions(-) diff --git a/.env.example b/.env.example index 50db198..e354682 100644 --- a/.env.example +++ b/.env.example @@ -7,6 +7,9 @@ LITELLM_URL=http://localhost:4000 LITELLM_API_KEY= LITELLM_MODEL=Qwen3.8-27B LITELLM_EMBED_MODEL=bge-multilingual-gemma2 +# Seconds one LLM call may take in total, the gateway's queue included. Keep it +# at the gateway's request timeout (LiteLLM: 600). +LLM_TIMEOUT_SECS=600 # GitHub GITHUB_TOKEN= diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index 7210ac9..20a8390 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -63,12 +63,15 @@ impl ComplianceAgent { "LITELLM_MODEL / LITELLM_EMBED_MODEL not set: those LLM parts are off" ); } - let llm = Arc::new(LlmClient::new( - config.litellm_url.clone(), - config.litellm_api_key.clone(), - config.litellm_model.clone(), - config.litellm_embed_model.clone(), - )); + let llm = Arc::new( + LlmClient::new( + config.litellm_url.clone(), + config.litellm_api_key.clone(), + config.litellm_model.clone(), + config.litellm_embed_model.clone(), + ) + .with_timeout(std::time::Duration::from_secs(config.llm_timeout_secs)), + ); let http = reqwest::Client::builder() .timeout(std::time::Duration::from_secs(30)) .connect_timeout(std::time::Duration::from_secs(10)) diff --git a/compliance-agent/src/config.rs b/compliance-agent/src/config.rs index c221469..c17b67b 100644 --- a/compliance-agent/src/config.rs +++ b/compliance-agent/src/config.rs @@ -53,6 +53,10 @@ fn build_config(app_env: AppEnv) -> Result { // unset model means the LLM parts are off (LlmClient refuses to call). litellm_model: env_var_opt("LITELLM_MODEL").unwrap_or_default(), litellm_embed_model: env_var_opt("LITELLM_EMBED_MODEL").unwrap_or_default(), + llm_timeout_secs: env_var_opt("LLM_TIMEOUT_SECS") + .and_then(|v| v.parse::().ok()) + .filter(|n| *n > 0) + .unwrap_or(600), github_token: env_secret_opt("GITHUB_TOKEN"), github_webhook_secret: env_secret_opt("GITHUB_WEBHOOK_SECRET"), gitlab_url: env_var_opt("GITLAB_URL"), diff --git a/compliance-agent/src/llm/client.rs b/compliance-agent/src/llm/client.rs index 44fa12d..5b315a2 100644 --- a/compliance-agent/src/llm/client.rs +++ b/compliance-agent/src/llm/client.rs @@ -19,20 +19,22 @@ impl LlmClient { model: String, embed_model: String, ) -> Self { - let http = reqwest::Client::builder() - .timeout(std::time::Duration::from_secs(300)) - .connect_timeout(std::time::Duration::from_secs(10)) - .build() - .unwrap_or_default(); Self { base_url, api_key, model, embed_model, - http, + http: http_client(DEFAULT_TIMEOUT), } } + /// The same client with `timeout` for each call in total (connecting, the + /// gateway's queue and the answer). + pub fn with_timeout(mut self, timeout: std::time::Duration) -> Self { + self.http = http_client(timeout); + self + } + pub(crate) fn chat_url(&self) -> String { format!( "{}/v1/chat/completions", @@ -338,6 +340,18 @@ pub struct ChatAnswer { /// model was still reasoning. const REASONING_RETRY_TOKENS: u32 = 16384; +/// Total time per LLM call unless the deployment sets one (`LLM_TIMEOUT_SECS`): +/// our LiteLLM gateway's own request timeout. +const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600); + +fn http_client(timeout: std::time::Duration) -> reqwest::Client { + reqwest::Client::builder() + .timeout(timeout) + .connect_timeout(std::time::Duration::from_secs(10)) + .build() + .unwrap_or_default() +} + /// The error when the model gave no answer even with /// [`REASONING_RETRY_TOKENS`]. const REASONING_EXHAUSTED: &str = diff --git a/compliance-agent/src/llm/triage.rs b/compliance-agent/src/llm/triage.rs index c96f570..b853c89 100644 --- a/compliance-agent/src/llm/triage.rs +++ b/compliance-agent/src/llm/triage.rs @@ -65,6 +65,8 @@ Respond with a JSON array, one entry per finding (no markdown fences). "id" is t const TRIAGE_MAX_FINDINGS: usize = 600; /// Triage calls in flight at once. const TRIAGE_CONCURRENCY: usize = 4; +/// Calls in flight that must all fail before the model is taken as down. +const MODEL_DOWN_AFTER: usize = 2; /// How much of an unreadable model answer goes to the debug log. const RESPONSE_SAMPLE_CHARS: usize = 500; @@ -492,10 +494,13 @@ async fn ask_in_chunks( .map(|chunk| triage_chunk(model, findings, chunk, graph_context, exploitation)), ) .await; - // Every call at once failed: the model is down (or hangs until the - // client's timeout), not cutting answers short. Asking about the - // rest, chunk by chunk and then one by one, would only take hours. - if answers.iter().all(Result::is_err) { + // Several calls at once all failed: the model is down (or hangs until + // the client's timeout), not cutting answers short. Asking about the + // rest, chunk by chunk and then one by one, would only take hours. A + // single failed call proves nothing (one slow answer under load), so + // the next try still runs: in a small scan the one-by-one try for the + // critical and high findings is all that gets them a verdict. + if group.len() >= MODEL_DOWN_AFTER && answers.iter().all(Result::is_err) { return (answered, Some(ModelDown)); } answered.extend(answers.into_iter().flatten().flatten()); @@ -514,8 +519,9 @@ const TRIES: [(usize, Severity); 3] = [ ]; /// Ask the model about every finding at `sent`, and again by id about those it -/// gave no verdict (see [`TRIES`]). Once every call in flight fails at once, -/// the model is taken as down and nothing more is asked. +/// gave no verdict (see [`TRIES`]). Once several calls in flight fail at once +/// ([`MODEL_DOWN_AFTER`]), the model is taken as down and nothing more is +/// asked. /// /// # Returns /// @@ -1491,6 +1497,18 @@ mod tests { } } + /// Fails the first `failures` calls (a timeout), then answers as + /// [`Self::scripted`]. + fn failing_first(failures: usize, answers: &[&str]) -> Self { + let model = Self::scripted(answers); + model + .script + .lock() + .unwrap() + .extend((0..failures).map(|_| Err("operation timed out".to_string()))); + model + } + fn confirming() -> Self { Self { confirm_all: true, @@ -1618,17 +1636,43 @@ mod tests { #[tokio::test] async fn a_model_that_is_down_skips_but_keeps_every_finding() { - let mut findings: Vec = (1..=3).map(|n| numbered(n, Severity::Critical)).collect(); + let mut findings: Vec = + (1..=15).map(|n| numbered(n, Severity::Critical)).collect(); let model = FakeModel::scripted(&[]); let summary = triage_findings(&model, &mut findings, None, None).await; - assert_eq!(findings.len(), 3); + assert_eq!(findings.len(), 15); assert!(findings .iter() .all(|f| f.triage_action.as_deref() == Some(SKIPPED_ACTION) && f.status == FindingStatus::Open)); - assert_eq!(summary.skipped_no_answer_severe, 3); - // The first call fails: the model is down, nothing is asked again. - assert_eq!(summary.calls, 1); + assert_eq!(summary.skipped_no_answer_severe, 15); + // Both calls of the first try fail: the model is down, nothing is + // asked again. + assert_eq!(summary.calls, 2); + } + + #[tokio::test] + async fn one_failed_call_still_asks_the_severe_findings_one_by_one() { + // A small scan: the first try is one call, and it times out. + let mut findings: Vec = vec![ + numbered(1, Severity::Critical), + numbered(2, Severity::Medium), + numbered(3, Severity::Medium), + ]; + // The second try (one call again) fails as well; the critical one, + // asked on its own, is answered. + let model = FakeModel::failing_first( + 2, + &[r#"{"id":1,"action":"confirm","confidence":9,"rationale":"reachable"}"#], + ); + let summary = triage_findings(&model, &mut findings, None, None).await; + + let asked = model.asked(); + assert_eq!(asked.len(), 3); + assert_eq!(asked[2], ["finding 1"]); + assert_eq!(findings[0].triage_action.as_deref(), Some("confirm")); + assert_eq!(summary.skipped_no_answer, 2); + assert_eq!(summary.skipped_no_answer_severe, 0); } #[tokio::test] @@ -1644,7 +1688,9 @@ mod tests { // The first four chunks are answered, then the model is gone. let model = FakeModel::scripted(&[&full, &full, &full, &full]); let summary = triage_findings(&model, &mut findings, None, None).await; - assert_eq!(summary.calls, 5); + // The fifth call fails alone, so the five are asked once more (one + // call); the last try is for critical and high findings only. + assert_eq!(summary.calls, 6); assert_eq!(summary.confirmed, 40); assert_eq!(summary.skipped_no_answer, 5); } diff --git a/compliance-core/src/config.rs b/compliance-core/src/config.rs index 92a5ff4..530bd77 100644 --- a/compliance-core/src/config.rs +++ b/compliance-core/src/config.rs @@ -9,6 +9,10 @@ pub struct AgentConfig { pub litellm_api_key: SecretString, pub litellm_model: String, pub litellm_embed_model: String, + /// Seconds one LLM call may take in total, waiting in the gateway's queue + /// included (`LLM_TIMEOUT_SECS`, default 600). Keep it at the gateway's own + /// request timeout: a call given up earlier keeps the model busy anyway. + pub llm_timeout_secs: u64, pub github_token: Option, pub github_webhook_secret: Option, pub gitlab_url: Option, @@ -324,6 +328,7 @@ impl Default for AgentConfig { litellm_api_key: SecretString::from(String::new()), litellm_model: String::new(), litellm_embed_model: String::new(), + llm_timeout_secs: 600, github_token: None, github_webhook_secret: None, gitlab_url: None,