O4: parallel workers, locks, provider quota (#12)

This commit was merged in pull request #12.
This commit is contained in:
hermes committed 2026-11-12 23:52:22 +00:00
1 parent afafc41376
commit 06662a085f
10 files changed
+410 -43

No files matched your search

+19 -7
View File
@@ -25,14 +25,14 @@ pub struct Task {
pub extra: Map<String, Value>,
}
pub trait Source {
pub trait Source: Send + Sync {
fn list(&self) -> Result<Vec<Task>>;
/// false = somebody else got it; skip silently.
fn claim(&self, t: &Task) -> Result<bool>;
fn report(&self, t: &Task, r: &Run) -> Result<()>;
}
pub trait Sink {
pub trait Sink: Send + Sync {
/// Called for runs that ended `done`. Returns a URL or note to store on the run.
fn publish(&self, t: &Task, r: &Run) -> Result<Option<String>>;
}
@@ -121,6 +121,18 @@ impl DirSource {
}
}
impl DirSource {
/// Quota requeue: the task goes back into the queue for the next pull.
fn mv_back(&self, id: &str) -> Result<bool> {
let name = format!("{id}.md");
match std::fs::rename(self.0.join(".running").join(&name), self.0.join(&name)) {
Ok(()) => Ok(true),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e.into()),
}
}
}
impl Source for DirSource {
fn list(&self) -> Result<Vec<Task>> {
let mut v = vec![];
@@ -141,12 +153,12 @@ impl Source for DirSource {
self.mv(&t.id, "", ".running")
}
fn report(&self, t: &Task, r: &Run) -> Result<()> {
let to = if r.status == crate::state::Status::Done {
".done"
} else {
".failed"
use crate::state::Status;
match r.status {
Status::Done => self.mv(&t.id, ".running", ".done")?,
Status::Requeued => self.mv_back(&t.id)?,
_ => self.mv(&t.id, ".running", ".failed")?,
};
self.mv(&t.id, ".running", to)?;
Ok(())
}
}
+123
View File
@@ -0,0 +1,123 @@
//! Cross-process locks via flock(2): released by the kernel when the holder dies, so stale locks cannot exist.
//! Files live under `<state>/locks`. Rust opens files O_CLOEXEC, so hx never inherits a lock.
use anyhow::Result;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::time::Duration;
pub struct Lock(#[allow(dead_code)] File); // dropped = closed = released
fn flock(path: &Path, nonblock: bool) -> Result<Option<Lock>> {
if let Some(d) = path.parent() {
std::fs::create_dir_all(d)?;
}
let f = File::options().create(true).append(true).open(path)?;
let op = libc::LOCK_EX | if nonblock { libc::LOCK_NB } else { 0 };
use std::os::fd::AsRawFd;
// SAFETY: plain syscall on an fd we own.
if unsafe { libc::flock(f.as_raw_fd(), op) } == 0 {
return Ok(Some(Lock(f)));
}
let e = std::io::Error::last_os_error();
if e.kind() == std::io::ErrorKind::WouldBlock {
return Ok(None);
}
Err(e.into())
}
pub fn try_lock(path: &Path) -> Result<Option<Lock>> {
flock(path, true)
}
pub fn lock(path: &Path) -> Result<Lock> {
Ok(flock(path, false)?.expect("blocking flock returns a lock"))
}
fn safe(s: &str) -> String {
s.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
}
})
.collect()
}
fn dir() -> PathBuf {
crate::state_dir().join("locks")
}
/// One lock per (profile, task id): two orch instances on one queue never run the same task.
pub fn task(profile: &str, id: &str) -> Result<Option<Lock>> {
try_lock(&dir().join(format!("task-{}-{}", safe(profile), safe(id))))
}
/// Serializes git worktree creation per repo (git itself races on its own locks).
pub fn repo(repo: &Path) -> Result<Lock> {
lock(&dir().join(format!("repo-{}", safe(&repo.to_string_lossy()))))
}
/// Held for the whole life of a run; `Run::reconcile` uses it to tell a live run from a dead one.
pub fn run(id: &str) -> Result<Option<Lock>> {
try_lock(&dir().join(format!("run-{}", safe(id))))
}
/// Concurrency slot for an account across all orch processes. Blocks until one of `max` slots is free.
pub fn slot(account: &str, max: u32) -> Result<Lock> {
loop {
for i in 0..max.max(1) {
if let Some(l) = try_lock(&dir().join(format!("slot-{}-{i}", safe(account))))? {
return Ok(l);
}
}
std::thread::sleep(Duration::from_millis(200));
}
}
fn pause_path(account: &str) -> PathBuf {
dir().join(format!("pause-{}", safe(account)))
}
/// Unix time until which the account is paused (0 = not paused).
pub fn paused_until(account: &str) -> u64 {
std::fs::read_to_string(pause_path(account))
.ok()
.and_then(|s| s.trim().parse().ok())
.unwrap_or(0)
}
/// Extends (never shortens) the pause.
pub fn pause(account: &str, until: u64) -> Result<()> {
if until > paused_until(account) {
std::fs::create_dir_all(dir())?;
std::fs::write(pause_path(account), until.to_string())?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn locks_exclude_and_release() {
let d = std::env::temp_dir().join(format!("orch-lock-{}", std::process::id()));
let p = d.join("x");
let a = try_lock(&p).unwrap().unwrap();
assert!(
try_lock(&p).unwrap().is_none(),
"second lock must fail while held"
);
drop(a);
assert!(try_lock(&p).unwrap().is_some(), "free after drop");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn names_are_sanitized() {
assert_eq!(safe("../a b"), "___a_b");
}
}
+56 -17
View File
@@ -1,11 +1,15 @@
mod adapter;
mod lock;
mod profile;
mod run;
mod state;
use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
#[derive(Parser)]
#[command(version, about = "Run hx coding agents on tasks")]
@@ -78,24 +82,59 @@ fn main() -> Result<std::process::ExitCode> {
Cmd::Pull { profile, limit } => {
let p = profile::Profile::load(&profile)?;
let src = adapter::source(p.source.as_ref().context("profile has no [source]")?)?;
let (mut ok, mut n) = (true, 0);
for t in src.list()? {
if limit.is_some_and(|l| n >= l) {
break;
let queue = Mutex::new(src.list()?.into_iter().collect::<VecDeque<_>>());
let (ok, claimed) = (AtomicBool::new(true), AtomicUsize::new(0));
let account = p.account(&profile).to_string();
std::thread::scope(|s| {
for _ in 0..p.workers {
s.spawn(|| {
let res = (|| -> Result<()> {
loop {
if lock::paused_until(&account) > state::now() {
eprintln!(
"account {account} paused (quota); leaving the rest queued"
);
return Ok(());
}
let Some(t) = queue.lock().unwrap().pop_front() else {
return Ok(());
};
let Some(repo) = t.repo.clone().or_else(|| p.repo.clone()) else {
eprintln!(
"{}: no repo (task `repo` or profile `repo`), skipped",
t.id
);
ok.store(false, Ordering::SeqCst);
continue;
};
// task lock first: a second orch on the same queue skips what is already taken
let Some(_held) = lock::task(&profile, &t.id)? else {
continue;
};
if limit
.is_some_and(|l| claimed.fetch_add(1, Ordering::SeqCst) >= l)
{
return Ok(());
}
if !src.claim(&t)? {
continue;
}
let r = process(&t, &repo, &profile, &p, Some(src.as_ref()))?;
if r.status != state::Status::Done
&& r.status != state::Status::Requeued
{
ok.store(false, Ordering::SeqCst);
}
}
})();
if let Err(e) = res {
eprintln!("worker: {e:#}");
ok.store(false, Ordering::SeqCst);
}
});
}
let Some(repo) = t.repo.clone().or_else(|| p.repo.clone()) else {
eprintln!("{}: no repo (task `repo` or profile `repo`), skipped", t.id);
ok = false;
continue;
};
if !src.claim(&t)? {
continue;
}
n += 1;
let r = process(&t, &repo, &profile, &p, Some(src.as_ref()))?;
ok &= r.status == state::Status::Done;
}
Ok(code(ok))
});
Ok(code(ok.load(Ordering::SeqCst)))
}
Cmd::Status { id: Some(id) } => {
println!("{}", serde_json::to_string_pretty(&state::Run::load(&id)?)?);
+25
View File
@@ -34,6 +34,13 @@ pub struct Profile {
/// Extra hx attempts after a red gate (default 2). 0 = fail straight to needs-human.
#[serde(default = "default_retries")]
pub max_retries: u32,
/// Parallel runs for `orch pull` (default 1).
#[serde(default = "one")]
pub workers: u32,
/// Provider account this profile bills to; profiles sharing a login set the same name. Default: profile name.
pub account: Option<String>,
/// Max simultaneous runs on the account across all orch processes (default = workers).
pub max_concurrent: Option<u32>,
#[serde(default)]
pub budget: Budget,
/// Default repo for tasks that name none (`orch pull`).
@@ -42,6 +49,10 @@ pub struct Profile {
pub sink: Option<crate::adapter::Adapter>,
}
fn one() -> u32 {
1
}
fn default_retries() -> u32 {
2
}
@@ -53,6 +64,9 @@ fn default_hx() -> String {
impl Profile {
pub fn parse(s: &str) -> Result<Self> {
let p: Profile = toml::from_str(s)?;
if p.workers == 0 || p.max_concurrent == Some(0) {
bail!("workers and max_concurrent must be >= 1");
}
if p.yolo && !p.sandbox {
bail!("yolo = true requires sandbox = true");
}
@@ -71,6 +85,10 @@ impl Profile {
Self::parse(&s).with_context(|| path.display().to_string())
}
pub fn account<'a>(&'a self, profile: &'a str) -> &'a str {
self.account.as_deref().unwrap_or(profile)
}
pub fn wall_secs(&self) -> u64 {
self.budget.wall_secs.unwrap_or(1800)
}
@@ -83,6 +101,7 @@ mod tests {
#[test]
fn minimal_and_full() {
let p = Profile::parse("").unwrap();
assert_eq!((p.workers, p.account("x")), (1, "x"));
assert_eq!(
(p.hx.as_str(), p.wall_secs(), p.gate.is_none()),
("hx", 1800, true)
@@ -97,6 +116,12 @@ mod tests {
);
}
#[test]
fn rejects_zero_workers() {
assert!(Profile::parse("workers = 0").is_err());
assert!(Profile::parse("max_concurrent = 0").is_err());
}
#[test]
fn rejects_yolo_without_sandbox_and_unknown_keys() {
assert!(Profile::parse("yolo=true").is_err());
+55 -2
View File
@@ -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)
+18 -14
View File
@@ -4,7 +4,7 @@ use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
/// queued -> running -> gating -> (retry: running) -> done | failed | needs-human.
/// queued -> running -> gating -> (retry: running) -> done | failed | needs-human | requeued.
#[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,
/// Provider quota used up: account paused, the task runs again later as a new run.
Requeued,
/// Gate still red after all retries: branch holds the best attempt, gate output in `ID.gate.log`.
NeedsHuman,
}
@@ -54,12 +56,19 @@ pub struct Run {
/// Sink result (PR URL, branch note) once published.
#[serde(default)]
pub published: Option<String>,
/// Unix time a full quota window resets (seen in this run's hx events).
#[serde(default)]
pub quota_until: Option<u64>,
}
pub fn now() -> u64 {
now_ms() / 1000
}
pub fn now_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
.map_or(0, |d| d.as_millis() as u64)
}
pub fn runs_dir() -> PathBuf {
@@ -113,9 +122,10 @@ impl Run {
/// An active run whose orchestrator died (crash, kill -9, reboot) is marked failed/interrupted and
/// its hx process group is killed, so status never lies and no orphan keeps spending tokens.
/// ponytail: pid reuse can make a dead orch look alive; store a start time (or flock) in O4.
/// Liveness = the run's flock (held by the executing orch for the whole run, released by the kernel on
/// death), so pid reuse cannot fake a live run.
pub fn reconcile(&mut self) -> Result<()> {
if self.status.active() && !alive(self.orch_pid) {
if self.status.active() && crate::lock::run(&self.id)?.is_some() {
if let Some(p) = self.hx_pid {
kill_group(p);
}
@@ -128,11 +138,6 @@ impl Run {
}
}
pub fn alive(pid: u32) -> bool {
// SAFETY: signal 0 only checks existence.
unsafe { libc::kill(pid as i32, 0) == 0 || *libc::__errno_location() == libc::EPERM }
}
pub fn kill_group(pgid: u32) {
// SAFETY: plain syscall; hx is spawned with process_group(0) so pgid == its pid.
unsafe { libc::killpg(pgid as i32, libc::SIGKILL) };
@@ -165,6 +170,7 @@ mod tests {
turns: 0,
spent_tokens: 0,
published: None,
quota_until: None,
}
}
@@ -174,11 +180,9 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
// SAFETY: single test touching this var; other tests in this binary do not read it.
unsafe { std::env::set_var("ORCH_STATE_DIR", &d) };
let mut c = std::process::Command::new("true").spawn().unwrap();
let dead = c.id();
c.wait().unwrap();
sample("live", std::process::id()).save().unwrap();
sample("dead", dead).save().unwrap();
sample("live", 1).save().unwrap();
sample("dead", 1).save().unwrap();
let _held = crate::lock::run("live").unwrap().unwrap(); // the live run's orch holds its lock
let live = Run::load("live").unwrap();
assert_eq!(live.status, Status::Running);
let dead = Run::load("dead").unwrap();