O2: gate retry with failure log, needs-human (closes #3)

This commit is contained in:
hermes committed 2026-11-12 23:20:48 +00:00
1 parent fb434c670c
commit 5f27fa69eb
4 files changed
+127 -41

No files matched your search

+10 -3
View File
@@ -7,11 +7,11 @@ use std::path::PathBuf;
#[derive(Deserialize, Debug, Default, Clone)] #[derive(Deserialize, Debug, Default, Clone)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct Budget { 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>, 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>, 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>, pub max_tokens: Option<u64>,
} }
@@ -31,10 +31,17 @@ pub struct Profile {
pub yolo: bool, pub yolo: bool,
/// Shell command run in the worktree after hx; exit 0 = pass. None = no gate. /// Shell command run in the worktree after hx; exit 0 = pass. None = no gate.
pub gate: Option<String>, 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)] #[serde(default)]
pub budget: Budget, pub budget: Budget,
} }
fn default_retries() -> u32 {
2
}
fn default_hx() -> String { fn default_hx() -> String {
"hx".into() "hx".into()
} }
+81 -35
View File
@@ -1,7 +1,7 @@
//! One run: worktree -> hx (NDJSON, budgets, process group) -> commit -> gate -> final state. //! One run: worktree -> hx (NDJSON, budgets, process group) -> commit -> gate -> final state.
use crate::profile::Profile; 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 anyhow::{Context, Result, bail};
use serde_json::Value; use serde_json::Value;
use std::io::{BufRead, Write}; use std::io::{BufRead, Write};
@@ -88,6 +88,9 @@ pub fn new_run(task: &Path, repo: &Path, profile: &str) -> Result<Run> {
input_tokens: 0, input_tokens: 0,
output_tokens: 0, output_tokens: 0,
session: None, 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() 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<()> { pub fn execute(r: &mut Run, p: &Profile, task: &Path) -> Result<()> {
let (_, body) = read_task(task)?; let (_, body) = read_task(task)?;
r.save()?; r.save()?;
@@ -108,50 +133,71 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Path) -> Result<()> {
fail(r, format!("setup: {e}"))?; fail(r, format!("setup: {e}"))?;
return Ok(()); return Ok(());
} }
r.status = Status::Running;
r.save()?;
let mut log = std::fs::File::create(log_path(&r.id))?; let mut log = std::fs::File::create(log_path(&r.id))?;
let reason = run_hx(r, p, &body, &mut log)?; let mut prompt = body.clone();
if !git(&r.worktree, &["status", "--porcelain"])? let mut session: Option<String> = None;
.trim() loop {
.is_empty() r.attempts += 1;
{ r.status = Status::Running;
// keep hx's work on the branch even when it failed: nothing is lost r.save()?;
git(&r.worktree, &["add", "-A"])?; writeln!(log, "\n--- attempt {}", r.attempts)?;
git( let reason = run_hx(r, p, &prompt, session.as_deref(), &mut log)?;
&r.worktree, if !git(&r.worktree, &["status", "--porcelain"])?
&["commit", "-qm", &format!("orch: {}", r.title)], .trim()
)?; .is_empty()
} {
if let Some(reason) = reason { // keep hx's work on the branch even when it failed: nothing is lost
return fail(r, reason); git(&r.worktree, &["add", "-A"])?;
} let msg = format!("orch: {} (attempt {})", r.title, r.attempts);
if let Some(gate) = &p.gate { 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.status = Status::Gating;
r.save()?; r.save()?;
writeln!(log, "\n--- gate: {gate}")?; writeln!(log, "\n--- gate: {gate}")?;
let st = Command::new("sh") // ponytail: no gate timeout; a hanging gate hangs the run. Add gate_secs when it bites.
.args(["-c", gate]) let o = Command::new("sh")
.args(["-c", &format!("({gate}) 2>&1")])
.current_dir(&r.worktree) .current_dir(&r.worktree)
.stdout(log.try_clone()?) .output()?;
.stderr(log.try_clone()?) log.write_all(&o.stdout)?;
.status()?; r.gate_exit = o.status.code();
r.gate_exit = st.code(); if o.status.success() {
if !st.success() { break;
return fail(r, "gate-failed");
} }
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.status = Status::Done;
r.reason = None;
r.ended = Some(now()); r.ended = Some(now());
r.save() r.save()
} }
/// Returns the failure reason, or None when hx finished cleanly. /// 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 parts = p.hx.split_whitespace();
let mut cmd = Command::new(parts.next().context("empty hx command")?); let mut cmd = Command::new(parts.next().context("empty hx command")?);
cmd.args(parts).args(["-p", body, "--mode", "json"]); cmd.args(parts).args(["-p", body, "--mode", "json"]);
if let Some(s) = session {
cmd.args(["--session", s]);
}
if p.sandbox { if p.sandbox {
cmd.arg("--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 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; let mut killed = None;
loop { loop {
let left = deadline.saturating_duration_since(Instant::now()); 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() { match ev["type"].as_str() {
Some("turn_start") => { Some("turn_start") => {
turns += 1; r.turns += 1;
if p.budget.max_turns.is_some_and(|m| turns > m) { if p.budget.max_turns.is_some_and(|m| r.turns > m) {
killed = Some("budget:turns".to_string()); killed = Some("budget:turns".to_string());
} }
} }
Some("stream") if ev["event"]["type"] == "done" => { Some("stream") if ev["event"]["type"] == "done" => {
let u = &ev["event"]["usage"]; 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); + 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()); killed = Some("budget:tokens".to_string());
} }
} }
+18 -1
View File
@@ -4,7 +4,7 @@ use anyhow::{Context, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::path::PathBuf; 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)] #[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum Status { pub enum Status {
@@ -13,6 +13,8 @@ pub enum Status {
Gating, Gating,
Done, Done,
Failed, Failed,
/// Gate still red after all retries: branch holds the best attempt, gate output in `ID.gate.log`.
NeedsHuman,
} }
impl Status { impl Status {
@@ -41,6 +43,14 @@ pub struct Run {
pub input_tokens: u64, pub input_tokens: u64,
pub output_tokens: u64, pub output_tokens: u64,
pub session: Option<String>, 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 { pub fn now() -> u64 {
@@ -53,6 +63,10 @@ pub fn runs_dir() -> PathBuf {
crate::state_dir().join("runs") 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 { pub fn log_path(id: &str) -> PathBuf {
runs_dir().join(format!("{id}.log")) runs_dir().join(format!("{id}.log"))
} }
@@ -144,6 +158,9 @@ mod tests {
input_tokens: 0, input_tokens: 0,
output_tokens: 0, output_tokens: 0,
session: None, session: None,
attempts: 0,
turns: 0,
spent_tokens: 0,
} }
} }
+18 -2
View File
@@ -25,6 +25,9 @@ for i in range(int(body.split("TURNS=")[1].split()[0]) if "TURNS=" in body else
e({"type": "turn_start"}) e({"type": "turn_start"})
e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50}}}) e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50}}})
if "WRITE" in body: open("out.txt", "w").write("x") if "WRITE" in body: open("out.txt", "w").write("x")
if "--session" in sys.argv:
open("retry-prompt.txt", "w").write(body)
if "RETRYFIX" in os.environ.get("MODE", "RETRYFIX"): open("out.txt", "w").write("x")
e({"type": "done", "error": "boom" if "FAIL" in body else None, "usage": {"input_tokens": 100, "output_tokens": 50}, "session": "/s.jsonl"}) e({"type": "done", "error": "boom" if "FAIL" in body else None, "usage": {"input_tokens": 100, "output_tokens": 50}, "session": "/s.jsonl"})
''') ''')
@@ -55,11 +58,24 @@ def check(p, st, reason=None):
return s return s
profile("p", 'gate = "test -f out.txt"\n') profile("p", 'gate = "test -f out.txt || { echo MARKER-GATE-OUT; exit 3; }"\n')
s = check(run("ok", body="WRITE"), "done") s = check(run("ok", body="WRITE"), "done")
assert s["gate_exit"] == 0 and s["input_tokens"] == 100 and s["session"] == "/s.jsonl", s assert s["gate_exit"] == 0 and s["input_tokens"] == 100 and s["session"] == "/s.jsonl", s
assert "out.txt" in subprocess.run(["git", "ls-tree", "--name-only", s["branch"]], cwd=repo, capture_output=True, text=True).stdout assert "out.txt" in subprocess.run(["git", "ls-tree", "--name-only", s["branch"]], cwd=repo, capture_output=True, text=True).stdout
check(run("nowrite", body="x"), "failed", "gate-failed") s = check(run("nowrite", body="NEVERFIX", env={"MODE": "NEVER"}), "needs-human", "gate-failed")
assert s["attempts"] == 3 and s["gate_exit"] != 0, s # 1 + 2 retries
assert "MARKER-GATE-OUT" in (tmp / "state/runs" / (s["id"] + ".gate.log")).read_text()
profile("r", 'gate = "test -f out.txt || { echo MARKER-GATE-OUT; exit 3; }"\nmax_retries = 1\n')
s = check(run("fixes", "r", body="x"), "done")
assert s["attempts"] == 2 and s["gate_exit"] == 0 and s["reason"] is None, s
sent = subprocess.run(["git", "show", s["branch"] + ":retry-prompt.txt"], cwd=repo, capture_output=True, text=True).stdout
assert "MARKER-GATE-OUT" in sent and "exit 3" in sent, sent # failure log reached hx on the resumed session
profile("z", 'gate = "false"\nmax_retries = 0\n')
s = check(run("noretry", "z", body="x"), "needs-human")
assert s["attempts"] == 1, s
profile("b", 'gate = "false"\nmax_retries = 2\n[budget]\nmax_turns = 2\n')
s = check(run("budget-across", "b", body="x"), "failed", "budget:turns") # budget spans attempts
assert (s["attempts"], s["turns"]) == (3, 3), s # 1 turn per attempt; 3rd turn exceeds 2
check(run("hxerr", body="FAIL WRITE"), "failed", "hx-failed: boom") check(run("hxerr", body="FAIL WRITE"), "failed", "hx-failed: boom")
check(run("nojson", body="NOJSON"), "failed", "hx-failed") check(run("nojson", body="NOJSON"), "failed", "hx-failed")