fix(llm): configurable call timeout; one failed triage call is not "model down" (#588)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Dashboard (push) Successful in 4m21s
CI / Deploy MCP (push) Successful in 4m17s
CI / Deploy Agent (push) Successful in 8m51s

This commit was merged in pull request #588.
This commit is contained in:
sharang committed 2026-11-04 08:10:46 +00:00
1 parent 3300bb1851
commit 7d73893485
6 files changed
+99 -24

No files matched your search

+3
View File
@@ -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=
+9 -6
View File
@@ -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))
+4
View File
@@ -53,6 +53,10 @@ fn build_config(app_env: AppEnv) -> Result<AgentConfig, AgentError> {
// 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::<u64>().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"),
+20 -6
View File
@@ -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 =
+58 -12
View File
@@ -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<M: TriageModel>(
.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<Finding> = (1..=3).map(|n| numbered(n, Severity::Critical)).collect();
let mut findings: Vec<Finding> =
(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<Finding> = 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);
}
+5
View File
@@ -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<SecretString>,
pub github_webhook_secret: Option<SecretString>,
pub gitlab_url: Option<String>,
@@ -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,