|
| 1 | +"""Independent availability recovery, without interrupting training or operator pauses.""" |
| 2 | + |
| 3 | +import argparse |
| 4 | +import fcntl |
| 5 | +import json |
| 6 | +import shlex |
| 7 | +import subprocess |
| 8 | +import time |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | +from rlm.v100.common import atomic_json, load_profile |
| 12 | +from rlm.v100.mission import status |
| 13 | +from rlm.v100.supervisor import install |
| 14 | + |
| 15 | +EXCLUSIVE = {"train", "mission-prepare", "optimize-mtp", "calibrate-training", "test-mtp"} |
| 16 | + |
| 17 | + |
| 18 | +def exclusive_work(root: Path) -> bool: |
| 19 | + rows = subprocess.check_output(["ps", "-eo", "args="], text=True, timeout=10) |
| 20 | + for row in rows.splitlines(): |
| 21 | + if "rlm.v100.cli" not in row: |
| 22 | + continue |
| 23 | + arguments = shlex.split(row) |
| 24 | + if "rlm.v100.cli" in arguments and arguments.count("--root") == 1: |
| 25 | + index = arguments.index("--root") + 1 |
| 26 | + if index < len(arguments) and Path(arguments[index]).resolve() == root.resolve(): |
| 27 | + if EXCLUSIVE.intersection(arguments): |
| 28 | + return True |
| 29 | + return False |
| 30 | + |
| 31 | + |
| 32 | +def preserved_profile(root: Path, record: dict) -> Path: |
| 33 | + candidates = [] |
| 34 | + if record.get("learning", {}).get("live_profile"): |
| 35 | + candidates.append(Path(record["learning"]["live_profile"])) |
| 36 | + if record.get("run"): |
| 37 | + candidates.append(Path(record["run"]) / "input-profile.json") |
| 38 | + checkpoint = root / "research/availability-recovery-update/current.json" |
| 39 | + if checkpoint.is_file(): |
| 40 | + candidates.append(Path(json.loads(checkpoint.read_text())["profile"])) |
| 41 | + errors = [] |
| 42 | + for path in candidates: |
| 43 | + path = path.resolve() |
| 44 | + if path.is_relative_to(root / "research") and path.is_file(): |
| 45 | + try: |
| 46 | + load_profile(path, root) |
| 47 | + return path |
| 48 | + except (ValueError, OSError, KeyError) as error: |
| 49 | + errors.append(str(error)[:200]) |
| 50 | + raise ValueError("No valid preserved accepted profile: " + "; ".join(errors)) |
| 51 | + |
| 52 | + |
| 53 | +def recover(root: Path, resume: bool = False) -> dict: |
| 54 | + root = root.resolve() |
| 55 | + folder = root / "research/mission-watchdog" |
| 56 | + folder.mkdir(parents=True, exist_ok=True) |
| 57 | + receipt = folder / "status.json" |
| 58 | + request = folder / "resume-request.json" |
| 59 | + if resume: |
| 60 | + atomic_json(request, {"requested": time.time()}) |
| 61 | + resume = resume or request.exists() |
| 62 | + with ( |
| 63 | + (folder / "lease.lock").open("a") as lease, |
| 64 | + (root / "research/mission-maintenance.lock").open("a") as maintenance, |
| 65 | + ): |
| 66 | + try: |
| 67 | + fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| 68 | + fcntl.flock(maintenance, fcntl.LOCK_SH | fcntl.LOCK_NB) |
| 69 | + except BlockingIOError: |
| 70 | + return {"stage": "maintenance-in-progress", "updated": time.time()} |
| 71 | + try: |
| 72 | + record = status(root) |
| 73 | + pause = root / "research/supervisor/pause.json" |
| 74 | + if resume: |
| 75 | + pause.unlink(missing_ok=True) |
| 76 | + if pause.exists(): |
| 77 | + result = {"stage": "operator-paused"} |
| 78 | + elif record.get("running"): |
| 79 | + request.unlink(missing_ok=True) |
| 80 | + result = {"stage": "mission-running", "run": record.get("run")} |
| 81 | + elif exclusive_work(root): |
| 82 | + result = { |
| 83 | + "stage": "deferred-training", |
| 84 | + "reason": "Owned exclusive job remains active", |
| 85 | + } |
| 86 | + else: |
| 87 | + previous = json.loads(receipt.read_text()) if receipt.is_file() else {} |
| 88 | + if not resume and time.time() < previous.get("next_retry", 0): |
| 89 | + result = {**previous, "stage": "recovery-backoff"} |
| 90 | + else: |
| 91 | + supervisor = root / "research/supervisor/status.json" |
| 92 | + state = json.loads(supervisor.read_text()) if supervisor.is_file() else {} |
| 93 | + if state.get("running") and 0 <= time.time() - state.get("updated", 0) < 15: |
| 94 | + result = {"stage": "supervisor-recovering", "supervisor": state} |
| 95 | + else: |
| 96 | + profile = preserved_profile(root, record) |
| 97 | + # Recheck after profile validation; another owned process may have started. |
| 98 | + if status(root).get("running") or exclusive_work(root): |
| 99 | + result = {"stage": "work-started-during-check"} |
| 100 | + else: |
| 101 | + result = { |
| 102 | + "stage": "recovery-submitted", |
| 103 | + "profile": str(profile), |
| 104 | + "supervisor": install(root, profile), |
| 105 | + "next_retry": time.time() + 300, |
| 106 | + } |
| 107 | + except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError) as error: |
| 108 | + result = { |
| 109 | + "stage": "recovery-blocked", |
| 110 | + "error": str(error)[:1000], |
| 111 | + "next_retry": time.time() + 300, |
| 112 | + } |
| 113 | + result["updated"] = time.time() |
| 114 | + atomic_json(receipt, result) |
| 115 | + return result |
| 116 | + |
| 117 | + |
| 118 | +def main() -> None: |
| 119 | + parser = argparse.ArgumentParser() |
| 120 | + parser.add_argument("--root", type=Path, required=True) |
| 121 | + parser.add_argument("--resume", action="store_true") |
| 122 | + args = parser.parse_args() |
| 123 | + print(json.dumps(recover(args.root, args.resume)), flush=True) |
| 124 | + |
| 125 | + |
| 126 | +if __name__ == "__main__": |
| 127 | + main() |
0 commit comments