O2: gate retry with failure log, needs-human (closes #3)
This commit is contained in:
1 parent
fb434c670c
commit
5f27fa69eb
4 files changed
+127
-41
No files matched your search
+81
-35
@@ -1,7 +1,7 @@
|
||||
//! One run: worktree -> hx (NDJSON, budgets, process group) -> commit -> gate -> final state.
|
||||
|
||||
use crate::profile::Profile;
|
||||
use crate::state::{Run, Status, kill_group, log_path, now};
|
||||
use crate::state::{Run, Status, gate_log_path, kill_group, log_path, now};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde_json::Value;
|
||||
use std::io::{BufRead, Write};
|
||||
@@ -88,6 +88,9 @@ pub fn new_run(task: &Path, repo: &Path, profile: &str) -> Result<Run> {
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
session: None,
|
||||
attempts: 0,
|
||||
turns: 0,
|
||||
spent_tokens: 0,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -98,7 +101,29 @@ fn fail(r: &mut Run, reason: impl Into<String>) -> Result<()> {
|
||||
r.save()
|
||||
}
|
||||
|
||||
/// Runs the whole pipeline. Errors only for orch-internal problems; task failures end as `Failed` state.
|
||||
/// Max bytes of gate output fed back to hx (the tail: errors are at the end).
|
||||
const GATE_LOG_LIMIT: usize = 8000;
|
||||
|
||||
fn tail(b: &[u8], limit: usize) -> String {
|
||||
let s = String::from_utf8_lossy(&b[b.len().saturating_sub(limit)..]).into_owned();
|
||||
s.trim_start_matches('\u{FFFD}').to_string()
|
||||
}
|
||||
|
||||
fn retry_prompt(gate: &str, code: Option<i32>, out: &[u8], resumed: bool, body: &str) -> String {
|
||||
let task = if resumed {
|
||||
String::new()
|
||||
} else {
|
||||
format!("Task:\n{body}\n\n")
|
||||
};
|
||||
format!(
|
||||
"{task}The check `{gate}` failed (exit {}). Fix the code so it passes. Output (last {GATE_LOG_LIMIT} bytes):\n{}",
|
||||
code.map_or("signal".into(), |c| c.to_string()),
|
||||
tail(out, GATE_LOG_LIMIT)
|
||||
)
|
||||
}
|
||||
|
||||
/// Runs the whole pipeline. Errors only for orch-internal problems; task failures end as `Failed` or
|
||||
/// `NeedsHuman` state. After a failed gate hx gets the gate output on the same session, up to `max_retries`.
|
||||
pub fn execute(r: &mut Run, p: &Profile, task: &Path) -> Result<()> {
|
||||
let (_, body) = read_task(task)?;
|
||||
r.save()?;
|
||||
@@ -108,50 +133,71 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Path) -> Result<()> {
|
||||
fail(r, format!("setup: {e}"))?;
|
||||
return Ok(());
|
||||
}
|
||||
r.status = Status::Running;
|
||||
r.save()?;
|
||||
|
||||
let mut log = std::fs::File::create(log_path(&r.id))?;
|
||||
let reason = run_hx(r, p, &body, &mut log)?;
|
||||
if !git(&r.worktree, &["status", "--porcelain"])?
|
||||
.trim()
|
||||
.is_empty()
|
||||
{
|
||||
// keep hx's work on the branch even when it failed: nothing is lost
|
||||
git(&r.worktree, &["add", "-A"])?;
|
||||
git(
|
||||
&r.worktree,
|
||||
&["commit", "-qm", &format!("orch: {}", r.title)],
|
||||
)?;
|
||||
}
|
||||
if let Some(reason) = reason {
|
||||
return fail(r, reason);
|
||||
}
|
||||
if let Some(gate) = &p.gate {
|
||||
let mut prompt = body.clone();
|
||||
let mut session: Option<String> = None;
|
||||
loop {
|
||||
r.attempts += 1;
|
||||
r.status = Status::Running;
|
||||
r.save()?;
|
||||
writeln!(log, "\n--- attempt {}", r.attempts)?;
|
||||
let reason = run_hx(r, p, &prompt, session.as_deref(), &mut log)?;
|
||||
if !git(&r.worktree, &["status", "--porcelain"])?
|
||||
.trim()
|
||||
.is_empty()
|
||||
{
|
||||
// keep hx's work on the branch even when it failed: nothing is lost
|
||||
git(&r.worktree, &["add", "-A"])?;
|
||||
let msg = format!("orch: {} (attempt {})", r.title, r.attempts);
|
||||
git(&r.worktree, &["commit", "-qm", &msg])?;
|
||||
}
|
||||
if let Some(reason) = reason {
|
||||
return fail(r, reason);
|
||||
}
|
||||
let Some(gate) = &p.gate else { break };
|
||||
r.status = Status::Gating;
|
||||
r.save()?;
|
||||
writeln!(log, "\n--- gate: {gate}")?;
|
||||
let st = Command::new("sh")
|
||||
.args(["-c", gate])
|
||||
// ponytail: no gate timeout; a hanging gate hangs the run. Add gate_secs when it bites.
|
||||
let o = Command::new("sh")
|
||||
.args(["-c", &format!("({gate}) 2>&1")])
|
||||
.current_dir(&r.worktree)
|
||||
.stdout(log.try_clone()?)
|
||||
.stderr(log.try_clone()?)
|
||||
.status()?;
|
||||
r.gate_exit = st.code();
|
||||
if !st.success() {
|
||||
return fail(r, "gate-failed");
|
||||
.output()?;
|
||||
log.write_all(&o.stdout)?;
|
||||
r.gate_exit = o.status.code();
|
||||
if o.status.success() {
|
||||
break;
|
||||
}
|
||||
std::fs::write(gate_log_path(&r.id), &o.stdout)?;
|
||||
if r.attempts > p.max_retries {
|
||||
r.status = Status::NeedsHuman;
|
||||
r.reason = Some("gate-failed".into());
|
||||
r.ended = Some(now());
|
||||
return r.save();
|
||||
}
|
||||
session = r.session.clone();
|
||||
prompt = retry_prompt(gate, r.gate_exit, &o.stdout, session.is_some(), &body);
|
||||
}
|
||||
r.status = Status::Done;
|
||||
r.reason = None;
|
||||
r.ended = Some(now());
|
||||
r.save()
|
||||
}
|
||||
|
||||
/// Returns the failure reason, or None when hx finished cleanly.
|
||||
fn run_hx(r: &mut Run, p: &Profile, body: &str, log: &mut std::fs::File) -> Result<Option<String>> {
|
||||
fn run_hx(
|
||||
r: &mut Run,
|
||||
p: &Profile,
|
||||
body: &str,
|
||||
session: Option<&str>,
|
||||
log: &mut std::fs::File,
|
||||
) -> Result<Option<String>> {
|
||||
let mut parts = p.hx.split_whitespace();
|
||||
let mut cmd = Command::new(parts.next().context("empty hx command")?);
|
||||
cmd.args(parts).args(["-p", body, "--mode", "json"]);
|
||||
if let Some(s) = session {
|
||||
cmd.args(["--session", s]);
|
||||
}
|
||||
if p.sandbox {
|
||||
cmd.arg("--sandbox");
|
||||
}
|
||||
@@ -187,7 +233,7 @@ fn run_hx(r: &mut Run, p: &Profile, body: &str, log: &mut std::fs::File) -> Resu
|
||||
});
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(p.wall_secs());
|
||||
let (mut turns, mut tokens, mut done) = (0u64, 0u64, None::<Value>);
|
||||
let mut done = None::<Value>;
|
||||
let mut killed = None;
|
||||
loop {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
@@ -199,16 +245,16 @@ fn run_hx(r: &mut Run, p: &Profile, body: &str, log: &mut std::fs::File) -> Resu
|
||||
};
|
||||
match ev["type"].as_str() {
|
||||
Some("turn_start") => {
|
||||
turns += 1;
|
||||
if p.budget.max_turns.is_some_and(|m| turns > m) {
|
||||
r.turns += 1;
|
||||
if p.budget.max_turns.is_some_and(|m| r.turns > m) {
|
||||
killed = Some("budget:turns".to_string());
|
||||
}
|
||||
}
|
||||
Some("stream") if ev["event"]["type"] == "done" => {
|
||||
let u = &ev["event"]["usage"];
|
||||
tokens += u["input_tokens"].as_u64().unwrap_or(0)
|
||||
r.spent_tokens += u["input_tokens"].as_u64().unwrap_or(0)
|
||||
+ u["output_tokens"].as_u64().unwrap_or(0);
|
||||
if p.budget.max_tokens.is_some_and(|m| tokens > m) {
|
||||
if p.budget.max_tokens.is_some_and(|m| r.spent_tokens > m) {
|
||||
killed = Some("budget:tokens".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user