O4: worker pool, flock locks, account slots, quota pause and requeue (closes #5)

This commit is contained in:
hermes committed 2026-11-12 23:52:16 +00:00
1 parent afafc41376
commit 47893a4993
10 files changed
+410 -43

No files matched your search

+4 -1
View File
@@ -35,10 +35,13 @@ is echoed back verbatim in later calls, so adapters stay stateless.
| `report` (source) | `{"task": Task, "run": Run}` | `{}`; called when a run ends in any state |
| `publish` (sink) | `{"task": Task, "run": Run}` | `{"url": "..."}` (url optional); only for runs that ended `done` |
`Run`: `id, status (done|failed|needs-human), reason, branch, repo, worktree, attempts, input_tokens,
`Run`: `id, status (done|failed|needs-human|requeued), reason, branch, repo, worktree, attempts, input_tokens,
output_tokens, published`. The work is on local branch `branch` in `repo`; a sink pushes it and opens a PR/MR,
posts a comment, or whatever the host needs. Host credentials live in the adapter, never in orch.
`requeued` (provider quota used up) means the task was not attempted to completion: `report` should put it back in
the queue (the `dir` source does) so a later `pull` runs it again once the account's window resets.
A failing `publish` or `report` never fails the run: the error is printed and, for publish, stored in the run's
`published` field as `publish-failed: ...`.
+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();
+82 -1
View File
@@ -21,6 +21,13 @@ if "NOJSON" in body: sys.exit(1)
if "HANG" in body:
open(os.environ.get("PIDFILE", "/dev/null"), "w").write(str(os.getpid()))
time.sleep(300)
conc = os.environ.get("CONC")
if "SLEEP=" in body:
if conc: open(conc, "a").write("+")
time.sleep(float(body.split("SLEEP=")[1].split()[0]))
if conc: open(conc, "a").write("-")
if "QUOTA" in body:
e({"type": "stream", "event": {"type": "quota", "windows": [{"label": "5h", "used_pct": 100.0, "resets_at": int(time.time()) + 3600}], "credits": None}})
for i in range(int(body.split("TURNS=")[1].split()[0]) if "TURNS=" in body else 1):
e({"type": "turn_start"})
e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50}}})
@@ -28,7 +35,7 @@ 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": "api 429: slow down" if "RATELIMIT" in body else "boom" if "FAIL" in body else None, "usage": {"input_tokens": 100, "output_tokens": 50}, "session": "/s.jsonl"})
''')
@@ -130,6 +137,80 @@ assert subprocess.run([orch, "pull", "--profile", "c"], env={**aenv, "BREAK": "l
profile("u", '[source]\nkind = "ftp"\n')
assert subprocess.run([orch, "pull", "--profile", "u"], env=env, capture_output=True, text=True).returncode != 0
# --- parallel pool, two orch instances, quota (O4) ---
def conc_max(f):
cur = best = 0
for ch in pathlib.Path(f).read_text():
cur += 1 if ch == "+" else -1
best = max(best, cur)
return best, pathlib.Path(f).read_text().count("+")
pq = tmp / "pq"
pq.mkdir()
for i in range(5):
(pq / f"t{i}.md").write_text(f"# T{i}\nWRITE SLEEP=0.5\n")
profile("w", f'repo = "{repo}"\ngate = "test -f out.txt"\nworkers = 2\n[source]\nkind = "dir"\npath = "{pq}"\n')
conc = tmp / "conc1"
t0 = time.time()
p = subprocess.run([orch, "pull", "--profile", "w"], env={**env, "CONC": str(conc)}, capture_output=True, text=True)
assert p.returncode == 0, p
assert conc_max(conc) == (2, 5), conc_max(conc) # 5 tasks, never more than 2 at once, and really 2
assert len(list((pq / ".done").glob("*.md"))) == 5
# account cap across profiles/processes: two profiles on one account, max_concurrent = 1 -> strictly serial
for n in ("x1", "x2"):
d = tmp / f"q{n}"
d.mkdir()
for i in range(2):
(d / f"{n}-{i}.md").write_text("# T\nWRITE SLEEP=0.4\n")
profile(n, f'repo = "{repo}"\naccount = "shared"\nworkers = 2\nmax_concurrent = 1\n[source]\nkind = "dir"\npath = "{d}"\n')
conc = tmp / "conc2"
ps = [subprocess.Popen([orch, "pull", "--profile", n], env={**env, "CONC": str(conc)}, stdout=subprocess.PIPE, text=True) for n in ("x1", "x2")]
assert all(x.wait() == 0 for x in ps)
assert conc_max(conc) == (1, 4), conc_max(conc)
# two orch instances on one queue (stateful claims, like a real host): every task runs exactly once
cd = tmp / "claims"
cd.mkdir()
cmd2 = f"{sys.executable} {root / 'tests/fake_adapter.py'}"
profile("two", f'repo = "{repo}"\nworkers = 2\n[source]\nkind = "cmd"\ncommand = "{cmd2}"\n')
ad2 = tmp / "ad2"
ad2.mkdir()
tenv = {**env, "ADAPTER_DIR": str(ad2), "REPO": str(repo), "LISTN": "6", "CLAIMDIR": str(cd)}
ps = [subprocess.Popen([orch, "pull", "--profile", "two"], env=tenv, stdout=subprocess.PIPE, text=True) for _ in range(2)]
outs = [x.communicate()[0] for x in ps]
ids = [l.split()[0] for o in outs for l in o.splitlines()]
names = sorted(i.rsplit("-", 1)[0] for i in ids)
assert names == [f"p{i}" for i in range(6)], names # each task exactly once, none lost
# quota: a full window pauses the account; the task is requeued, the rest stays queued; resumes after the window
qd = tmp / "qd"
qd.mkdir()
(qd / "a-quota.md").write_text("# A\nQUOTA RATELIMIT\n")
(qd / "b-next.md").write_text("# B\nWRITE\n")
(qd / "c-next.md").write_text("# C\nWRITE\n")
profile("qp", f'repo = "{repo}"\naccount = "acct-q"\ngate = "test -f out.txt"\n[source]\nkind = "dir"\npath = "{qd}"\n')
p = subprocess.run([orch, "pull", "--profile", "qp"], env=env, capture_output=True, text=True)
assert p.returncode == 0, p # requeue is not a failure
rid = p.stdout.split()[0]
s = status(rid)
assert s["status"] == "requeued" and s["reason"].startswith("quota:"), s
assert sorted(os.listdir(qd)) == [".running", "a-quota.md", "b-next.md", "c-next.md"], os.listdir(qd)
pause = tmp / "state/locks/pause-acct-q"
until = int(pause.read_text())
assert abs(until - (time.time() + 3600)) < 60, until # = the reset time hx reported
p = subprocess.run([orch, "pull", "--profile", "qp"], env=env, capture_output=True, text=True)
assert p.stdout == "" and "paused" in p.stderr, p # nothing runs while paused
pause.write_text(str(int(time.time()) - 1)) # window reset
(qd / "a-quota.md").write_text("# A\nWRITE\n")
p = subprocess.run([orch, "pull", "--profile", "qp"], env=env, capture_output=True, text=True)
assert p.returncode == 0 and p.stdout.count(" done") == 3, p
# a clean run that saw a full window still pauses the account for the next tasks
(qd / "d.md").write_text("# D\nQUOTA WRITE\n")
(qd / "e.md").write_text("# E\nWRITE\n")
p = subprocess.run([orch, "pull", "--profile", "qp"], env=env, capture_output=True, text=True)
assert p.stdout.count(" done") == 1 and (qd / "e.md").exists() and "paused" in p.stderr, p
# kill orch mid-run: status must say interrupted and hx must be dead after the next orch call
pidfile = tmp / "hx.pid"
p = subprocess.Popen([orch, "run", str(task("killed", "HANG")), "--repo", str(repo), "--profile", "p"],
+10 -1
View File
@@ -9,7 +9,16 @@ open(f"{d}/calls.log", "a").write(json.dumps({"op": op, "in": data}) + "\n")
if os.environ.get("BREAK") == op:
print("not json")
sys.exit(0)
if op == "list":
if op == "list" and os.environ.get("LISTN"):
out = {"tasks": [{"id": f"p{i}", "title": f"P{i}", "body": "WRITE SLEEP=0.4", "repo": os.environ["REPO"]}
for i in range(int(os.environ["LISTN"]))]}
elif op == "claim" and os.environ.get("CLAIMDIR"):
try: # a real host claims atomically; model it with O_EXCL
os.close(os.open(os.path.join(os.environ["CLAIMDIR"], data["task"]["id"]), os.O_CREAT | os.O_EXCL))
out = {"claimed": True}
except FileExistsError:
out = {"claimed": False}
elif op == "list":
out = {"tasks": [
{"id": "t-good", "title": "Good", "body": "WRITE", "repo": os.environ["REPO"], "number": 7},
{"id": "t-taken", "title": "Taken", "body": "WRITE", "repo": os.environ["REPO"]},
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env python3
"""Flake hunt: run tests/e2e.py N times, optionally under CPU load. usage: flake.py N [LOADERS]"""
import subprocess, sys
n = int(sys.argv[1])
load = [subprocess.Popen([sys.executable, "-c", "while True: pass"]) for _ in range(int(sys.argv[2]) if len(sys.argv) > 2 else 0)]
bad = 0
try:
for i in range(n):
p = subprocess.run([sys.executable, "tests/e2e.py"], capture_output=True, text=True)
if p.returncode:
bad += 1
print(f"run {i} FAILED\n{p.stderr[-800:]}")
finally:
for l in load:
l.terminate()
print(f"{n - bad}/{n} ok")
sys.exit(1 if bad else 0)