O2: gate retry with failure log (#10)
This commit was merged in pull request #10.
This commit is contained in:
1 parent
fb434c670c
commit
2f79b69977
4 files changed
+127
-41
No files matched your search
+10
-3
@@ -7,11 +7,11 @@ use std::path::PathBuf;
|
||||
#[derive(Deserialize, Debug, Default, Clone)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Budget {
|
||||
/// Wall clock limit for the hx run (not the gate). Default 30 min.
|
||||
/// Wall clock limit per hx attempt (not the gate). Default 30 min.
|
||||
pub wall_secs: Option<u64>,
|
||||
/// Max `turn_start` events before hx is killed.
|
||||
/// Max `turn_start` events over the whole run (all attempts) before hx is killed.
|
||||
pub max_turns: Option<u64>,
|
||||
/// Max input+output tokens, summed over `stream/done` events.
|
||||
/// Max input+output tokens over the whole run, summed over `stream/done` events.
|
||||
pub max_tokens: Option<u64>,
|
||||
}
|
||||
|
||||
@@ -31,10 +31,17 @@ pub struct Profile {
|
||||
pub yolo: bool,
|
||||
/// Shell command run in the worktree after hx; exit 0 = pass. None = no gate.
|
||||
pub gate: Option<String>,
|
||||
/// Extra hx attempts after a red gate (default 2). 0 = fail straight to needs-human.
|
||||
#[serde(default = "default_retries")]
|
||||
pub max_retries: u32,
|
||||
#[serde(default)]
|
||||
pub budget: Budget,
|
||||
}
|
||||
|
||||
fn default_retries() -> u32 {
|
||||
2
|
||||
}
|
||||
|
||||
fn default_hx() -> String {
|
||||
"hx".into()
|
||||
}
|
||||
|
||||
+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());
|
||||
}
|
||||
}
|
||||
|
||||
+18
-1
@@ -4,7 +4,7 @@ use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// queued -> running -> gating -> done | failed. (retry and needs-human arrive with O2.)
|
||||
/// queued -> running -> gating -> (retry: running) -> done | failed | needs-human.
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Status {
|
||||
@@ -13,6 +13,8 @@ pub enum Status {
|
||||
Gating,
|
||||
Done,
|
||||
Failed,
|
||||
/// Gate still red after all retries: branch holds the best attempt, gate output in `ID.gate.log`.
|
||||
NeedsHuman,
|
||||
}
|
||||
|
||||
impl Status {
|
||||
@@ -41,6 +43,14 @@ pub struct Run {
|
||||
pub input_tokens: u64,
|
||||
pub output_tokens: u64,
|
||||
pub session: Option<String>,
|
||||
/// hx runs so far (1 + retries).
|
||||
#[serde(default)]
|
||||
pub attempts: u32,
|
||||
/// Budget counters, summed over all attempts.
|
||||
#[serde(default)]
|
||||
pub turns: u64,
|
||||
#[serde(default)]
|
||||
pub spent_tokens: u64,
|
||||
}
|
||||
|
||||
pub fn now() -> u64 {
|
||||
@@ -53,6 +63,10 @@ pub fn runs_dir() -> PathBuf {
|
||||
crate::state_dir().join("runs")
|
||||
}
|
||||
|
||||
pub fn gate_log_path(id: &str) -> PathBuf {
|
||||
runs_dir().join(format!("{id}.gate.log"))
|
||||
}
|
||||
|
||||
pub fn log_path(id: &str) -> PathBuf {
|
||||
runs_dir().join(format!("{id}.log"))
|
||||
}
|
||||
@@ -144,6 +158,9 @@ mod tests {
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
session: None,
|
||||
attempts: 0,
|
||||
turns: 0,
|
||||
spent_tokens: 0,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user