O4: parallel workers, locks, provider quota (#12)
This commit was merged in pull request #12.
This commit is contained in:
1 parent
afafc41376
commit
06662a085f
10 files changed
+410
-43
No files matched your search
+55
-2
@@ -1,6 +1,7 @@
|
||||
//! One run: worktree -> hx (NDJSON, budgets, process group) -> commit -> gate -> final state.
|
||||
|
||||
use crate::adapter::Task;
|
||||
use crate::lock;
|
||||
use crate::profile::Profile;
|
||||
use crate::state::{Run, Status, gate_log_path, kill_group, log_path, now};
|
||||
use anyhow::{Context, Result, bail};
|
||||
@@ -40,7 +41,8 @@ pub fn new_run(task: &Task, repo: &Path, profile: &str) -> Result<Run> {
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let id = format!("{stem}-{}", now());
|
||||
// ms, not s: a requeued task can start again within the same second and must not reuse the branch name
|
||||
let id = format!("{stem}-{}", crate::state::now_ms());
|
||||
let repo = repo
|
||||
.canonicalize()
|
||||
.with_context(|| format!("repo {}", repo.display()))?;
|
||||
@@ -66,6 +68,7 @@ pub fn new_run(task: &Task, repo: &Path, profile: &str) -> Result<Run> {
|
||||
turns: 0,
|
||||
spent_tokens: 0,
|
||||
published: None,
|
||||
quota_until: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -76,6 +79,15 @@ fn fail(r: &mut Run, reason: impl Into<String>) -> Result<()> {
|
||||
r.save()
|
||||
}
|
||||
|
||||
/// hx surfaces provider rejections as `api 429: ...`; also match the usual wording.
|
||||
fn is_rate_limit(reason: &str) -> bool {
|
||||
let r = reason.to_lowercase();
|
||||
r.contains("api 429")
|
||||
|| r.contains("rate limit")
|
||||
|| r.contains("rate_limit")
|
||||
|| r.contains("usage limit")
|
||||
}
|
||||
|
||||
/// Max bytes of gate output fed back to hx (the tail: errors are at the end).
|
||||
const GATE_LOG_LIMIT: usize = 8000;
|
||||
|
||||
@@ -101,10 +113,25 @@ fn retry_prompt(gate: &str, code: Option<i32>, out: &[u8], resumed: bool, body:
|
||||
/// `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: &Task) -> Result<()> {
|
||||
let body = task.body.clone();
|
||||
// held until return: proves the run is alive to `Run::reconcile` in any other orch process
|
||||
let _alive = lock::run(&r.id)?;
|
||||
r.save()?;
|
||||
let account = p.account(&r.profile).to_string();
|
||||
let _slot = lock::slot(&account, p.max_concurrent.unwrap_or(p.workers))?;
|
||||
let until = lock::paused_until(&account);
|
||||
if until > now() {
|
||||
r.status = Status::Requeued;
|
||||
r.reason = Some(format!("quota-paused until {until}"));
|
||||
r.ended = Some(now());
|
||||
return r.save();
|
||||
}
|
||||
std::fs::create_dir_all(r.worktree.parent().unwrap())?;
|
||||
let wt = r.worktree.to_string_lossy().into_owned();
|
||||
if let Err(e) = git(&r.repo, &["worktree", "add", "-b", &r.branch, &wt, "HEAD"]) {
|
||||
let added = {
|
||||
let _repo = lock::repo(&r.repo)?; // git races on its own locks when worktrees are added in parallel
|
||||
git(&r.repo, &["worktree", "add", "-b", &r.branch, &wt, "HEAD"])
|
||||
};
|
||||
if let Err(e) = added {
|
||||
fail(r, format!("setup: {e}"))?;
|
||||
return Ok(());
|
||||
}
|
||||
@@ -113,6 +140,7 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> {
|
||||
let mut session: Option<String> = None;
|
||||
loop {
|
||||
r.attempts += 1;
|
||||
r.quota_until = None; // per attempt: only a window seen in THIS attempt can excuse its failure
|
||||
r.status = Status::Running;
|
||||
r.save()?;
|
||||
writeln!(log, "\n--- attempt {}", r.attempts)?;
|
||||
@@ -126,7 +154,18 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> {
|
||||
let msg = format!("orch: {} (attempt {})", r.title, r.attempts);
|
||||
git(&r.worktree, &["commit", "-qm", &msg])?;
|
||||
}
|
||||
if let Some(until) = r.quota_until {
|
||||
lock::pause(&account, until)?; // every full window pauses the account, even after a clean run
|
||||
}
|
||||
if let Some(reason) = reason {
|
||||
if r.quota_until.is_some() || is_rate_limit(&reason) {
|
||||
// provider said no: not the task's fault. Pause the account and hand the task back.
|
||||
lock::pause(&account, r.quota_until.unwrap_or(now() + 900))?;
|
||||
r.status = Status::Requeued;
|
||||
r.reason = Some(format!("quota: {reason}"));
|
||||
r.ended = Some(now());
|
||||
return r.save();
|
||||
}
|
||||
return fail(r, reason);
|
||||
}
|
||||
let Some(gate) = &p.gate else { break };
|
||||
@@ -225,6 +264,20 @@ fn run_hx(
|
||||
killed = Some("budget:turns".to_string());
|
||||
}
|
||||
}
|
||||
Some("stream") if ev["event"]["type"] == "quota" => {
|
||||
let full: Vec<&Value> = ev["event"]["windows"]
|
||||
.as_array()
|
||||
.map(|w| {
|
||||
w.iter()
|
||||
.filter(|w| w["used_pct"].as_f64().unwrap_or(0.0) >= 99.5)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if !full.is_empty() {
|
||||
let reset = full.iter().filter_map(|w| w["resets_at"].as_u64()).max();
|
||||
r.quota_until = Some(reset.unwrap_or(now() + 3600));
|
||||
}
|
||||
}
|
||||
Some("stream") if ev["event"]["type"] == "done" => {
|
||||
let u = &ev["event"]["usage"];
|
||||
r.spent_tokens += u["input_tokens"].as_u64().unwrap_or(0)
|
||||
|
||||
Reference in new issue
Block a user