File size: 3,968 Bytes
158258b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/env python3
"""Persist a five-minute machine-readable heartbeat for the Codex SDK sweep."""

from __future__ import annotations

import argparse
import json
import os
import subprocess
import time
from datetime import datetime, timezone
from pathlib import Path

from ptb_codex_sdk_status import MODELS, ROOT, SWEEP, TASKS, classify

INITIAL_JOB = {
    (model, task): str(402112 + model_i * len(TASKS) + task_i)
    for model_i, model in enumerate(MODELS)
    for task_i, task in enumerate(TASKS)
}
TERMINAL_FAILURES = {
    "BOOT_FAIL", "CANCELLED", "DEADLINE", "FAILED", "NODE_FAIL", "OUT_OF_MEMORY",
    "PREEMPTED", "REVOKED", "TIMEOUT",
}


def current_jobs() -> dict[tuple[str, str], str]:
    """Overlay recovery job IDs recorded after an initial cell failure."""
    jobs = dict(INITIAL_JOB)
    path = ROOT / "RECOVERY_JOBS.json"
    if path.is_file():
        for key, job in json.loads(path.read_text()).items():
            model, task = key.split("|", 1)
            jobs[(model, task)] = str(job)
    return jobs


def scheduler_states(jobs: dict[tuple[str, str], str]) -> dict[str, dict[str, str]]:
    ids = ",".join(jobs.values())
    output = subprocess.run(
        ["sacct", "-j", ids, "--format=JobIDRaw,State,ExitCode,Elapsed", "-n", "-P"],
        check=False, capture_output=True, text=True,
    ).stdout
    states: dict[str, dict[str, str]] = {}
    for line in output.splitlines():
        job, state, code, elapsed, *_ = (line.split("|") + [""] * 4)[:4]
        if "." not in job and job in jobs.values():
            states[job] = {"state": state.split()[0], "exit_code": code, "elapsed": elapsed}
    return states


def build_snapshot() -> dict:
    jobs = current_jobs()
    scheduler = scheduler_states(jobs)
    cells = []
    counts: dict[str, int] = {}
    action_required = []
    for model in MODELS:
        safe_model = model.replace("/", "_")
        for task in TASKS:
            runs = sorted(SWEEP.glob(f"{task}_{safe_model}_*"))
            run = runs[-1] if runs else None
            status, score = classify(run)
            counts[status] = counts.get(status, 0) + 1
            job = jobs[(model, task)]
            job_state = scheduler.get(job, {}).get("state", "UNKNOWN")
            cell = {
                "task": task, "model": model, "job_id": job, "job_state": job_state,
                "artifact_status": status, "score": score,
                "run_dir": str(run) if run else None,
            }
            cells.append(cell)
            if job_state in TERMINAL_FAILURES and status != "complete":
                action_required.append(cell)
    return {
        "checked_at": datetime.now(timezone.utc).isoformat(),
        "results_root": str(ROOT),
        "counts": counts,
        "complete": counts.get("complete", 0) == len(TASKS) * len(MODELS),
        "action_required": action_required,
        "cells": cells,
    }


def write_snapshot(snapshot: dict) -> None:
    ROOT.mkdir(parents=True, exist_ok=True)
    temporary = ROOT / "WATCH_STATUS.json.tmp"
    destination = ROOT / "WATCH_STATUS.json"
    temporary.write_text(json.dumps(snapshot, indent=2) + "\n")
    temporary.replace(destination)
    with (ROOT / "WATCH.log").open("a") as log:
        log.write(f"{snapshot['checked_at']} counts={snapshot['counts']} "
                  f"action_required={len(snapshot['action_required'])}\n")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--interval", type=int, default=300)
    parser.add_argument("--once", action="store_true")
    args = parser.parse_args()
    while True:
        snapshot = build_snapshot()
        write_snapshot(snapshot)
        print(json.dumps({key: snapshot[key] for key in
                          ("checked_at", "counts", "complete", "action_required")}), flush=True)
        if args.once or snapshot["complete"]:
            return
        time.sleep(args.interval)


if __name__ == "__main__":
    main()