From 543a2b155d0a35251f422dc23ab96cb1bc44064b Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:43:51 +0200 Subject: [PATCH] fix(triage): read imperfect batch answers and retry unanswered findings once A batch triage answer was only accepted as a bare JSON array (fences at the very start stripped), with strict field types. Prose around the array, trailing commas, a wrapping object, an answer cut off at max_tokens, or a single field such as "id": 1, "confidence": "7" or "rationale": null failed the whole chunk, and every finding in it went through untriaged. - parse_triage_response: tolerant, pure parser (fences/prose, trailing commas, wrapper object, single verdict object, truncated array salvage); verdicts stay positional, the first unreadable one ends the list - TriageResult: lenient fields (null, numeric strings); the unused echoed id is no longer deserialized - findings a chunk got no verdict for are retried once in chunks half the size; whatever is still unanswered stays as reported (never dropped) - warn lines name how many findings are affected; a 500-char sample of an unreadable answer goes to DEBUG, the prompt never does Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/llm/triage.rs | 513 ++++++++++++++++++++++++----- 1 file changed, 433 insertions(+), 80 deletions(-) diff --git a/compliance-agent/src/llm/triage.rs b/compliance-agent/src/llm/triage.rs index ab70e89..fce0fe3 100644 --- a/compliance-agent/src/llm/triage.rs +++ b/compliance-agent/src/llm/triage.rs @@ -1,6 +1,9 @@ +use std::ops::Range; use std::sync::Arc; use compliance_core::models::{Finding, FindingStatus}; +use serde::{Deserialize, Deserializer}; +use serde_json::Value; use crate::llm::LlmClient; use crate::pipeline::orchestrator::GraphContext; @@ -55,6 +58,8 @@ Respond with a JSON array, one entry per finding in the same order presented (no const TRIAGE_MAX_FINDINGS: usize = 600; /// Triage calls in flight at once. const TRIAGE_CONCURRENCY: usize = 4; +/// How much of an unreadable model answer goes to the debug log. +const RESPONSE_SAMPLE_CHARS: usize = 500; /// The findings the LLM triage looks at, by index: the most severe first, at /// most [`TRIAGE_MAX_FINDINGS`]. @@ -66,14 +71,15 @@ fn triage_selection(findings: &[Finding]) -> Vec { selected } -/// The model's answer for one chunk: its verdicts in chunk order, or `None` -/// when the call failed or its answer could not be read. +/// The model's answer for one chunk: its verdicts in chunk order, at most one +/// per finding. Fewer (none at all when the call failed or its answer could +/// not be read) leave the rest of the chunk without a verdict. async fn triage_chunk( llm: &LlmClient, chunk: &[&Finding], graph_context: Option<&GraphContext>, chunk_start: usize, -) -> Option> { +) -> Vec { let mut user_prompt = String::new(); for (i, finding) in chunk.iter().enumerate() { @@ -141,39 +147,117 @@ async fn triage_chunk( { Ok(response) => response, Err(e) => { - tracing::warn!("LLM batch triage failed for chunk starting at {chunk_start}: {e}"); - return None; + tracing::warn!( + "LLM batch triage failed for chunk starting at {chunk_start}: {e}; {} findings \ + affected, left unchanged unless a retry answers them", + chunk.len() + ); + return Vec::new(); } }; - let cleaned = response.trim(); - let cleaned = if cleaned.starts_with("```") { - cleaned - .trim_start_matches("```json") - .trim_start_matches("```") - .trim_end_matches("```") - .trim() - } else { - cleaned - }; - match serde_json::from_str::>(cleaned) { - Ok(results) => Some(results), - Err(_) => { + let mut verdicts = match parse_triage_response(&response) { + Ok(verdicts) => verdicts, + Err(e) => { tracing::warn!( - "Failed to parse batch triage response for chunk starting at {chunk_start}: {cleaned}" + "Failed to parse batch triage response for chunk starting at {chunk_start}: {e}; \ + {} findings affected, left unchanged unless a retry answers them", + chunk.len() ); - None + // A sample of the answer only, never the prompt (it carries the code). + let sample: String = response.chars().take(RESPONSE_SAMPLE_CHARS).collect(); + tracing::debug!( + "Unreadable batch triage response (first {RESPONSE_SAMPLE_CHARS} chars): {sample}" + ); + return Vec::new(); + } + }; + if verdicts.len() < chunk.len() { + tracing::warn!( + "Batch triage for chunk starting at {chunk_start} answered {} of {} findings", + verdicts.len(), + chunk.len() + ); + } + // Extra verdicts belong to no finding of this chunk. + verdicts.truncate(chunk.len()); + verdicts +} + +/// Ask the model about each batch of positions in `selected`, +/// [`TRIAGE_CONCURRENCY`] batches at a time, and record its verdicts in +/// `verdicts` (indexed like `selected`). +/// +/// # Returns +/// +/// The positions the model gave no verdict for: one range per batch that fell +/// short. +async fn triage_batches( + llm: &LlmClient, + findings: &[Finding], + selected: &[usize], + batches: &[Range], + graph_context: Option<&GraphContext>, + verdicts: &mut [Option], +) -> Vec> { + let chunks: Vec> = batches + .iter() + .map(|range| { + selected[range.clone()] + .iter() + .map(|&i| &findings[i]) + .collect() + }) + .collect(); + // A few calls at once; the answers stay in batch order. + let mut answers: Vec> = Vec::with_capacity(batches.len()); + for (group, ranges) in chunks + .chunks(TRIAGE_CONCURRENCY) + .zip(batches.chunks(TRIAGE_CONCURRENCY)) + { + let calls = group + .iter() + .zip(ranges) + .map(|(chunk, range)| triage_chunk(llm, chunk, graph_context, range.start)); + answers.extend(futures_util::future::join_all(calls).await); + } + + let mut missing = Vec::new(); + for (range, answer) in batches.iter().zip(answers) { + let answered = answer.len(); + for (slot, verdict) in verdicts[range.clone()].iter_mut().zip(answer) { + *slot = Some(verdict); + } + if answered < range.len() { + missing.push(range.start + answered..range.end); } } + missing +} + +/// Split each range in two halves (the first one the larger) for a retry in +/// smaller chunks; a single position stays as it is. +fn halves(ranges: &[Range]) -> Vec> { + ranges + .iter() + .flat_map(|range| { + let mid = range.start + range.len().div_ceil(2); + [range.start..mid, mid..range.end] + }) + .filter(|range| !range.is_empty()) + .collect() } /// Triage `findings` with the LLM, in chunks: confirm, re-rate or flag each /// one. Nothing is removed; a flagged finding is kept as "needs review". The /// most severe findings go first, at most [`TRIAGE_MAX_FINDINGS`], and -/// [`TRIAGE_CONCURRENCY`] chunks are triaged at a time. +/// [`TRIAGE_CONCURRENCY`] chunks are triaged at a time. Findings a chunk got +/// no verdict for (the call failed, the answer was unreadable or cut short) +/// are asked about once more, in chunks half the size; whatever is still +/// unanswered then stays as reported. /// /// # Returns /// -/// How many findings passed triage (confirmed or re-rated). +/// How many findings passed triage (confirmed, re-rated, or left unchanged). pub async fn triage_findings( llm: &Arc, findings: &mut [Finding], @@ -188,53 +272,210 @@ pub async fn triage_findings( ); } - // Ask for every chunk first (read-only), a few at a time, then apply the - // answers. - let chunks: Vec<&[usize]> = selected.chunks(TRIAGE_CHUNK_SIZE).collect(); - let mut answers: Vec>> = Vec::with_capacity(chunks.len()); - { - let read: &[Finding] = findings; - for (group_no, group) in chunks.chunks(TRIAGE_CONCURRENCY).enumerate() { - let batches: Vec> = group - .iter() - .map(|indices| indices.iter().map(|&i| &read[i]).collect()) - .collect(); - let calls = batches.iter().enumerate().map(|(k, batch)| { - let start = (group_no * TRIAGE_CONCURRENCY + k) * TRIAGE_CHUNK_SIZE; - triage_chunk(llm, batch, graph_context, start) - }); - answers.extend(futures_util::future::join_all(calls).await); + // Ask for every chunk first (read-only), then apply the answers. + let mut verdicts: Vec> = (0..selected.len()).map(|_| None).collect(); + let batches: Vec> = (0..selected.len()) + .step_by(TRIAGE_CHUNK_SIZE) + .map(|start| start..(start + TRIAGE_CHUNK_SIZE).min(selected.len())) + .collect(); + let missing = triage_batches( + llm, + findings, + &selected, + &batches, + graph_context, + &mut verdicts, + ) + .await; + if !missing.is_empty() { + // One retry only, in smaller chunks: whatever is left after it stays as reported. + let retry = halves(&missing); + tracing::info!( + "LLM triage: retrying {} findings in {} smaller chunks", + retry.iter().map(Range::len).sum::(), + retry.len() + ); + let unanswered: usize = triage_batches( + llm, + findings, + &selected, + &retry, + graph_context, + &mut verdicts, + ) + .await + .iter() + .map(Range::len) + .sum(); + if unanswered > 0 { + tracing::warn!( + "LLM triage: no verdict for {unanswered} findings after a retry; \ + they stay unchanged, as reported" + ); } } - let answers = chunks.into_iter().zip(answers); let mut passed = 0; - for (indices, answer) in answers { - for (pos, &i) in indices.iter().enumerate() { - let finding = &mut findings[i]; - // No usable answer for the chunk, or none for this finding: keep - // it as reported. - let Some(result) = answer.as_ref().and_then(|results| results.get(pos)) else { - finding.status = FindingStatus::Triaged; - passed += 1; - continue; - }; - let file_classification = classify_file_path(finding.file_path.as_deref()); - let adjusted_confidence = adjust_confidence(result.confidence, &file_classification); - finding.confidence = Some(adjusted_confidence); - finding.triage_action = Some(result.action.clone()); - finding.triage_rationale = Some(result.rationale.clone()); - if let Some(ref remediation) = result.remediation { - finding.remediation = Some(remediation.clone()); - } - if apply_action(finding, &result.action, adjusted_confidence) { - passed += 1; - } + for (&i, verdict) in selected.iter().zip(&verdicts) { + let finding = &mut findings[i]; + // No usable answer for this finding: keep it as reported. + let Some(result) = verdict else { + finding.status = FindingStatus::Triaged; + passed += 1; + continue; + }; + let file_classification = classify_file_path(finding.file_path.as_deref()); + let adjusted_confidence = adjust_confidence(result.confidence, &file_classification); + finding.confidence = Some(adjusted_confidence); + finding.triage_action = Some(result.action.clone()); + finding.triage_rationale = Some(result.rationale.clone()); + if let Some(ref remediation) = result.remediation { + finding.remediation = Some(remediation.clone()); + } + if apply_action(finding, &result.action, adjusted_confidence) { + passed += 1; } } passed } +/// Why a batch triage answer could not be read. +#[derive(Debug, PartialEq, thiserror::Error)] +enum TriageParseError { + /// Neither a JSON array of verdicts, an object wrapping one, nor a single + /// verdict object was found in the answer. + #[error("no JSON array of verdicts in the answer")] + NoVerdicts, +} + +/// Read the model's verdicts from its batch answer, tolerating what models +/// tend to wrap around the JSON: markdown fences, prose before or after, +/// trailing commas, an object wrapping the array (`{"results": [...]}`), a +/// bare object for a single finding, and an answer cut off mid-array (the +/// complete leading verdicts are kept). Verdicts stay in answer order; the +/// first element that is not a verdict ends the list, so no later verdict is +/// matched to the wrong finding. +/// +/// # Errors +/// +/// [`TriageParseError::NoVerdicts`] when no verdict can be read. +fn parse_triage_response(response: &str) -> Result, TriageParseError> { + // Every `[` is a candidate start: prose before the array may hold one too. + let from_array = response + .match_indices('[') + .filter_map(|(start, _)| repair_json(&response[start..])) + .find_map(|json| verdicts_in(serde_json::from_str(&json).ok()?)); + if let Some(verdicts) = from_array { + return Ok(verdicts); + } + // No array at all: a lone verdict object (a one-finding chunk). + response + .find('{') + .and_then(|start| repair_json(&response[start..])) + .and_then(|json| verdicts_in(serde_json::from_str(&json).ok()?)) + .ok_or(TriageParseError::NoVerdicts) +} + +/// The leading verdicts in a parsed answer: an array of objects, an object +/// wrapping one, or a single verdict object; `None` when there is no verdict. +fn verdicts_in(value: Value) -> Option> { + let items = match value { + Value::Array(items) => items, + Value::Object(mut map) => { + // `Value::take` moves the array out, leaving `null` in its place. + match map + .values_mut() + .find(|v| is_object_array(v)) + .map(Value::take) + { + Some(Value::Array(items)) => items, + _ if map.contains_key("action") => vec![Value::Object(map)], + _ => return None, + } + } + Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => return None, + }; + // An array of anything else (`[1]` in prose) is not the answer. + if !items.first().is_some_and(Value::is_object) { + return None; + } + let verdicts: Vec = items + .into_iter() + .map_while(|item| serde_json::from_value(item).ok()) + .collect(); + // No verdict at all: keep looking (an empty `[]` in prose is not the answer). + (!verdicts.is_empty()).then_some(verdicts) +} + +/// `true` for a non-empty array whose elements are all objects. +fn is_object_array(value: &Value) -> bool { + matches!(value, Value::Array(items) if !items.is_empty() && items.iter().all(Value::is_object)) +} + +/// The JSON value `text` starts with (`[` or `{`), made parseable: anything +/// after its closing bracket is cut off, trailing commas are dropped, and an +/// array cut off mid-element is closed after its last complete element. +/// `None` when `text` does not start with a bracket, the brackets do not +/// match, or a cut-off value has no complete element to keep. +fn repair_json(text: &str) -> Option { + let mut out = String::with_capacity(text.len() + 1); + // Closing brackets still expected, innermost last. + let mut open: Vec = Vec::new(); + let mut in_string = false; + let mut escaped = false; + // Length of `out` after the last complete element of the outermost array. + let mut last_element_end = None; + for c in text.chars() { + if out.is_empty() && c != '[' && c != '{' { + return None; + } + if in_string { + out.push(c); + if escaped { + escaped = false; + } else if c == '\\' { + escaped = true; + } else if c == '"' { + in_string = false; + } + continue; + } + match c { + '"' => in_string = true, + '[' => open.push(']'), + '{' => open.push('}'), + ']' | '}' => { + drop_trailing_comma(&mut out); + if open.pop() != Some(c) { + return None; + } + match open.len() { + 0 => { + out.push(c); + return Some(out); + } + 1 if text.starts_with('[') => last_element_end = Some(out.len() + 1), + _ => {} + } + } + _ => {} + } + out.push(c); + } + // Cut off: keep the complete leading elements of an outermost array. + out.truncate(last_element_end?); + out.push(']'); + Some(out) +} + +/// Remove a `,` (and the whitespace after it) at the end of `json`. +fn drop_trailing_comma(json: &mut String) { + let trimmed = json.trim_end(); + if trimmed.ends_with(',') { + json.truncate(trimmed.len() - 1); + } +} + /// Apply the model's `action` to `finding`; `true` when it passed triage. /// /// A dismissed or low-confidence finding is kept as @@ -373,18 +614,20 @@ fn upgrade_severity( } } -#[derive(serde::Deserialize)] +/// The model's verdict on one finding. Verdicts are matched to findings by +/// position, so the echoed `id` is not read (a model may echo the finding +/// number instead of the fingerprint). Every field is read leniently: a +/// `null`, a number sent as a string, or a missing field takes the default +/// rather than failing the whole verdict. +#[derive(Deserialize)] struct TriageResult { - /// Finding fingerprint echoed back by the LLM (optional). - #[serde(default)] - #[allow(dead_code)] - id: String, - #[serde(default = "default_action")] + #[serde(default = "default_action", deserialize_with = "action_or_default")] action: String, - #[serde(default)] + #[serde(default, deserialize_with = "lenient_number")] confidence: f64, - #[serde(default)] + #[serde(default, deserialize_with = "null_as_empty")] rationale: String, + #[serde(default)] remediation: Option, } @@ -392,6 +635,26 @@ fn default_action() -> String { "confirm".to_string() } +/// `action`, with `null` read as the default action. +fn action_or_default<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Ok(Option::::deserialize(deserializer)?.unwrap_or_else(default_action)) +} + +/// A string field, with `null` read as empty. +fn null_as_empty<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Ok(Option::::deserialize(deserializer)?.unwrap_or_default()) +} + +/// A number, also when sent as a string (`"7"`); `0` for `null` or anything +/// that is not a number. +fn lenient_number<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Ok(match Value::deserialize(deserializer)? { + Value::Number(n) => n.as_f64().unwrap_or_default(), + Value::String(s) => s.trim().parse().unwrap_or_default(), + Value::Null | Value::Bool(_) | Value::Array(_) | Value::Object(_) => 0.0, + }) +} + #[cfg(test)] mod tests { @@ -656,17 +919,107 @@ mod tests { } #[test] - fn triage_result_with_markdown_fences() { - // Simulate LLM wrapping response in markdown code fences - let raw = "```json\n{\"action\":\"upgrade\",\"confidence\":9,\"rationale\":\"critical\",\"remediation\":null}\n```"; - let cleaned = raw - .trim() - .trim_start_matches("```json") - .trim_start_matches("```") - .trim_end_matches("```") - .trim(); - let r: TriageResult = serde_json::from_str(cleaned).unwrap(); - assert_eq!(r.action, "upgrade"); - assert_eq!(r.confidence, 9.0); + fn triage_result_reads_nulls_numeric_strings_and_numeric_ids() { + let json = r#"{"id":3,"action":null,"confidence":"7","rationale":null,"remediation":null}"#; + let r: TriageResult = serde_json::from_str(json).unwrap(); + assert_eq!(r.action, "confirm"); + assert_eq!(r.confidence, 7.0); + assert_eq!(r.rationale, ""); + assert!(r.remediation.is_none()); + } + + // ── Batch response parsing ─────────────────────────────────── + + fn actions(response: &str) -> Vec { + parse_triage_response(response) + .unwrap() + .into_iter() + .map(|r| r.action) + .collect() + } + + #[test] + fn parses_a_plain_array() { + let raw = r#"[{"action":"dismiss","confidence":1},{"action":"confirm","confidence":8}]"#; + assert_eq!(actions(raw), ["dismiss", "confirm"]); + } + + #[test] + fn parses_a_fenced_array() { + let raw = "```json\n[{\"action\":\"upgrade\",\"confidence\":9}]\n```"; + assert_eq!(actions(raw), ["upgrade"]); + } + + #[test] + fn parses_an_array_between_prose() { + let raw = "Here is my triage [2 findings]:\n```\n[{\"action\":\"dismiss\",\ + \"rationale\":\"uses buf[0] safely\"},{\"action\":\"confirm\"}]\n```\n\ + Let me know if you need more."; + assert_eq!(actions(raw), ["dismiss", "confirm"]); + } + + #[test] + fn parses_trailing_commas() { + let raw = r#"[{"action":"dismiss","confidence":2,}, {"action":"confirm"},]"#; + assert_eq!(actions(raw), ["dismiss", "confirm"]); + } + + #[test] + fn parses_an_object_wrapping_the_array() { + let raw = r#"{"results": [{"action":"downgrade"},{"action":"confirm"}]}"#; + assert_eq!(actions(raw), ["downgrade", "confirm"]); + } + + #[test] + fn parses_a_single_verdict_object() { + let raw = r#"```json +{"action":"dismiss","confidence":1,"rationale":"test code"} +```"#; + assert_eq!(actions(raw), ["dismiss"]); + } + + #[test] + fn a_truncated_array_keeps_its_complete_verdicts() { + let raw = r#"[{"action":"dismiss","rationale":"a } in [text]"},{"action":"confirm"},{"action":"upg"#; + assert_eq!(actions(raw), ["dismiss", "confirm"]); + } + + #[test] + fn a_verdict_that_cannot_be_read_ends_the_list() { + // The third verdict must not slide onto the second finding. + let raw = r#"[{"action":"dismiss"},{"action":["x"]},{"action":"confirm"}]"#; + assert_eq!(actions(raw), ["dismiss"]); + let raw = r#"[{"action":"dismiss"},null,{"action":"confirm"}]"#; + assert_eq!(actions(raw), ["dismiss"]); + } + + #[test] + fn an_empty_array_in_prose_is_not_the_answer() { + let raw = r#"No dependencies []. Verdicts: [{"action":"confirm"}]"#; + assert_eq!(actions(raw), ["confirm"]); + } + + #[test] + fn garbage_is_an_error() { + for raw in [ + "", + "I cannot triage these findings.", + "[1, 2, 3]", + "{\"note\": \"nothing here\"}", + "[{\"action\":\"dismi", + ] { + assert_eq!( + parse_triage_response(raw).err(), + Some(TriageParseError::NoVerdicts), + "{raw}" + ); + } + } + + #[test] + fn the_retry_halves_each_unanswered_range() { + assert_eq!(halves(&[Range { start: 0, end: 9 }]), [0..5, 5..9]); + assert_eq!(halves(&[3..4, 30..60]), [3..4, 30..45, 45..60]); + assert!(halves(&[]).is_empty()); } }