fix(triage): every critical/high finding gets a verdict, stored on rescans too (#462)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 9m37s
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 9m37s
The LLM triage of the first pilot scans left 74 of 75 findings without a triage_action. Three causes: - Partial answers: 30 findings per call with a 4096-token budget that a reasoning model spends on thinking and the answer together. The answer was cut off after a few verdicts; #457 only retries an empty answer. Verdicts were also matched by position and the echoed id was ignored, so a finding the model left out shifted every later verdict. - Not persisted: write_back stored triage fields only on rows this run inserted. A rescan (or a scan restarted after stages 1-4 had saved its findings) triaged them, then dropped the result. - Unanswered findings were marked "triaged" and counted as "passed". Now: - 10 findings per call with a 12k budget (below #457's retry budget); verdicts matched by id (the finding's number in the chunk, or its fingerprint), by position only when the answer carries no ids - findings without a verdict are asked again by id in chunks half the size, then each critical/high one on its own - one call per fingerprint: copies (gitleaks reports a secret once per commit) share the verdict - low/info findings are not sent; recorded as triage_action "skipped", rationale "skipped: low"; likewise "skipped: over cap" and "skipped: no answer". Skipped findings keep their status (open). - write_back stores triage on rows an earlier run stored while nobody has decided about them (open/triaged/needs_review); a skip never replaces an earlier verdict; status still only onto open rows - one summary line per scan replaces "N findings passed confidence threshold": triaged by outcome, skipped by reason, LLM calls - dismissed and low-confidence findings stay as needs_review (#367): nothing is dropped Tests drive the triage with a fake model: partial answer then retry by id, malformed chunks, model down, threshold, lows and copies, and the stored updates for new and earlier rows. Closes #462 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
This commit is contained in:
1 parent
34688fa322
commit
9f298a60e6
4 files changed
+1069
-257
No files matched your search
@@ -87,6 +87,53 @@ impl LlmClient {
|
||||
})
|
||||
}
|
||||
|
||||
/// Like [`Self::chat`], with a token budget of `max_tokens` (a reasoning
|
||||
/// model spends it on thinking and the answer together), and whether the
|
||||
/// answer was cut off at that budget (`finish_reason: length`): a cut-off
|
||||
/// answer is returned as far as it got, for the caller to use what is
|
||||
/// complete in it.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// As [`Self::chat`].
|
||||
pub async fn chat_with_budget(
|
||||
&self,
|
||||
system_prompt: &str,
|
||||
user_prompt: &str,
|
||||
temperature: Option<f64>,
|
||||
max_tokens: u32,
|
||||
) -> Result<ChatAnswer, AgentError> {
|
||||
let messages = vec![
|
||||
ChatMessage {
|
||||
role: "system".to_string(),
|
||||
content: Some(system_prompt.to_string()),
|
||||
tool_calls: None,
|
||||
tool_call_id: None,
|
||||
},
|
||||
ChatMessage {
|
||||
role: "user".to_string(),
|
||||
content: Some(user_prompt.to_string()),
|
||||
tool_calls: None,
|
||||
tool_call_id: None,
|
||||
},
|
||||
];
|
||||
let request_body = ChatCompletionRequest {
|
||||
model: self.model.clone(),
|
||||
messages,
|
||||
temperature,
|
||||
max_tokens: Some(max_tokens),
|
||||
tools: None,
|
||||
};
|
||||
let (response, finish_reason) = self.send_chat_request_with_reason(&request_body).await?;
|
||||
Ok(ChatAnswer {
|
||||
content: match response {
|
||||
LlmResponse::Content(c) => c,
|
||||
LlmResponse::ToolCalls { .. } => String::new(),
|
||||
},
|
||||
cut_off: finish_reason.as_deref() == Some("length"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Chat with a list of (role, content) messages → text response
|
||||
#[allow(dead_code)]
|
||||
pub async fn chat_with_messages(
|
||||
@@ -171,9 +218,19 @@ impl LlmClient {
|
||||
&self,
|
||||
request_body: &ChatCompletionRequest,
|
||||
) -> Result<LlmResponse, AgentError> {
|
||||
self.send_chat_request_with_reason(request_body)
|
||||
.await
|
||||
.map(|(response, _)| response)
|
||||
}
|
||||
|
||||
/// [`Self::send_chat_request`], and the reason the model stopped.
|
||||
async fn send_chat_request_with_reason(
|
||||
&self,
|
||||
request_body: &ChatCompletionRequest,
|
||||
) -> Result<(LlmResponse, Option<String>), AgentError> {
|
||||
let (response, finish_reason) = self.send_once(request_body).await?;
|
||||
if !exhausted(&response, finish_reason.as_deref()) {
|
||||
return Ok(response);
|
||||
return Ok((response, finish_reason));
|
||||
}
|
||||
if request_body.max_tokens.unwrap_or(0) >= REASONING_RETRY_TOKENS {
|
||||
return Err(AgentError::Other(REASONING_EXHAUSTED.to_string()));
|
||||
@@ -190,7 +247,7 @@ impl LlmClient {
|
||||
if exhausted(&response, finish_reason.as_deref()) {
|
||||
return Err(AgentError::Other(REASONING_EXHAUSTED.to_string()));
|
||||
}
|
||||
Ok(response)
|
||||
Ok((response, finish_reason))
|
||||
}
|
||||
|
||||
/// One chat completion request, and the reason the model stopped.
|
||||
@@ -262,6 +319,15 @@ impl LlmClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// A text answer, and whether the model stopped at its token budget.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ChatAnswer {
|
||||
/// The answer, without the model's reasoning.
|
||||
pub content: String,
|
||||
/// The model was cut off at its token budget: the answer may be partial.
|
||||
pub cut_off: bool,
|
||||
}
|
||||
|
||||
/// The token budget of the second request when the first ran out while the
|
||||
/// model was still reasoning.
|
||||
const REASONING_RETRY_TOKENS: u32 = 16384;
|
||||
|
||||
+800
-217
File diff suppressed because it is too large.
Load diff
@@ -170,12 +170,9 @@ impl RunFindings {
|
||||
Ok(saved)
|
||||
}
|
||||
|
||||
/// Store what triage changed on the findings this run saved, and the
|
||||
/// control refs of findings an earlier run stored. Findings no stage has
|
||||
/// saved yet (the grounded surface checks) are saved first.
|
||||
///
|
||||
/// A status is written only onto a row still `open`: a person who marked
|
||||
/// a finding while the scan ran keeps their choice.
|
||||
/// Store what triage changed on the findings this run saved and on those
|
||||
/// an earlier run stored (see [`row_writes`]). Findings no stage has saved
|
||||
/// yet (the grounded surface checks) are saved first.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
@@ -194,44 +191,29 @@ impl RunFindings {
|
||||
|
||||
let mut new_findings = Vec::new();
|
||||
let mut written: HashSet<&str> = HashSet::new();
|
||||
let mut refreshed = 0_u32;
|
||||
let (mut retriaged, mut refreshed) = (0_u32, 0_u32);
|
||||
for finding in findings.iter() {
|
||||
if !written.insert(finding.fingerprint.as_str()) {
|
||||
continue;
|
||||
}
|
||||
match self.inserted.get(&finding.fingerprint) {
|
||||
Some(id) => {
|
||||
db.findings()
|
||||
.update_one(doc! { "_id": id }, triage_update(finding)?)
|
||||
.await?;
|
||||
if finding.status != FindingStatus::Open {
|
||||
db.findings()
|
||||
.update_one(
|
||||
doc! { "_id": id, "status": "open" },
|
||||
doc! { "$set": { "status": bson_of(&finding.status)? } },
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
new_findings.push(finding.clone());
|
||||
let inserted = self.inserted.get(&finding.fingerprint).copied();
|
||||
for write in row_writes(finding, inserted)? {
|
||||
let result = db.findings().update_one(write.filter, write.update).await?;
|
||||
match write.kind {
|
||||
WriteKind::EarlierTriage if result.matched_count > 0 => retriaged += 1,
|
||||
WriteKind::EarlierControlRefs => refreshed += 1,
|
||||
_ => {}
|
||||
}
|
||||
// A mapping pass (newly enabled or tuned) computed refs for a
|
||||
// finding first stored before it ran.
|
||||
None if !finding.control_refs.is_empty() => {
|
||||
db.findings()
|
||||
.update_one(
|
||||
doc! { "fingerprint": &finding.fingerprint },
|
||||
doc! { "$set": { "control_refs": finding.control_refs.clone() } },
|
||||
)
|
||||
.await?;
|
||||
refreshed += 1;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if inserted.is_some() {
|
||||
new_findings.push(finding.clone());
|
||||
}
|
||||
}
|
||||
if refreshed > 0 {
|
||||
if retriaged > 0 || refreshed > 0 {
|
||||
tracing::info!(
|
||||
scan_run_id = %self.scan_run_id,
|
||||
"refreshed control_refs on {refreshed} existing findings"
|
||||
"stored this run's triage on {retriaged} and refreshed control_refs on \
|
||||
{refreshed} findings an earlier run stored"
|
||||
);
|
||||
}
|
||||
Ok(new_findings)
|
||||
@@ -369,6 +351,104 @@ fn bson_of<T: serde::Serialize>(value: &T) -> Result<Bson, AgentError> {
|
||||
to_bson(value).map_err(|e| AgentError::Other(format!("encode finding field: {e}")))
|
||||
}
|
||||
|
||||
/// What one update in [`RunFindings::write_back`] stores.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum WriteKind {
|
||||
/// The triage fields of a row this run saved.
|
||||
NewTriage,
|
||||
/// The triage's status of a row this run saved, while it is still open.
|
||||
NewStatus,
|
||||
/// The triage fields of a row an earlier run stored.
|
||||
EarlierTriage,
|
||||
/// The triage's status of a row an earlier run stored, while it is still open.
|
||||
EarlierStatus,
|
||||
/// The control refs of a row an earlier run stored.
|
||||
EarlierControlRefs,
|
||||
}
|
||||
|
||||
/// One update of a finding's stored row.
|
||||
#[derive(Debug)]
|
||||
struct RowWrite {
|
||||
kind: WriteKind,
|
||||
filter: Document,
|
||||
update: Document,
|
||||
}
|
||||
|
||||
/// The updates that store what the triage stages changed on `finding`:
|
||||
/// `inserted` is its row id when this run saved it, `None` when an earlier
|
||||
/// run stored it.
|
||||
///
|
||||
/// - Triage fields (action, rationale, severity, confidence, remediation,
|
||||
/// control refs) are stored on a row this run saved, and on an earlier row
|
||||
/// nobody has decided about yet ([`UNDECIDED`]): a rescan triages the
|
||||
/// findings an earlier run stored, and its result must not be lost (#462).
|
||||
/// A "skipped" result never replaces an earlier verdict.
|
||||
/// - A status is written only onto a row still `open`: a person who marked a
|
||||
/// finding keeps their choice.
|
||||
/// - The control refs of an earlier row are refreshed whatever its status (a
|
||||
/// mapping pass newly enabled or tuned).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A field that cannot be encoded.
|
||||
fn row_writes(finding: &Finding, inserted: Option<ObjectId>) -> Result<Vec<RowWrite>, AgentError> {
|
||||
let mut writes = Vec::new();
|
||||
let status = (finding.status != FindingStatus::Open)
|
||||
.then(|| bson_of(&finding.status))
|
||||
.transpose()?;
|
||||
match inserted {
|
||||
Some(id) => {
|
||||
writes.push(RowWrite {
|
||||
kind: WriteKind::NewTriage,
|
||||
filter: doc! { "_id": id },
|
||||
update: triage_update(finding)?,
|
||||
});
|
||||
if let Some(status) = status {
|
||||
writes.push(RowWrite {
|
||||
kind: WriteKind::NewStatus,
|
||||
filter: doc! { "_id": id, "status": "open" },
|
||||
update: doc! { "$set": { "status": status } },
|
||||
});
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if let Some(action) = &finding.triage_action {
|
||||
let mut filter = doc! {
|
||||
"fingerprint": &finding.fingerprint,
|
||||
"status": { "$in": UNDECIDED.to_vec() },
|
||||
};
|
||||
if action == crate::llm::triage::SKIPPED_ACTION {
|
||||
// Matches a row without a triage action too.
|
||||
filter.insert(
|
||||
"triage_action",
|
||||
doc! { "$in": [Bson::Null, crate::llm::triage::SKIPPED_ACTION] },
|
||||
);
|
||||
}
|
||||
writes.push(RowWrite {
|
||||
kind: WriteKind::EarlierTriage,
|
||||
filter,
|
||||
update: triage_update(finding)?,
|
||||
});
|
||||
if let Some(status) = status {
|
||||
writes.push(RowWrite {
|
||||
kind: WriteKind::EarlierStatus,
|
||||
filter: doc! { "fingerprint": &finding.fingerprint, "status": "open" },
|
||||
update: doc! { "$set": { "status": status } },
|
||||
});
|
||||
}
|
||||
}
|
||||
if !finding.control_refs.is_empty() {
|
||||
writes.push(RowWrite {
|
||||
kind: WriteKind::EarlierControlRefs,
|
||||
filter: doc! { "fingerprint": &finding.fingerprint },
|
||||
update: doc! { "$set": { "control_refs": finding.control_refs.clone() } },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(writes)
|
||||
}
|
||||
|
||||
/// The fields the triage stages set, as an update.
|
||||
fn triage_update(finding: &Finding) -> Result<Document, AgentError> {
|
||||
Ok(doc! { "$set": {
|
||||
@@ -381,3 +461,86 @@ fn triage_update(finding: &Finding) -> Result<Document, AgentError> {
|
||||
"updated_at": mongodb::bson::DateTime::now(),
|
||||
} })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use compliance_core::models::{ScanType, Severity};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn triaged(action: &str, status: FindingStatus) -> Finding {
|
||||
let mut f = Finding::new(
|
||||
"repo".into(),
|
||||
"fp-1".into(),
|
||||
"semgrep".into(),
|
||||
ScanType::Sast,
|
||||
"unsafe deserialization".into(),
|
||||
"desc".into(),
|
||||
Severity::High,
|
||||
);
|
||||
f.triage_action = Some(action.into());
|
||||
f.triage_rationale = Some("reachable from a request handler".into());
|
||||
f.status = status;
|
||||
f
|
||||
}
|
||||
|
||||
fn set_of(write: &RowWrite) -> &Document {
|
||||
write.update.get_document("$set").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_rows_triage_and_status_are_stored() {
|
||||
let id = ObjectId::new();
|
||||
let writes = row_writes(&triaged("dismiss", FindingStatus::NeedsReview), Some(id)).unwrap();
|
||||
let kinds: Vec<WriteKind> = writes.iter().map(|w| w.kind).collect();
|
||||
assert_eq!(kinds, [WriteKind::NewTriage, WriteKind::NewStatus]);
|
||||
assert_eq!(set_of(&writes[0]).get_str("triage_action"), Ok("dismiss"));
|
||||
assert_eq!(
|
||||
set_of(&writes[0]).get_str("triage_rationale"),
|
||||
Ok("reachable from a request handler")
|
||||
);
|
||||
assert_eq!(writes[1].filter, doc! { "_id": id, "status": "open" });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_earlier_rows_triage_is_stored_unless_a_person_decided() {
|
||||
// #462: a rescan's verdicts on rows an earlier run stored were dropped.
|
||||
let writes = row_writes(&triaged("confirm", FindingStatus::Triaged), None).unwrap();
|
||||
let kinds: Vec<WriteKind> = writes.iter().map(|w| w.kind).collect();
|
||||
assert_eq!(kinds, [WriteKind::EarlierTriage, WriteKind::EarlierStatus]);
|
||||
assert_eq!(set_of(&writes[0]).get_str("triage_action"), Ok("confirm"));
|
||||
assert_eq!(
|
||||
set_of(&writes[0]).get_str("triage_rationale"),
|
||||
Ok("reachable from a request handler")
|
||||
);
|
||||
assert_eq!(
|
||||
writes[0].filter,
|
||||
doc! { "fingerprint": "fp-1", "status": { "$in": ["open", "triaged", "needs_review"] } }
|
||||
);
|
||||
assert_eq!(
|
||||
writes[1].filter,
|
||||
doc! { "fingerprint": "fp-1", "status": "open" }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_skip_never_replaces_an_earlier_verdict() {
|
||||
let writes = row_writes(&triaged("skipped", FindingStatus::Open), None).unwrap();
|
||||
assert_eq!(writes.len(), 1, "no status write for an open finding");
|
||||
assert_eq!(
|
||||
writes[0].filter.get_document("triage_action").unwrap(),
|
||||
&doc! { "$in": [Bson::Null, "skipped"] }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untriaged_earlier_row_only_gets_its_control_refs() {
|
||||
let mut f = triaged("confirm", FindingStatus::Open);
|
||||
f.triage_action = None;
|
||||
assert!(row_writes(&f, None).unwrap().is_empty());
|
||||
f.control_refs = vec!["CRA-1".into()];
|
||||
let writes = row_writes(&f, None).unwrap();
|
||||
assert_eq!(writes.len(), 1);
|
||||
assert_eq!(writes[0].kind, WriteKind::EarlierControlRefs);
|
||||
}
|
||||
}
|
||||
@@ -563,13 +563,13 @@ impl PipelineOrchestrator {
|
||||
all_findings.len()
|
||||
);
|
||||
self.update_phase(scan_run_id, ScanPhase::LlmTriage).await;
|
||||
let triaged = crate::llm::triage::triage_findings(
|
||||
&self.llm,
|
||||
let triage = crate::llm::triage::triage_findings(
|
||||
self.llm.as_ref(),
|
||||
&mut all_findings,
|
||||
graph_context.as_ref(),
|
||||
)
|
||||
.await;
|
||||
tracing::info!("[{repo_id}] Triaged: {triaged} findings passed confidence threshold");
|
||||
tracing::info!("[{repo_id}] {triage}");
|
||||
|
||||
// Stage 5b: control triage — stamp findings with the compliance control(s)
|
||||
// they're evidence for and flag control false positives (grounded LLM over
|
||||
|
||||
Reference in new issue
Block a user