#!/usr/bin/env python3 """Launch independent collection workers across CPU/GPU slots.""" from __future__ import annotations import argparse import json import os from pathlib import Path import shlex import shutil import subprocess import sys import tempfile import time ROOT = Path(__file__).resolve().parents[2] COLLECTOR = Path(__file__).with_name("collect_one.py") IDLE_CASES = frozenset(("", "-", "idle", "none")) def _normalize_case(case) -> str: value = "" if case is None else str(case).strip() return "" if value.lower() in IDLE_CASES else value def parse_slots(value: str) -> list[dict]: slots = [] for item in value.split(";"): parts = item.split(":") if len(parts) != 4: raise ValueError("slots must use slot:cpus:gpu:case;...") slot, cpus, gpu, case = parts if not slot: raise ValueError("each slot needs a name") slots.append({"slot": slot, "cpus": cpus, "gpu": gpu, "case": _normalize_case(case)}) if not slots: raise ValueError("at least one slot is required") return slots def load_json(path: Path) -> dict: try: value = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise ValueError(f"cannot read queue config {path}: {exc}") from exc if not isinstance(value, dict): raise ValueError("queue config must be a JSON object") return value def save(path: Path, value: dict) -> None: path.parent.mkdir(parents=True, exist_ok=True) fd, name = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent) temporary = Path(name) try: with os.fdopen(fd, "w", encoding="utf-8") as stream: stream.write(json.dumps(value, ensure_ascii=False, indent=2) + "\n") temporary.replace(path) finally: temporary.unlink(missing_ok=True) def _iter_process_argv(): proc_root = Path("/proc") if proc_root.is_dir(): for process_dir in proc_root.iterdir(): if not process_dir.name.isdigit(): continue try: raw = (process_dir / "cmdline").read_bytes() except OSError: continue argv = [part.decode(errors="replace") for part in raw.split(b"\0") if part] if argv: yield argv return try: result = subprocess.run( ["ps", "-axo", "pid=,command="], check=False, capture_output=True, text=True, ) except OSError: return if result.returncode != 0: return for line in result.stdout.splitlines(): line = line.strip() if not line: continue fields = line.split(None, 1) command = fields[1] if len(fields) == 2 and fields[0].isdigit() else line try: argv = shlex.split(command) except ValueError: continue if argv: yield argv def _case_process_running(case: str) -> bool: for argv in _iter_process_argv(): if not any(Path(token).name == "collect_one.py" for token in argv): continue for index, token in enumerate(argv): if token == "--case-id" and index + 1 < len(argv) and argv[index + 1] == case: return True if token == "--case-id=" + case: return True return False def _write_orphaned(logs: Path, case: str) -> None: marker = logs / case / "ORPHANED.json" if marker.is_file(): return try: save(marker, { "case_id": case, "status": "orphaned", "log_dir": str(logs / case), "recorded_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), }) except OSError as exc: print(f"collection_queue: cannot write orphan marker for {case}: {exc}", flush=True) def status_for(logs: Path, case: str, process: subprocess.Popen | None) -> tuple[str | None, int | None]: case_log = logs / case success = (case_log / "SUCCESS.json").is_file() failed = (case_log / "FAILED").is_file() if process is None: if success: return "success", None if failed: return "failed", None if _case_process_running(case): return "running", None _write_orphaned(logs, case) return "orphaned", None returncode = process.poll() if returncode is None: return "running", None if returncode == 0 and success: return "success", returncode if failed or returncode != 0: return "failed", returncode return "failed", returncode def _rebuild_slots(slot_specs: list[dict], previous_slots) -> list[dict]: previous_cases = {} if isinstance(previous_slots, list): for previous in previous_slots: if not isinstance(previous, dict): continue name = previous.get("slot") case = _normalize_case(previous.get("case")) if name and case and name not in previous_cases: previous_cases[name] = case slots = [] assigned = set() for spec in slot_specs: slot = dict(spec) case = previous_cases.get(slot["slot"], "") if case in assigned: case = "" slot["case"] = case if case: assigned.add(case) slots.append(slot) return slots def _launch_failure(logs: Path, case: str, status: str, started: float | None) -> bool: if status != "failed": return False try: if (logs / case / "FAILED").read_text(encoding="utf-8").strip() == "insufficient_disk": return True except OSError: pass if started is not None: return time.monotonic() - started <= 120 try: metadata = load_json(logs / case / "queue_meta.json") elapsed = time.time() - float(metadata["launch_time"]) return 0 <= elapsed <= 120 except (ValueError, KeyError, TypeError): return False def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--config", type=Path, required=True) parser.add_argument("--base", type=Path, help="legacy data root for default dataset/log locations") parser.add_argument("--host", help="optional host label recorded by older queue callers") parser.add_argument("--dataset", type=Path) parser.add_argument("--log-root", type=Path) parser.add_argument("--library", type=Path) parser.add_argument("--tree", type=Path, default=ROOT) parser.add_argument("--seed-base", type=int, required=True) parser.add_argument( "--slots", required=True, help="slot:cpus:gpu:case;... (empty/idle/none/- case means free)", ) parser.add_argument("--start-index", type=int, default=1) parser.add_argument("--max-new", type=int, default=100) parser.add_argument("--interval", type=float, default=30) parser.add_argument("--min-free-gb", type=float, help="override config disk threshold (GiB; default 30)") parser.add_argument("--launch-failure-streak", type=int, default=8) parser.add_argument("--launch-failure-cooldown-s", type=float, default=600, help="pause new launches after consecutive fast failures (seconds)") args = parser.parse_args(argv) try: slots = parse_slots(args.slots) queue_config = load_json(args.config) except ValueError as exc: parser.error(str(exc)) base = args.base.resolve() if args.base else None tree = args.tree.resolve() sys.path.insert(0, str(tree)) from rhg_paths import resolve from tools.collection.collect_one import disk_space_problem, min_free_gb try: minimum = min_free_gb(args.min_free_gb if args.min_free_gb is not None else resolve(queue_config.get("min_free_gb"))) if args.launch_failure_streak <= 0: raise ValueError("--launch-failure-streak must be positive") if not 0 < args.launch_failure_cooldown_s < float("inf"): raise ValueError("--launch-failure-cooldown-s must be positive and finite") except ValueError as exc: parser.error(str(exc)) dataset_value = args.dataset or queue_config.get("dataset") logs_value = args.log_root or queue_config.get("log_root") dataset = Path(resolve(str(dataset_value))) if dataset_value else None logs = Path(resolve(str(logs_value))) if logs_value else None if base is not None: dataset = dataset or base / "home_scene_dataset" logs = logs or base / "collection_logs" if dataset is None or logs is None: parser.error("provide --dataset and --log-root (or set both fields in the config)") dataset = dataset.resolve() logs = logs.resolve() state_path = logs / "queue_state.json" heavy_path = logs / "queue_heavy_retest.jsonl" state = {"next_index": args.start_index, "launched": 0, "completed": [], "slots": slots} if state_path.is_file(): try: previous = json.loads(state_path.read_text(encoding="utf-8")) if isinstance(previous, dict): for key in ("next_index", "launched"): if key in previous: state[key] = previous[key] if isinstance(previous.get("completed"), list): state["completed"] = previous["completed"] state["slots"] = _rebuild_slots(slots, previous.get("slots")) except (OSError, json.JSONDecodeError): pass io_warnings = set() state_needs_save = True def warn_io(label: str, exc: OSError) -> None: if label not in io_warnings: print(f"collection_queue: cannot write {label}: {exc}", flush=True) io_warnings.add(label) def persist_state() -> None: nonlocal state_needs_save try: save(state_path, state) state_needs_save = False io_warnings.discard("queue state") except OSError as exc: state_needs_save = True warn_io("queue state", exc) persist_state() processes: dict[str, subprocess.Popen] = {} started_at: dict[str, float] = {} failure_streak = 0 pause_until = 0.0 disk_waiting = False def launch(slot: dict) -> None: index = int(state["next_index"]) case = f"queue_{index:06d}" seed = args.seed_base + index command = [sys.executable, str(COLLECTOR), "--config", str(args.config.resolve()), "--case-id", case, "--seed", str(seed), "--dataset", str(dataset), "--log-root", str(logs), "--min-free-gb", str(minimum)] if slot["cpus"] not in ("", "-", "none", "None"): command += ["--cpus", str(slot["cpus"])] if slot["gpu"] not in ("", "-", "none", "None"): command += ["--gpu", str(slot["gpu"])] if args.library: command += ["--library", str(args.library.resolve())] case_log = logs / case case_log.mkdir(parents=True, exist_ok=True) save(case_log / "queue_meta.json", { "case_id": case, "seed": seed, "slot": slot["slot"], "cpus": slot["cpus"], "gpu": slot["gpu"], "tree": str(tree), "config": str(args.config.resolve()), "host": args.host, "started_by": "collection_queue.py", "launch_time": time.time(), }) started = time.monotonic() with (case_log / "launcher.log").open("ab", buffering=0) as stream: process = subprocess.Popen(command, cwd=tree, env=os.environ.copy(), stdout=stream, stderr=subprocess.STDOUT, start_new_session=True) processes[case] = process started_at[case] = started slot["case"] = case state["next_index"] = index + 1 state["launched"] = int(state["launched"]) + 1 while True: changed = False for slot in state["slots"]: case = slot.get("case") or "" if case: status, returncode = status_for(logs, case, processes.get(case)) if status in {"success", "failed", "orphaned"}: entry = {"case_id": case, "status": status, "returncode": returncode, "log_dir": str(logs / case), "time": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} state["completed"].append(entry) if status == "failed": try: with heavy_path.open("a", encoding="utf-8") as stream: stream.write(json.dumps(dict(entry, kind="heavy_retest"), ensure_ascii=False) + "\n") io_warnings.discard("heavy retest log") except OSError as exc: warn_io("heavy retest log", exc) if _launch_failure(logs, case, status, started_at.pop(case, None)): failure_streak += 1 if failure_streak >= args.launch_failure_streak: pause_until = time.monotonic() + args.launch_failure_cooldown_s print(f"collection_queue: launch failure circuit open: {failure_streak} " f"consecutive failures within 120s or insufficient_disk; " f"last case={case}, returncode={returncode}; " f"pausing launches for {args.launch_failure_cooldown_s:g}s", flush=True) failure_streak = 0 else: failure_streak = 0 slot["case"] = "" processes.pop(case, None) changed = True # Reap every slot before refilling so a failure burst cannot consume more IDs. for slot in state["slots"]: if slot.get("case") or int(state["launched"]) >= args.max_new: continue if time.monotonic() < pause_until: break problem = disk_space_problem((tree / "engine" / "runs", logs), minimum, usage=shutil.disk_usage) if problem: if not disk_waiting: print(f"collection_queue: waiting: insufficient_disk: {problem}", flush=True) disk_waiting = True break if disk_waiting: print("collection_queue: disk space recovered; resuming launches", flush=True) disk_waiting = False try: launch(slot) changed = True except OSError as exc: pause_until = time.monotonic() + args.launch_failure_cooldown_s print(f"collection_queue: launch failed without consuming an ID: {exc}; " f"pausing launches for {args.launch_failure_cooldown_s:g}s", flush=True) break if changed or state_needs_save: persist_state() if int(state["launched"]) >= args.max_new and not any(slot.get("case") for slot in state["slots"]): break time.sleep(max(0.0, args.interval)) persist_state() return 0 if __name__ == "__main__": raise SystemExit(main())