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

+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)