"""One Kaggle session: pick a runnable job, hold its lease, run it until done or out of time. python -m pocket_math.runner --job auto --ops-repo ORG/pocket-math-ops Friends never pass anything but the job id. Everything else comes from the queue and the job's own repo, so any account can continue any job. """ from __future__ import annotations import argparse import os import shutil import subprocess import sys import time import traceback import uuid from pathlib import Path from .config import PROJECT_DIR, resolve_job_config from .context import JobContext, OutOfTime, Session, secret_values from .hub import Heartbeat, JobHandle, Lease, LeaseLost, make_store, use_http_timeouts from .queue import DONE, FAILED, JobView, QueueEntry, job_repo, parse_queue, runnable LEASE_TTL = 45 * 60 HEARTBEAT_EVERY = 10 * 60 MAX_FAILS = 2 MIN_MINUTES_TO_START = 25 def detect_gpus() -> int: if shutil.which("nvidia-smi") is None: return 0 out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True).stdout return sum(1 for line in out.splitlines() if line.startswith("GPU ")) def code_sha() -> str: if os.environ.get("PM_CODE_SHA"): return os.environ["PM_CODE_SHA"] marker = PROJECT_DIR / "CODE_SHA" if marker.exists(): return marker.read_text().strip() try: return subprocess.run(["git", "-C", str(PROJECT_DIR), "rev-parse", "HEAD"], capture_output=True, text=True, timeout=20).stdout.strip() or "unknown" except (OSError, subprocess.SubprocessError): return "unknown" def whoami(hub: str) -> str: if hub != "hf": return os.environ.get("USER") or os.environ.get("USERNAME") or "local" try: from huggingface_hub import HfApi return HfApi(token=os.environ.get("HF_TOKEN")).whoami()["name"] except Exception: # noqa: BLE001 - attribution only return "unknown" def job_views(entries: list[QueueEntry], ops_repo: str, hub: str) -> dict[str, JobView]: views = {} for e in entries: store = make_store(job_repo(ops_repo, e.id), hub) head = store.head() if head is None: views[e.id] = JobView(None, None) continue state_text = store.read_text("state.json", revision=head) import json status = json.loads(state_text).get("status") if state_text else None views[e.id] = JobView(status, Lease.parse(store.read_text("lease.json", revision=head))) return views def run_job(entry: QueueEntry, handle: JobHandle, session: Session) -> str: """Returns "done", "paused", "failed" or "lost".""" from .jobs import HANDLERS beat = Heartbeat(handle, HEARTBEAT_EVERY) beat.start() ctx: JobContext | None = None try: config = handle.read_json("config.json") or resolve_job_config(entry.config, entry.overrides, org=session.ops_repo.split("/")[0]) state = handle.read_json("state.json", {}) or {"status": "new", "fails": 0, "sessions": []} ctx = JobContext(entry.id, config, handle, session, state) sessions = [*state.get("sessions", []), {"id": session.id, "user": session.user, "start": time.time()}] ctx.commit({"config.json": config}, "session start", state={"status": "running", "sessions": sessions[-50:]}) handler = HANDLERS[config["kind"]] try: outcome = handler(ctx) except OutOfTime as e: ctx.log(f"pausing: {e}") outcome = "paused" ctx.commit({}, f"session end: {outcome}", state={"status": DONE if outcome == "done" else "paused", "fails": 0}) return outcome except LeaseLost: print(f"lease on {entry.id} was taken over; this session stops writing", flush=True) return "lost" except Exception as e: # noqa: BLE001 - record the failure in the job repo, then let the next job run tb = traceback.format_exc() message = f"{type(e).__name__}: {str(e)[:500]}" for secret in secret_values(): tb, message = tb.replace(secret, "***"), message.replace(secret, "***") print(tb, flush=True) if ctx is None or handle.lost.is_set(): return "failed" fails = int(ctx.state.get("fails", 0)) + 1 status = FAILED if fails >= MAX_FAILS else "paused" try: ctx.commit({"logs/last_error.txt": tb[-6000:]}, f"error: {type(e).__name__}", state={"status": status, "fails": fails, "last_error": message}) except LeaseLost: return "lost" return "failed" finally: beat.stop() beat.join(timeout=900) if not handle.lost.is_set(): try: handle.commit({}, "release", released=True) except Exception as e: # noqa: BLE001 - an unreleased lease expires on its own after LEASE_TTL print(f"lease release failed ({type(e).__name__}); it expires in {LEASE_TTL // 60} min", flush=True) def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--job", default="auto", help="a job id from the queue, or 'auto' for the first runnable job") p.add_argument("--ops-repo", default=os.environ.get("PM_OPS_REPO"), required=not os.environ.get("PM_OPS_REPO")) p.add_argument("--hub", default=os.environ.get("PM_HUB", "hf"), help="'hf' or 'local: