"""Adaptive orchestrator for the main run under a flapping model cluster. Two runner processes: * stable pool: the models that have been reliably served; launched once and left alone so backend churn elsewhere never interrupts them * straggler: any model marked UNSTABLE runs in its own runner with its own run id (records merged into the main file when it stops), started and stopped with its backend availability Exit conditions: every cell clean for all models, or (user decision 2026-08-08) all stable-pool models complete while every straggler has been unavailable for 30 minutes, in which case the run concludes without them. python3 src/orchestrate_run.py --run-id main """ from __future__ import annotations import argparse import collections import json import os import signal import subprocess import sys import time import urllib.request MODELS = ["gemma-4-31b", "glm-5.2-fp8", "gptoss-120b", "gptoss-20b", "leanstral-2603", "qwen3-30b-a3b-instruct-fp8", "qwen3.5-9b", "qwen3.6-27b-fp8"] UNSTABLE = {"glm-5.2-fp8"} # runs in its own start/stop runner BASE = "http://YOUR-VLLM-HOST:8000/v1" KEY = "YOUR-API-KEY" PER_MODEL = 2752 TOTAL = PER_MODEL * len(MODELS) def probe(model: str, timeout: float = 30.0) -> bool: body = json.dumps({"model": model, "max_tokens": 5, "messages": [{"role": "user", "content": "say ok"}]}) req = urllib.request.Request( f"{BASE}/chat/completions", data=body.encode(), headers={"Content-Type": "application/json", "Authorization": f"Bearer {KEY}"}, method="POST") try: with urllib.request.urlopen(req, timeout=timeout) as resp: return b'"content"' in resp.read() except Exception: return False def load_clean(paths: list[str]): seen, per_model, fails = set(), collections.Counter(), 0 topo = collections.Counter() for path in paths: if not os.path.exists(path): continue for line in open(path): try: r = json.loads(line) except Exception: continue k = r.get("key") if (k == "ERR" or k in seen or r.get("model") not in MODELS or r.get("role_failures", 0) > 0): continue seen.add(k) per_model[r["model"]] += 1 topo[r.get("topology", "?")] += 1 if not r.get("parsed_ok", True): fails += 1 return seen, per_model, fails, topo def purge(run_id: str) -> None: subprocess.run([sys.executable, "src/purge_infra_failures.py", "--run-id", run_id, "--apply"], check=False, capture_output=True) def launch(run_id: str, subset: list[str], log: str): cmd = [sys.executable, "src/runner.py", "--run-id", run_id, "--models", ",".join(sorted(subset))] return subprocess.Popen(cmd, stdout=open(log, "a"), stderr=subprocess.STDOUT) def stop(proc) -> None: if proc and proc.poll() is None: proc.send_signal(signal.SIGTERM) try: proc.wait(timeout=30) except subprocess.TimeoutExpired: proc.kill() def merge(straggler_records: str, main_records: str) -> None: """Append straggler records into the main file (runner must be stopped).""" if not os.path.exists(straggler_records): return with open(straggler_records) as src, open(main_records, "a") as dst: for line in src: dst.write(line) os.rename(straggler_records, straggler_records + ".merged") def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--run-id", default="main") ap.add_argument("--probe-interval", type=int, default=180) ap.add_argument("--status-interval", type=int, default=300) args = ap.parse_args() stable_models = [m for m in MODELS if m not in UNSTABLE] rid_s = args.run_id + "_straggler" rec_main = os.path.join("results", args.run_id, "records.jsonl") rec_str = os.path.join("results", rid_s, "records.jsonl") os.makedirs(os.path.join("results", rid_s), exist_ok=True) proc7 = None # stable pool runner procG = None # straggler runner glm_up_streak = 0 glm_down_streak = 0 straggler_wait = 0 last_status = 0.0 while True: seen, per_model, fails, topo = load_clean([rec_main, rec_str]) finished = {m for m in MODELS if per_model[m] >= PER_MODEL} if len(seen) >= TOTAL: stop(proc7); stop(procG) merge(rec_str, rec_main) print(f"EVENT run complete: {len(seen)}/{TOTAL} clean cells", flush=True) return # ---- stable pool: launch once, relaunch only if it died with work left stable_left = [m for m in stable_models if m not in finished] if stable_left: if proc7 is None or proc7.poll() is not None: if proc7 is not None: print("EVENT stable-pool runner exited, relaunching", flush=True) purge(args.run_id) proc7 = launch(args.run_id, stable_left, "logs/main.out") elif proc7 and proc7.poll() is None: pass # let it finish and exit on its own # ---- straggler: start when up 2 probes, stop when down 2 probes stragglers_left = [m for m in UNSTABLE if m not in finished] if stragglers_left: up = all(probe(m) for m in stragglers_left) glm_up_streak = glm_up_streak + 1 if up else 0 glm_down_streak = glm_down_streak + 1 if not up else 0 if up and glm_up_streak >= 2 and ( procG is None or procG.poll() is not None): print(f"EVENT straggler backend stable, starting runner for " f"{stragglers_left}", flush=True) purge(rid_s) procG = launch(rid_s, stragglers_left, "logs/straggler.out") if not up and glm_down_streak >= 2 and procG and \ procG.poll() is None: print("EVENT straggler backend down, stopping its runner", flush=True) stop(procG) # user decision: conclude without stragglers after the stable pool # finishes and stragglers stay unavailable for 30 minutes if not stable_left and not up: straggler_wait += 1 if straggler_wait >= 10: stop(proc7); stop(procG) merge(rec_str, rec_main) print(f"EVENT run concluded WITHOUT {stragglers_left}: " f"{len(seen)} clean cells; finished: " f"{sorted(finished)}", flush=True) return else: straggler_wait = 0 now = time.time() if now - last_status >= args.status_interval: tp = "/".join(str(topo[t]) for t in ["single", "chain", "critique", "debate", "hierarchical"]) g = per_model.get("glm-5.2-fp8", 0) print(f"STATUS | {time.strftime('%H:%M')} | {len(seen)}/{TOTAL} " f"| {100 * len(seen) / TOTAL:.1f}% | fails {fails} " f"({100 * fails / max(len(seen), 1):.1f}%) " f"| glm {g}/{PER_MODEL} " f"| {tp} |", flush=True) last_status = now time.sleep(args.probe_interval) if __name__ == "__main__": main()