Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 59 additions & 1 deletion src/local_review.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ pub async fn run_worker(
emit(
progress,
ProgressEvent::ReviewComplete {
partial: result.as_ref().map_or(true, result_has_error),
partial: result.as_ref().map_or(true, result_is_incomplete),
},
);

Expand Down Expand Up @@ -1651,6 +1651,7 @@ async fn run_worker_in_worktree(
let mut combined_findings = Vec::new();
let mut combined_concerns = Vec::new();
let mut combined_dismissed_concerns = Vec::new();
let mut combined_failed_stages = Vec::new();
let mut combined_related = Vec::new();
let mut combined_related_dismissed = Vec::new();
let mut combined_prior_resolutions = Vec::new();
Expand Down Expand Up @@ -1719,6 +1720,14 @@ async fn run_worker_in_worktree(
if let Some(dismissed) = review.get("dismissed_concerns").and_then(|v| v.as_array()) {
combined_dismissed_concerns.extend(dismissed.clone());
}
if let Some(failed) = review.get("failed_stages").and_then(|v| v.as_array()) {
for f in failed {
let mut failed_val = f.clone();
failed_val["patch_index"] = json!(p_idx);
failed_val["patch_subject"] = json!(patch_subject);
combined_failed_stages.push(failed_val);
}
}
merge_related_preexisting(
review,
p_idx,
Expand Down Expand Up @@ -1798,6 +1807,7 @@ async fn run_worker_in_worktree(
"related_preexisting_dismissed".to_string(),
json!(combined_related_dismissed),
);
obj.insert("failed_stages".to_string(), json!(combined_failed_stages));
if let Some(exec) = design_exec {
total_tokens_in = total_tokens_in.saturating_add(exec.tokens_in);
total_tokens_out = total_tokens_out.saturating_add(exec.tokens_out);
Expand Down Expand Up @@ -1925,6 +1935,20 @@ pub fn result_has_error(result: &Value) -> bool {
.unwrap_or(false)
}

/// The failed stages of every patch review, each stamped with its patch.
pub fn result_failed_stages(result: &Value) -> &[Value] {
result
.get("review")
.and_then(|review| review.get("failed_stages"))
.and_then(Value::as_array)
.map_or(&[], Vec::as_slice)
}

/// True when a patch's review failed or had a failed stage.
pub fn result_is_incomplete(result: &Value) -> bool {
result_has_error(result) || !result_failed_stages(result).is_empty()
}

pub fn result_has_high_or_critical_findings(result: &Value) -> bool {
let Some(findings) = result
.get("review")
Expand Down Expand Up @@ -1967,6 +1991,8 @@ pub fn format_agent_review_output(result: &Value) -> Value {

let status = if result_has_error(result) {
"error"
} else if result_is_incomplete(result) {
"incomplete"
} else if !findings.is_empty() {
"issues_found"
} else {
Expand Down Expand Up @@ -2022,6 +2048,10 @@ pub fn format_agent_review_output(result: &Value) -> Value {
if let Some(partial) = result.get("partial") {
obj.insert("partial".into(), partial.clone());
}
let failed_stages = result_failed_stages(result);
if !failed_stages.is_empty() {
obj.insert("failed_stages".into(), json!(failed_stages));
}
if let Some(err) = result.get("error")
&& !err.is_null()
{
Expand Down Expand Up @@ -3076,6 +3106,34 @@ mod tests {
assert_eq!(formatted_err["error"], "patch 1: timed out");
}

#[test]
fn test_a_review_that_lost_a_stage_is_incomplete() {
let lost = json!({
"review": {
"findings": [{"problem": "missing bounds check", "severity": "High"}],
"concerns": [],
"failed_stages": [{
"stage": "execution-flow",
"error": "LLM output was truncated by provider (e.g. hit max tokens)",
"patch_index": 1,
}],
},
});
assert!(!result_has_error(&lost));
assert!(result_is_incomplete(&lost));
let formatted = format_agent_review_output(&lost);
assert_eq!(formatted["status"], "incomplete");
assert_eq!(formatted["failed_stages"][0]["stage"], "execution-flow");

let whole = json!({"review": {"findings": [], "failed_stages": []}});
assert!(!result_is_incomplete(&whole));
assert!(
format_agent_review_output(&whole)
.get("failed_stages")
.is_none()
);
}

#[tokio::test]
async fn test_build_review_input_from_git_filters_b4_tracker_commit() {
let dir = tempfile::tempdir().unwrap();
Expand Down
43 changes: 40 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ use sashiko::events::{Event, MessageSource, ParsedArticle};
use sashiko::ingestor::Ingestor;
use sashiko::local_review::{
ProgressEvent, ReviewOptions, WorkerOptions, format_agent_review_output, print_worker_json,
result_has_error, result_has_high_or_critical_findings, run_git_review, run_worker_from_stdin,
result_failed_stages, result_has_high_or_critical_findings, result_is_incomplete,
run_git_review, run_worker_from_stdin,
};
use sashiko::project::ProjectId;
use sashiko::prompt_bundle;
Expand Down Expand Up @@ -3297,7 +3298,7 @@ async fn handle_review_command(
}
}

if result_has_error(&result) {
if result_is_incomplete(&result) {
std::process::exit(3);
}
if result_has_high_or_critical_findings(&result) {
Expand Down Expand Up @@ -4193,6 +4194,17 @@ fn write_review_result(
write_colored(out, Color::Red, "Error: ")?;
writeln!(out, "{}", error)?;
}
for lost in result_failed_stages(result) {
let field = |key: &str| lost.get(key).and_then(Value::as_str).unwrap_or("?");
write_colored(out, Color::Red, "\nIncomplete: ")?;
writeln!(
out,
"patch {} lost stage '{}': {}",
lost.get("patch_index").and_then(Value::as_i64).unwrap_or(0),
field("stage"),
field("error")
)?;
}

let Some(review) = result.get("review") else {
return Ok(());
Expand All @@ -4217,7 +4229,7 @@ fn write_review_result(
.and_then(Value::as_array)
.is_some_and(|items| !items.is_empty());

if total == 0 && !result_has_error(result) {
if total == 0 && !result_is_incomplete(result) {
let msg = if has_preexisting {
no_patch_findings_message(true)
} else if has_design_concerns {
Expand Down Expand Up @@ -6514,6 +6526,31 @@ mod tests {
assert!(text.contains(" > return -EINVAL;"), "{text}");
}

#[test]
fn test_write_review_result_names_a_lost_stage() {
let result = serde_json::json!({
"review": {
"findings": [],
"failed_stages": [{
"stage": "execution-flow",
"error": "LLM output was truncated by provider (e.g. hit max tokens)",
"patch_index": 1,
}],
},
});
let mut out = termcolor::NoColor::new(Vec::new());
write_review_result(&mut out, &result, "HEAD", false).unwrap();
let text = String::from_utf8(out.into_inner()).unwrap();
assert!(
text.contains(
"Incomplete: patch 1 lost stage 'execution-flow': LLM output was truncated"
),
"{text}"
);
assert!(!text.contains("No issues found"), "{text}");
assert!(!text.contains("No patch-introduced issues found"), "{text}");
}

#[test]
fn test_worker_parses_the_related_preexisting_floor() {
let cli = Cli::try_parse_from([
Expand Down
1 change: 1 addition & 0 deletions src/notes/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1361,6 +1361,7 @@ mod tests {
tokens_cached: 0,
history_start: 0,
history_end: 3,
error: None,
}],
..Default::default()
};
Expand Down
9 changes: 9 additions & 0 deletions src/worker/prompts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,14 @@ impl Worker {
state.all_dismissed_concerns.clone()
};
let dismissed_concerns_count = dismissed_concerns.len();
let failed_stages: Vec<Value> = outcome
.stage_runs
.iter()
.filter_map(|r| {
let error = r.error.as_ref()?;
Some(json!({"stage": r.name, "error": error}))
})
.collect();

let review_inline = if state.review_inline.is_empty() && !self.skip_report {
"No issues found.".to_string()
Expand All @@ -716,6 +724,7 @@ impl Worker {
"fixes": state.fixes,
"concerns_count": concerns_count,
"dismissed_concerns_count": dismissed_concerns_count,
"failed_stages": failed_stages,
"review_map": review_map,
});

Expand Down
62 changes: 61 additions & 1 deletion src/workflow/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ pub struct StageRunRecord {
pub tokens_cached: u32,
pub history_start: usize,
pub history_end: usize,
/// Why the stage failed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}

/// Execution outcome and aggregated metrics from running a workflow.
Expand Down Expand Up @@ -67,6 +70,7 @@ impl std::fmt::Display for WorkflowFailure {
impl std::error::Error for WorkflowFailure {}

fn stage_outcome_from_error(err: &anyhow::Error) -> StageOutcome {
let error = Some(err.to_string());
if let Some(failure) = err.downcast_ref::<crate::ai::SessionFailure>() {
StageOutcome {
tokens_in: u32::try_from(failure.usage.prompt_tokens).unwrap_or(u32::MAX),
Expand All @@ -75,10 +79,12 @@ fn stage_outcome_from_error(err: &anyhow::Error) -> StageOutcome {
.unwrap_or(u32::MAX),
history: failure.history.clone(),
skipped: false,
error,
}
} else {
StageOutcome {
skipped: false,
error,
..Default::default()
}
}
Expand Down Expand Up @@ -108,6 +114,7 @@ fn record_stage_outcome(
tokens_cached: stage_outcome.tokens_cached,
history_start,
history_end,
error: stage_outcome.error,
});
}

Expand Down Expand Up @@ -468,6 +475,7 @@ mod tests {
if content == "__ERROR__" {
anyhow::bail!("simulated fatal provider error");
}
let truncated = content == "__TRUNCATED__";
Ok(AiResponse {
content: Some(content),
thought: None,
Expand All @@ -479,7 +487,7 @@ mod tests {
total_tokens: 15,
cached_tokens: None,
}),
truncated: false,
truncated,
})
}

Expand Down Expand Up @@ -662,6 +670,58 @@ mod tests {
assert!(!outcome.stage_runs[1].skipped);
assert_eq!(outcome.stage_runs[1].history_start, 1);
assert_eq!(outcome.stage_runs[1].history_end, 3);
assert!(outcome.stage_runs[0].error.is_some());
assert_eq!(outcome.stage_runs[1].error, None);
}

#[tokio::test]
async fn test_workflow_best_effort_records_a_truncated_stage() {
let provider = Arc::new(MockProvider::queued(vec![
"__TRUNCATED__".to_string(),
r#"{"items": ["concern_ok"]}"#.to_string(),
]));
let tmp = tempfile::tempdir().unwrap();
let tools = Arc::new(ToolBox::new(tmp.path().to_path_buf()));
let env = WorkflowEnv {
provider,
tools,
base_dir: tmp.path(),
context_tag: None,
};

let mut state = DummyState::default();
let stage = |name| -> Box<dyn ExecutableStage<DummyState>> {
Box::new(
Stage::builder(name)
.user_prompt(PromptTemplate::new("Analyze"))
.output_format(OutputFormat::json())
.reduce(|s: &mut DummyState, out: DummyConcernsOutput| {
s.concerns.extend(out.items);
})
.build(),
)
};
let workflow = Workflow::builder("best_effort_truncated")
.parallel(
vec![stage("stage_cut"), stage("stage_ok")],
ParallelPolicy::BestEffort,
)
.build();

let outcome = WorkflowEngine::execute(&workflow, &env, &mut state, None)
.await
.expect("one stage finishing keeps the batch alive");
assert_eq!(state.concerns, vec!["concern_ok".to_string()]);
let cut = &outcome.stage_runs[0];
assert_eq!(cut.name, "stage_cut");
assert!(
cut.error
.as_deref()
.is_some_and(|e| e.contains("truncated")),
"the record must say why the stage is missing, got {:?}",
cut.error
);
assert_eq!(outcome.stage_runs[1].error, None);
}

#[tokio::test]
Expand Down
4 changes: 4 additions & 0 deletions src/workflow/stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ pub struct StageOutcome {
pub tokens_cached: u32,
pub history: Vec<AiMessage>,
pub skipped: bool,
/// Why the stage failed.
pub error: Option<String>,
}

impl StageOutcome {
Expand Down Expand Up @@ -469,6 +471,7 @@ impl<S: Send + Sync + 'static, T: DeserializeOwned + Send + 'static> ExecutableS
tokens_out: 0,
tokens_cached: 0,
skipped: true,
error: None,
},
Box::new(|_| {}),
));
Expand Down Expand Up @@ -542,6 +545,7 @@ impl<S: Send + Sync + 'static, T: DeserializeOwned + Send + 'static> ExecutableS
tokens_cached,
history: result.history,
skipped: false,
error: None,
};

let reducer = self.reducer.clone();
Expand Down
Loading