"""R5 test-pass runner, version 2 (clarifications J2-J9 of 23 Nov 2026, records/R5/RULE/j11_v3_4_clarifications_2.txt). One process pulls tasks from ONE task list shared by both GPU slots (V and L) and by every process of a slot (J3: N=1 or 2 processes per GPU, started by testpass_.sbatch). The list is built once by testpass_build_tasks.py --final when the first process passes the start of the pass (not before 12:00 UTC and not before the gate file exists), so a selection.json frozen before 12:00 is used without any hand edit (J2/J7); a second process only reads it. Times (J4, config times_utc): no task is claimed from 16:40 UTC (retries included); at 16:55 every evaluation stops: eval_vlm_test.py / vlmb_eval_vlm_testpass.py get --deadline-utc 16:55 and stop between batches (a set that is not complete is written only as .partial.tsv); command tasks (LINEDET, REF) get SIGTERM to their whole process group at 16:55 and SIGKILL 30 s later; an evaluation still running 60 s after 16:55 is stopped the same way. J3: testpass_.sbatch always starts workers 0 and 1; worker 1 reads --nfile when the pass opens and exits unless the file starts with 2. If the builder fails, it is run again with --force-fallback (J2 fallback) before the runner gives up. Claims: mkdir lock per task (heartbeat every 30 s, stale after 15 min) plus an optional lock key ("lock"), locks that must not be held ("blocked_by") and an exclusive prefix ("exclusive_prefix": no other lock with that prefix may be held), checked again after claiming. Status: one file per task, /status/.json, written atomically by the claim holder: done, failed (retried once, after the other tasks), failed_final, not_run_no_checkpoint, stopped_by_deadline. A task interrupted by a killed job is claimable again and is not counted as a failure. Order (J2): the first claimable task of the list is taken, so a row starts only after every row above it has started. Exceptions, each recorded: a command task whose own gate file (J9) does not exist yet is passed over until it exists; a task pinned to the other slot (REF on slot L, J8) is waited for while that slot has a live runner, at most pin_wait_max_seconds, then run here; a LINEDET task whose checkpoint is being run by another process is passed over. At exit each process writes /summary__w_.json with every task's status and, for evaluation tasks, the complete sets (rows not complete by 16:55 are "not run by the deadline", J4). kind vlma -> eval_vlm_test.py (.venv_vlm); kind vlmb -> CODE/scripts/r5_vlmb/vlmb_eval_vlm_testpass.py with the arm's own venv and environment (leader_cmds.py, read-only); kind cmd -> the task's argv (LINEDET's commands through linedet_ckpt_task.sh, linedet.lm_gate, REF's test_pass_commands.sh), unchanged owner scripts. usage: testpass_runner.py --config testpass_config.json --slot V --worker 0|1 [--nfile N_FILE] [--tasks FIXED_LIST.json] """ import argparse import json import os import shutil import signal import subprocess import sys import threading import time from datetime import datetime, timezone sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import leader_cmds as lc # noqa: E402 (read-only use of the shared VLMB interface helper) ap = argparse.ArgumentParser() ap.add_argument("--config", required=True) ap.add_argument("--slot", required=True) ap.add_argument("--worker", type=int, default=0) ap.add_argument("--tasks", default="", help="a fixed task list instead of the shared one (tests and smoke runs)") ap.add_argument("--nfile", default="", help="J3: a worker >= 1 runs only if this file starts with 2, read when the pass opens") A = ap.parse_args() CFG = json.load(open(A.config, encoding="utf-8")) P, T = CFG["paths"], CFG["times_utc"] HERE = os.path.dirname(os.path.abspath(__file__)) PY = [os.path.join(P["code"], ".venv_vlm", "bin", "python"), "-I"] TPD = P["testpass_dir"] STATUSD, CLAIMD, ALIVED = (os.path.join(TPD, x) for x in ("status", "claims", "alive")) for d in (TPD, STATUSD, CLAIMD, ALIVED): os.makedirs(d, exist_ok=True) LOGD = os.path.join(P["data"], "logs", "r5_vlma") os.makedirs(LOGD, exist_ok=True) JOB = os.environ.get("SLURM_JOB_ID", "nojob") ME = "%s_w%d_%s" % (A.slot, A.worker, JOB) FINAL = ("done", "failed_final", "not_run_no_checkpoint", "stopped_by_deadline") def utc(): return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def ts(s): return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp() NOT_BEFORE, NO_START, STOP = ts(T["not_before"]), ts(T["no_task_starts_from"]), ts(T["evaluations_stop_at"]) GRACE, KILL_AFTER = float(T.get("grace_after_stop_seconds_eval", 60)), float(T.get("kill_after_term_seconds", 30)) def say(*a): print("[testpass %s %s]" % (ME, utc()), *a, flush=True) def safe(name): return "".join(c if c.isalnum() or c in "-_." else "_" for c in name) def jload(p, d=None): try: with open(p, encoding="utf-8") as f: return json.load(f) except Exception: # noqa: BLE001 return d def jdump(o, p): tmp = "%s.tmp.%s.%d" % (p, ME, os.getpid()) with open(tmp, "w", encoding="utf-8") as f: json.dump(o, f, indent=1, ensure_ascii=False) os.replace(tmp, p) def status(t): return jload(os.path.join(STATUSD, safe(t["id"]) + ".json"), {}) or {} def set_status(t, **kw): s = status(t) s.update(kw, id=t["id"], row=t.get("row"), updated_utc=utc(), by=ME) jdump(s, os.path.join(STATUSD, safe(t["id"]) + ".json")) return s # ------------------------------------------------------------------ claims, locks, heartbeats HB = {"dirs": set()} def claim(key): d = os.path.join(CLAIMD, safe(key)) try: os.mkdir(d) except FileExistsError: hb = os.path.join(d, "heartbeat") try: age = time.time() - (os.path.getmtime(hb) if os.path.exists(hb) else os.path.getmtime(d)) except FileNotFoundError: return None if age < 900: return None shutil.rmtree(d, ignore_errors=True) try: os.mkdir(d) except FileExistsError: return None with open(os.path.join(d, "owner"), "w") as f: f.write("%s %s pid %d\n" % (ME, utc(), os.getpid())) with open(os.path.join(d, "heartbeat"), "w") as f: f.write(utc()) HB["dirs"].add(d) return d def release(d): if d: HB["dirs"].discard(d) shutil.rmtree(d, ignore_errors=True) def held(key): d = os.path.join(CLAIMD, safe(key)) if not os.path.isdir(d): return False hb = os.path.join(d, "heartbeat") try: return time.time() - (os.path.getmtime(hb) if os.path.exists(hb) else os.path.getmtime(d)) < 900 except FileNotFoundError: return False ALIVE = os.path.join(ALIVED, ME) def hb_loop(): while True: for d in list(HB["dirs"]) + [None]: try: with open(os.path.join(d, "heartbeat") if d else ALIVE, "w") as f: f.write(utc()) except Exception: # noqa: BLE001 pass time.sleep(30) def slot_alive(slot): for f in os.listdir(ALIVED): if f.startswith(slot + "_w") and f != ME: try: if time.time() - os.path.getmtime(os.path.join(ALIVED, f)) < 120: return True except FileNotFoundError: pass return False threading.Thread(target=hb_loop, daemon=True).start() CUR = {"proc": None, "term": False} def on_term(signum, frame): # noqa: ARG001 CUR["term"] = True p = CUR["proc"] if p is not None: try: os.killpg(p.pid, signal.SIGTERM) except ProcessLookupError: pass signal.signal(signal.SIGTERM, on_term) # ------------------------------------------------------------------ completeness of evaluation tasks def complete_sets(t): """sets written completely: VLMA in meta.json key test_pass (greedy folder and _retry); maker-code arms in meta_testpass.json key sets (greedy folder decides: an adapter may have no sampling path).""" out, refused = {}, set() for ck in (t["ckpt"], t["ckpt"] + "_retry"): if t["kind"] == "vlmb": m = jload(os.path.join(P["preds_root"], t["arm"], ck, "meta_testpass.json"), {}) or {} s, ref = m.get("sets") or {}, m.get("refused_sets") or [] else: m = jload(os.path.join(P["preds_root"], t["arm"], ck, "meta.json"), {}) or {} tp = m.get("test_pass") or {} s, ref = tp.get("sets") or {}, tp.get("refused_sets") or [] out[ck] = sorted(k for k, v in s.items() if isinstance(v, dict) and v.get("complete") is True) refused |= {x.get("name") for x in ref if isinstance(x, dict)} return out, refused def eval_done(t): c, refused = complete_sets(t) want = set(t["sets"]) - refused if t["kind"] == "vlmb": return want <= set(c[t["ckpt"]]), c, refused return want <= set(c[t["ckpt"]]) and want <= set(c[t["ckpt"] + "_retry"]), c, refused # ------------------------------------------------------------------ commands def command(t): if t["kind"] == "cmd": env = dict(os.environ) env.update(CFG.get("cmd_env", {})) # tests only (scratch paths for LINEDET); absent in the real config env.update(t.get("env", {})) env["TESTPASS_DIR"] = TPD return list(t["argv"]), env common = ["--arm", t["arm"], "--ckpt", t["ckpt"], "--evalsets", P["evalsets"], "--preds-root", P["preds_root"], "--sets", ",".join(t["sets"]), "--test-pass", "--gate-file", P["gate_vlm"], "--batch", str(t.get("batch", 16)), "--deadline-utc", T["evaluations_stop_at"]] if t.get("limit"): common += ["--limit", str(t["limit"])] if t.get("device"): common += ["--device", t["device"]] if t["kind"] == "vlmb": env = lc.vlmb_env(t["short"], os.environ) cmd = lc.vlmb_python(t["short"]) + [os.path.join(lc.VB, "vlmb_eval_vlm_testpass.py"), "--short", t["short"], "--base-dir", os.path.join(P["data"], "hf_cache", "r5_vlmb_models", t["short"]), "--state", t["state"], "--registry", P["maker_registry"]] + common return cmd, env env = dict(os.environ) env.update(HF_HUB_OFFLINE="1", TOKENIZERS_PARALLELISM="false") cmd = PY + [os.path.join(HERE, "eval_vlm_test.py"), "--short", t["short"], "--model-dir", t["model_dir"], "--registry", P["vlma_registry"]] + common return cmd, env def run(t): cmd, env = command(t) for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): env.pop(k, None) env["PYTHONUNBUFFERED"] = "1" lp = os.path.join(LOGD, "testpass_%s_%s.log" % (safe(t["id"]), ME)) term_at = STOP + (0 if t["kind"] == "cmd" else GRACE) say("%s: start; log %s" % (t["id"], lp)) t0, termed = time.time(), None with open(lp, "a") as lf: lf.write("\n===== %s %s cmd: %s\n" % (utc(), ME, " ".join(cmd))) lf.flush() p = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT, env=env, cwd=TPD, start_new_session=True) CUR["proc"] = p while True: try: rc = p.wait(timeout=5) break except subprocess.TimeoutExpired: now = time.time() if termed is None and (now >= term_at or CUR["term"]): termed = now say("%s: stop time (J4) or SIGTERM: SIGTERM to its process group" % t["id"]) try: os.killpg(p.pid, signal.SIGTERM) except ProcessLookupError: pass elif termed is not None and now >= termed + KILL_AFTER: try: os.killpg(p.pid, signal.SIGKILL) except ProcessLookupError: pass CUR["proc"] = None try: # workers left behind in the group (DataLoader, Pool) go with it os.killpg(p.pid, signal.SIGKILL) except (ProcessLookupError, PermissionError): pass say("%s: exit %s after %.0fs%s" % (t["id"], rc, time.time() - t0, " (stopped)" if termed else "")) return rc, lp, round(time.time() - t0, 1), termed is not None # ------------------------------------------------------------------ start of the pass say("config %s; slot %s worker %d; times: not before %s, no start from %s, stop %s" % (A.config, A.slot, A.worker, T["not_before"], T["no_task_starts_from"], T["evaluations_stop_at"])) said = 0 while time.time() < NOT_BEFORE or not os.path.exists(P["gate_vlm"]): if time.time() >= NO_START or CUR["term"]: say("the pass did not open before %s (gate file %s exists: %s); exit" % (T["no_task_starts_from"], P["gate_vlm"], os.path.exists(P["gate_vlm"]))) sys.exit(0) if time.time() - said > 600: say("waiting: not before %s, gate file %s exists: %s" % (T["not_before"], P["gate_vlm"], os.path.exists(P["gate_vlm"]))) said = time.time() time.sleep(15) if A.worker >= 1 and A.nfile: # J3: the N file is read when the pass opens, so a check written after the job started counts try: nval = open(A.nfile).read(1) except OSError: nval = "" if nval != "2": say("J3: %s does not say 2 (%r): worker %d exits, this slot runs one process" % (A.nfile, nval, A.worker)) sys.exit(0) say("J3: %s says 2: worker %d runs as the second process of slot %s" % (A.nfile, A.worker, A.slot)) if A.tasks: TL = A.tasks else: TL = os.path.join(TPD, "tasks_shared.json") B_CMD = PY + [os.path.join(HERE, "testpass_build_tasks.py"), "--config", A.config, "--final"] rc = subprocess.call(B_CMD) if rc != 0 or not os.path.exists(TL): say("the builder failed (exit %s): second try with --force-fallback (J2 fallback)" % rc) rc = subprocess.call(B_CMD + ["--force-fallback"]) if rc != 0 or not os.path.exists(TL): say("REFUSED: the task list could not be built (builder exit %s)" % rc) sys.exit(6) DOC = jload(TL) TASKS = DOC["tasks"] say("task list %s: mode %s, %d tasks, B1 %s, B2 %s" % (TL, DOC.get("mode"), len(TASKS), DOC.get("B1"), DOC.get("B2"))) PIN_WAIT = {} NOTED = set() def note_once(key, msg): if key not in NOTED: NOTED.add(key) say(msg) def lock_conflict(t, own): """True when the task may not run now: its own lock is held (before claiming), a lock in blocked_by is held, or (exclusive_prefix) any other lock with that prefix is held. own=True: after this process claimed the task's lock.""" if not own and t.get("lock") and held("lock_" + t["lock"]): return True if any(held("lock_" + x) for x in t.get("blocked_by", [])): return True pre = t.get("exclusive_prefix") if pre: mine = safe("lock_" + t["lock"]) if t.get("lock") else None for d in os.listdir(CLAIMD): if d.startswith(safe("lock_" + pre)) and d != mine and held(d): return True return False def pick(retry_pass): """first claimable task in list order; returns (task, claim, lockclaim) or ('wait', None, None) or (None, None, None)""" blocked = False for t in TASKS: s = status(t) st = s.get("status") if st in FINAL: continue if retry_pass != (st == "failed"): continue if t["kind"] != "cmd": ok, c, _ = eval_done(t) if ok: set_status(t, status="done", note="complete before this process looked", complete_sets=c) continue if t.get("exists_path") and not os.path.exists(t["exists_path"]): set_status(t, status="not_run_no_checkpoint", note="no checkpoint at %s when the task came up (%s)" % (t["exists_path"], utc())) say("%s: not run, no checkpoint %s" % (t["id"], t["exists_path"])) continue if t.get("gate") and not os.path.exists(t["gate"]): note_once("gate" + t["id"], "%s: its gate file %s does not exist yet: passed over until it exists (J9)" % (t["id"], t["gate"])) blocked = True continue if held("task_" + t["id"]): continue pin = t.get("slot") if pin and pin != A.slot: if slot_alive(pin): w0 = PIN_WAIT.setdefault(t["id"], time.time()) if time.time() - w0 < float(t.get("pin_wait_max_seconds", 900)): note_once("pin" + t["id"], "%s: pinned to slot %s (J8), which has a live runner: waiting so that no later row starts first (J2)" % (t["id"], pin)) return "wait", None, None note_once("pinx" + t["id"], "%s: slot %s did not start it within %.0f s: run here (J8 placement departure, recorded)" % (t["id"], pin, time.time() - w0)) else: note_once("pinn" + t["id"], "%s: pinned to slot %s, which has no live runner: run here (J8 placement departure, recorded)" % (t["id"], pin)) if lock_conflict(t, own=False): blocked = True continue cl = claim("task_" + t["id"]) if cl is None: continue lk = None if t.get("lock"): lk = claim("lock_" + t["lock"]) if lk is None: release(cl) blocked = True continue if lock_conflict(t, own=True): # checked again after claiming: of two tasks claiming at once, at least one backs off release(lk) release(cl) blocked = True continue return t, cl, lk return ("wait" if blocked else None), None, None for retry_pass in (False, True): while not CUR["term"]: if time.time() >= NO_START: say("no task starts from %s (J4)" % T["no_task_starts_from"]) break t, cl, lk = pick(retry_pass) if t == "wait": time.sleep(30) continue if t is None: break s = status(t) extra = {} if t["id"] in PIN_WAIT: extra["pin_wait_seconds"] = round(time.time() - PIN_WAIT[t["id"]], 1) extra["ran_on_slot"] = A.slot set_status(t, status="running", started_utc=utc(), failures=s.get("failures", 0), **extra) try: rc, lp, sec, stopped = run(t) finally: release(lk) release(cl) hist = (status(t).get("history") or []) + [{"by": ME, "rc": rc, "seconds": sec, "ended_utc": utc(), "log": lp, "stopped": stopped}] if t["kind"] == "cmd": ok = rc == 0 c = None else: ok, c, refused = eval_done(t) fails = s.get("failures", 0) if ok: st = "done" elif rc == 10 and t["kind"] == "cmd": st = "not_run_no_checkpoint" elif stopped or time.time() >= STOP: st = "stopped_by_deadline" else: fails += 1 st = "failed" if fails < 2 else "failed_final" set_status(t, status=st, rc=rc, failures=fails, history=hist, complete_sets=c) say("%s: %s%s" % (t["id"], st, "" if c is None else " (complete: %s)" % c)) # ------------------------------------------------------------------ summary (J4: what was not run by the deadline) rows = [] for t in TASKS: s = status(t) r = {"id": t["id"], "row": t.get("row"), "kind": t["kind"], "arm": t.get("arm"), "ckpt": t.get("ckpt"), "sets": t.get("sets"), "status": s.get("status", "not_started"), "rc": s.get("rc"), "failures": s.get("failures", 0)} if t["kind"] != "cmd": ok, c, refused = eval_done(t) r["complete_sets"] = c r["refused_sets"] = sorted(x for x in refused if x) for k in ("pin_wait_seconds", "ran_on_slot", "note"): if k in s: r[k] = s[k] rows.append(r) summ = {"written_utc": utc(), "by": ME, "task_list": TL, "mode": DOC.get("mode"), "not_run_by_the_deadline": [r["id"] for r in rows if r["status"] not in ("done", "not_run_no_checkpoint")], "tasks": rows} jdump(summ, os.path.join(TPD, "summary_%s.json" % ME)) say("runner finished; %d of %d tasks not done (summary_%s.json)" % (len(summ["not_run_by_the_deadline"]), len(rows), ME))