From da1574a53f089fca3322128101ed4efa1634a4ff Mon Sep 17 00:00:00 2001 From: Professor Synapse <131487882+ProfSynapse@users.noreply.github.com> Date: Tue, 17 Nov 2026 06:31:31 -0500 Subject: [PATCH] fix(runpod): migrate one-shot pod lifecycle to REST v2 (#282) --- .../fine-tuning/reference/runpod-jobs.md | 82 ++++++++--- .../fine-tuning/scripts/runpod_run_job.py | 64 ++++---- .../fine-tuning/reference/runpod-jobs.md | 82 ++++++++--- .../fine-tuning/scripts/runpod_run_job.py | 64 ++++---- .skills/fine-tuning/reference/runpod-jobs.md | 82 ++++++++--- .skills/fine-tuning/scripts/runpod_run_job.py | 64 ++++---- tests/cloud/test_runpod_run_job.py | 137 ++++++++++++++++++ 7 files changed, 422 insertions(+), 153 deletions(-) create mode 100644 tests/cloud/test_runpod_run_job.py diff --git a/.agents/skills/fine-tuning/reference/runpod-jobs.md b/.agents/skills/fine-tuning/reference/runpod-jobs.md index ca377425c..1b18cb07f 100644 --- a/.agents/skills/fine-tuning/reference/runpod-jobs.md +++ b/.agents/skills/fine-tuning/reference/runpod-jobs.md @@ -12,12 +12,46 @@ This lane is for arbitrary wrapper jobs. Cloud TRAINING stays on the `reference/cloud-training.md`. The launcher (`scripts/runpod_run_job.py`) talks to the RunPod REST API -(`https://rest.runpod.io/v1`) for pod create/terminate and to the GraphQL API +(`https://api.runpod.io/v2`) for pod create/terminate and to the GraphQL API for runtime polling. It does NOT use the `runpod` Python SDK. This split was -forced by hard debugging (2026-07-05, 4 dead pods); see the gotchas below. +established by debugging (2026-07-05); the historical gotchas below describe +the v1 behavior. GraphQL uptime polling is retained in this migration. --- + +## REST v2 migration (issue #282) + +[RunPod's overview](https://docs.runpod.io/api-reference-v2/overview) states that +v1 is no longer available. This is a payload migration, not only a URL change: + +- [Create](https://docs.runpod.io/api-reference-v2/pods/create-a-pod): + `POST https://api.runpod.io/v2/pods`, Bearer auth, JSON body with `name`, + `image`, `gpu: {id, count, allowedCudaVersions?}`, `cloud`, `disk`, `env`, + `entrypoint` and `cmd`. The command is one element of `cmd`, preserving shell + quoting. `mounts.persistent: {size: 20, path: "/workspace"}` preserves v1's + default workspace volume (no network volume). A successful immediate create + returns HTTP 201 and a pod object with top-level `id`, `status`, and `cost`. + This launcher does not request queued deployment. +- [Terminate](https://docs.runpod.io/api-reference-v2/pods/terminate-a-pod): + `DELETE https://api.runpod.io/v2/pods/{id}`, no request body, HTTP 204 with no + response body. Cleanup uses this same endpoint on every exit path. +- [Migration guide](https://docs.runpod.io/api-reference-v2/migrate-from-v1): + no `minDownloadMbps` replacement; CUDA constraints move inside `gpu`. + Without `--no-entrypoint-override`, both `entrypoint` and `cmd` are explicit; + with that flag, both are omitted so image defaults apply. + +The training backend's dependency is `runpod>=1.7.0`, not an exact pin. +The 1.7.0 SDK pod create/get/terminate methods use GraphQL, as does the installed +1.12.0 SDK. No dependency change is required for the REST v1 shutdown. + +Live create → terminate validation remains an owner-run paid test: review a +`--dry-run` spec with a pinned commit and image, then run a single +`--probe-only --max-hosts 1` attempt with a short `--timeout-min`. Record the +created ID, confirm cleanup returns successfully, and verify that exact pod is +removed in the console/API. If interrupted or cleanup fails, use the sweep +command above immediately. Offline tests do not establish live GPU boot proof. + ## Requirements - `RUNPOD_API_KEY` in the environment (required; the script exits 2 without it). @@ -47,7 +81,7 @@ python3 scripts/runpod_run_job.py \ ``` Always validate with `--dry-run` first: it prints the resolved pod spec as JSON -(image digest, GPU, disk, env keys redacted, the full `dockerEntrypoint` chain) +(image digest, GPU, disk, env keys redacted, the full `entrypoint` chain) without any API call or cost. Key flags: @@ -59,9 +93,8 @@ Key flags: - `--cloud-type` -- `COMMUNITY` (default, cheaper) or `SECURE`. - `--env KEY=VALUE` -- extra pod env vars, repeatable. - `--timeout-min` -- hard wall-clock cap; the pod is terminated at timeout. -- `--min-download` -- minimum host download speed (Mbps, default 700). Community - hosts below this stall for tens of minutes pulling a large image; the boot - timeout then recycles onto a better host (see `--max-hosts`). +- `--min-download` -- deprecated compatibility flag; warns and is ignored. V2 + removed host bandwidth placement filters. The boot timeout still bounds pulls. - `--allowed-cuda "12.8,12.9,13.0"` -- CUDA versions the host driver must offer; a host whose driver is older than the image's CUDA fails container start silently. @@ -72,7 +105,7 @@ Key flags: - `--probe-only` -- skip clone+wrapper; boot the image, print `nvidia-smi`, and exit as soon as real container uptime is observed. Use this to isolate boot/image reliability from wrapper logic before spending on a real run. -- `--no-entrypoint-override` -- do not set `dockerEntrypoint`; let the image's +- `--no-entrypoint-override` -- do not set `entrypoint`; let the image's own ENTRYPOINT/CMD run (diagnostic: isolates whether the override itself prevents container start). @@ -82,10 +115,10 @@ Key flags: The script owns the full pod lifecycle: REST `POST /pods` -> wait for REAL container uptime -> poll every 30s -> exit on pod EXITED -> and ALWAYS -`DELETE /pods/{id}` in a `finally` block, with 3 retries. A wedged or timed-out -run cannot silently keep billing. If termination fails after retries, the -script prints the console URL (https://www.runpod.io/console/pods) for a manual -kill -- verify. +`DELETE /pods/{id}` in a `finally` block, with up to 3 attempts. If all termination attempts fail, the launcher raises +an error with the pod ID and manual cleanup URL, preventing further host +retries or a successful exit while a pod may still be billing. Process death +can still bypass cleanup; sweep manually and verify. Exit codes: 0 = wrapper finished (pod EXITED), 1 = pod failed / boot timeout / wall-clock timeout / all `--max-hosts` boot attempts exhausted, 2 = bad @@ -112,19 +145,19 @@ workdir instead: The braces matter: a bare `cd A || cd B && clone` parses as `cd A || (cd B && clone)` and SKIPS the clone whenever `cd A` succeeds. -### 2. dockerEntrypoint override (why REST, not the SDK) +### 2. entrypoint override (why REST, not the SDK) Images that ship an ENTRYPOINT (unsloth's `/usr/local/bin/entrypoint.sh`) receive GraphQL `dockerArgs` as *arguments to the entrypoint*, which can crash-loop the container forever with uptime pinned at 0 while it bills as -RUNNING. The REST `dockerEntrypoint` field REPLACES the ENTRYPOINT so the job +RUNNING. The REST `entrypoint` field REPLACES the ENTRYPOINT so the job command actually runs. The SDK also embeds `docker_args` into its GraphQL mutation with zero escaping, so any double quote corrupts the API call. REST takes a JSON body: no quoting restrictions. -### 3. REST has no uptime; poll GraphQL +### 3. Historical v1 uptime limitation; retained GraphQL polling -The REST pod object carries no uptime field (only `desiredStatus`, +The v1 REST pod object carried no uptime field (only `desiredStatus`, `lastStartedAt`), so an uptime check against REST reads every pod as never-booted forever (six healthy-or-not pods were killed at the boot timeout by exactly that bug). Actual container runtime lives only in the GraphQL @@ -134,11 +167,11 @@ User-Agent (Cloudflare), so the poller sends an explicit UA. ### 4. Fail-hold: "ran and failed" vs "never booted" -RunPod has no logs API (`runpod-python#400`). On nonzero exit the job command +The v1 launcher had no logs API (`runpod-python#400`). On nonzero exit the job command prints the code and holds the container alive for `FAIL_HOLD_S` (300s) before exiting nonzero, so the uptime poller can tell "ran and failed" (uptime climbs to ~300s then EXITED) apart from a boot crash-loop (uptime stuck at 1-2s). -Because there is no log API, a wrapper that wants diagnostics from a failed run +Although v2 provides log streaming, this launcher retains GraphQL polling; a wrapper that wants diagnostics from a failed run must upload them itself before it exits -- see "Failure telemetry" below. ### 5. hf_xet download hang (cross-provider, not RunPod-specific) @@ -168,8 +201,17 @@ container and re-runs the whole job from the top. The launcher's `DELETE /pods/{id}` in the `finally` block is the only thing that breaks this loop. So if the launcher PROCESS dies before that `finally` runs (session end, `TaskStop`, killed babysitter), the pod keeps re-running the job indefinitely -and billing the whole time. Sweep it manually: `DELETE /v1/pods/`, confirm -HTTP 204, then re-query until the pod reads null. Hardening option worth +and billing the whole time. Sweep only the pod ID owned by your attempt: + +```bash +curl --fail-with-body --request DELETE \ + --url "https://api.runpod.io/v2/pods/" \ + --header "Authorization: Bearer $RUNPOD_API_KEY" +``` + +Expect HTTP 204 with no body. Verify using `GET /v2/pods/` (404 after +removal) and the console; list responses are now `{"pods": [...]}` with +pagination, so a missing ID on the first page alone is not confirmation. Hardening option worth considering for long unattended jobs: have the wrapper self-terminate at job end by calling the REST delete with its own `RUNPOD_POD_ID` (injected into every pod) and the API key, so pod teardown does not depend on the launcher @@ -257,7 +299,7 @@ runs/modal// # Modal training runs ### Failure telemetry -Because RunPod has no log API, a failed wrapper leaves zero diagnostics unless +This launcher does not fetch v2 logs, so a failed wrapper leaves no retained diagnostics unless it uploads them itself. The recommended pattern (see the Epistemic-Humility AL wrapper for a worked example): capture the wrapper's own stdout+stderr to a file from the first line (`exec > >(tee logfile) 2>&1`), and on ANY nonzero exit diff --git a/.agents/skills/fine-tuning/scripts/runpod_run_job.py b/.agents/skills/fine-tuning/scripts/runpod_run_job.py index e00786f77..212093027 100644 --- a/.agents/skills/fine-tuning/scripts/runpod_run_job.py +++ b/.agents/skills/fine-tuning/scripts/runpod_run_job.py @@ -6,13 +6,13 @@ image, then terminate the pod. Generic by design -- the repo, commit, wrapper, and image are all arguments; nothing here is project-specific. -Uses the RunPod REST API (https://rest.runpod.io/v1) rather than the GraphQL +Uses the RunPod REST API (https://api.runpod.io/v2) rather than the GraphQL SDK, for two hard-won reasons (2026-07-05 lane debugging, 4 dead pods): - 1. dockerEntrypoint override. Images that ship an ENTRYPOINT (e.g. + 1. entrypoint override. Images that ship an ENTRYPOINT (e.g. unsloth/unsloth's /usr/local/bin/entrypoint.sh) receive GraphQL dockerArgs as *arguments to the entrypoint*, which can crash-loop the container forever with uptime pinned at 0 while the pod bills as - RUNNING. The REST field dockerEntrypoint replaces the ENTRYPOINT so the + RUNNING. The REST field entrypoint replaces the ENTRYPOINT so the job command actually runs. 2. The SDK embeds docker_args into its GraphQL mutation with zero escaping (dockerArgs: "{docker_args}"), so any double quote corrupts the API @@ -30,7 +30,7 @@ --repo-url https://github.com/org/repo.git --commit \ --wrapper path/inside/repo/job.sh --wrapper-args "--stage extract" \ [--gpu "NVIDIA GeForce RTX 3090"] [--image ] \ - [--min-download 700] [--allowed-cuda "12.8,12.9,13.0"] \ + [--allowed-cuda "12.8,12.9,13.0"] \ [--timeout-min 180] [--probe-only] [--dry-run] """ @@ -43,7 +43,7 @@ import urllib.error import urllib.request -API_BASE = "https://rest.runpod.io/v1" +API_BASE = "https://api.runpod.io/v2" # Default image matches the tuner's runpod training backend pin. DEFAULT_IMAGE = ( @@ -51,9 +51,8 @@ "@sha256:5266c57be21059bfb407d80dc2f448868a5c2e2dbe7b2aa27780f48b48cbec39" ) POLL_INTERVAL_S = 30 -# Covers image pull + container start on a host passing --min-download; -# a ~20GB image at 700 Mbps pulls in ~4-5 min, so 15 min is generous and -# anything slower means we picked a bad host and should recycle. +# Covers image pull + container start. REST v2 has no download-speed filter; +# stalled pulls remain bounded by this timeout. BOOT_TIMEOUT_S = 900 # How long a failed job holds the container alive before exiting nonzero, so # the uptime poller can distinguish "ran and failed" (uptime climbs to this @@ -72,9 +71,9 @@ def parse_args() -> argparse.Namespace: ap.add_argument("--image", default=DEFAULT_IMAGE, help="container image (pin by digest)") ap.add_argument("--gpu", default="NVIDIA GeForce RTX 4090", help="RunPod gpu_type_id") ap.add_argument("--cloud-type", default="COMMUNITY", choices=["COMMUNITY", "SECURE"]) - ap.add_argument("--min-download", type=int, default=700, - help="minimum host download speed in Mbps; community hosts " - "below this stall for tens of minutes pulling large images") + ap.add_argument("--min-download", type=int, default=None, + help="deprecated: REST v2 removed the download-speed filter; " + "accepted with a warning for existing callers") ap.add_argument("--allowed-cuda", default="", help="comma-separated CUDA versions the host must offer " "(e.g. '12.8,12.9,13.0'); a host whose driver is older " @@ -90,7 +89,7 @@ def parse_args() -> argparse.Namespace: help="skip clone+wrapper; just print GPU info and exit " "(boot-reliability isolation test)") ap.add_argument("--no-entrypoint-override", action="store_true", - help="do not set dockerEntrypoint; let the image's own " + help="do not set entrypoint; let the image's own " "ENTRYPOINT/CMD run (isolates whether the override " "itself prevents container start)") ap.add_argument("--max-hosts", type=int, default=3, @@ -104,7 +103,7 @@ def parse_args() -> argparse.Namespace: def build_job_command(args: argparse.Namespace) -> str: - """The shell command the container runs (via dockerEntrypoint bash -lc). + """The shell command the container runs (via entrypoint bash -lc). The command runs as the image's default container user, which is NOT necessarily root: the unsloth image runs as unsloth:runtimeusers with @@ -201,12 +200,10 @@ def api(method: str, path: str, api_key: str, body: dict | None = None) -> dict: def poll_pod(api_key: str, pod_id: str) -> dict: """Return {status, uptime} for a pod. - Create/terminate go through REST, but boot polling CANNOT: the REST pod - object carries no uptime field at all (only desiredStatus/lastStartedAt), - so an uptime check against REST reads every pod as never-booted forever - (2026-07-05: six healthy-or-not pods were killed at the boot timeout by - exactly that bug). Actual container runtime lives only in the GraphQL - pod.runtime.uptimeInSeconds. + Create/terminate use REST v2. Retain the established GraphQL uptime + polling: v1 REST exposed desiredStatus/lastStartedAt, not container + uptime (2026-07-05: checking it killed six pods at the boot timeout). + This migration does not change the runtime observation contract. """ query = ('query{pod(input:{podId:"%s"}){desiredStatus ' "runtime{uptimeInSeconds}}}" % pod_id) @@ -232,20 +229,21 @@ def poll_pod(api_key: str, pod_id: str) -> dict: def build_pod_spec(args: argparse.Namespace) -> dict: spec = { "name": args.run_tag, - "imageName": args.image, - "gpuTypeIds": [args.gpu], - "gpuCount": 1, - "cloudType": args.cloud_type, - "containerDiskInGb": args.disk_gb, - "minDownloadMbps": args.min_download, + "image": args.image, + "gpu": {"id": args.gpu, "count": 1}, + "cloud": args.cloud_type, + "disk": args.disk_gb, + # Preserve v1's default writable /workspace volume explicitly. + "mounts": {"persistent": {"size": 20, "path": "/workspace"}}, "env": build_pod_env(args), } if not args.no_entrypoint_override: # Full ENTRYPOINT replacement: the image's own entrypoint never runs. - spec["dockerEntrypoint"] = ["bash", "-lc", build_job_command(args)] + spec["entrypoint"] = ["bash", "-lc"] + spec["cmd"] = [build_job_command(args)] cuda = [v.strip() for v in args.allowed_cuda.split(",") if v.strip()] if cuda: - spec["allowedCudaVersions"] = cuda + spec["gpu"]["allowedCudaVersions"] = cuda return spec @@ -259,14 +257,18 @@ def terminate(api_key: str, pod_id: str) -> None: except Exception as e: # noqa: BLE001 print(f"[runpod] terminate attempt {attempt + 1} failed: {e}") time.sleep(10) - print( - f"[runpod] WARNING: could not terminate pod {pod_id}; " - "kill it manually at https://www.runpod.io/console/pods" + raise RuntimeError( + f"Could not terminate pod {pod_id}; stop here to avoid more billing. " + f"Manually DELETE {API_BASE}/pods/{pod_id} or use " + "https://www.runpod.io/console/pods" ) def main() -> int: args = parse_args() + if args.min_download is not None: + print("WARNING: --min-download is ignored: REST v2 removed host bandwidth filters", + file=sys.stderr) if len(args.commit) != 40: print(f"ERROR: --commit must be a full 40-char sha (got {len(args.commit)} chars)") @@ -307,7 +309,7 @@ def run_once(args: argparse.Namespace, api_key: str, attempt: int) -> int | str: if not pod_id: print(f"ERROR: create pod returned no id: {pod}") return 1 - print(f"[runpod] pod {pod_id} created (${pod.get('costPerHr', '?')}/hr, attempt {attempt})") + print(f"[runpod] pod {pod_id} created (${pod.get('cost', '?')}/hr, attempt {attempt})") print(f"[runpod] console: https://www.runpod.io/console/pods/{pod_id}") # Boot wait, then completion poll. EXITED == the job command finished diff --git a/.claude/skills/fine-tuning/reference/runpod-jobs.md b/.claude/skills/fine-tuning/reference/runpod-jobs.md index ca377425c..1b18cb07f 100644 --- a/.claude/skills/fine-tuning/reference/runpod-jobs.md +++ b/.claude/skills/fine-tuning/reference/runpod-jobs.md @@ -12,12 +12,46 @@ This lane is for arbitrary wrapper jobs. Cloud TRAINING stays on the `reference/cloud-training.md`. The launcher (`scripts/runpod_run_job.py`) talks to the RunPod REST API -(`https://rest.runpod.io/v1`) for pod create/terminate and to the GraphQL API +(`https://api.runpod.io/v2`) for pod create/terminate and to the GraphQL API for runtime polling. It does NOT use the `runpod` Python SDK. This split was -forced by hard debugging (2026-07-05, 4 dead pods); see the gotchas below. +established by debugging (2026-07-05); the historical gotchas below describe +the v1 behavior. GraphQL uptime polling is retained in this migration. --- + +## REST v2 migration (issue #282) + +[RunPod's overview](https://docs.runpod.io/api-reference-v2/overview) states that +v1 is no longer available. This is a payload migration, not only a URL change: + +- [Create](https://docs.runpod.io/api-reference-v2/pods/create-a-pod): + `POST https://api.runpod.io/v2/pods`, Bearer auth, JSON body with `name`, + `image`, `gpu: {id, count, allowedCudaVersions?}`, `cloud`, `disk`, `env`, + `entrypoint` and `cmd`. The command is one element of `cmd`, preserving shell + quoting. `mounts.persistent: {size: 20, path: "/workspace"}` preserves v1's + default workspace volume (no network volume). A successful immediate create + returns HTTP 201 and a pod object with top-level `id`, `status`, and `cost`. + This launcher does not request queued deployment. +- [Terminate](https://docs.runpod.io/api-reference-v2/pods/terminate-a-pod): + `DELETE https://api.runpod.io/v2/pods/{id}`, no request body, HTTP 204 with no + response body. Cleanup uses this same endpoint on every exit path. +- [Migration guide](https://docs.runpod.io/api-reference-v2/migrate-from-v1): + no `minDownloadMbps` replacement; CUDA constraints move inside `gpu`. + Without `--no-entrypoint-override`, both `entrypoint` and `cmd` are explicit; + with that flag, both are omitted so image defaults apply. + +The training backend's dependency is `runpod>=1.7.0`, not an exact pin. +The 1.7.0 SDK pod create/get/terminate methods use GraphQL, as does the installed +1.12.0 SDK. No dependency change is required for the REST v1 shutdown. + +Live create → terminate validation remains an owner-run paid test: review a +`--dry-run` spec with a pinned commit and image, then run a single +`--probe-only --max-hosts 1` attempt with a short `--timeout-min`. Record the +created ID, confirm cleanup returns successfully, and verify that exact pod is +removed in the console/API. If interrupted or cleanup fails, use the sweep +command above immediately. Offline tests do not establish live GPU boot proof. + ## Requirements - `RUNPOD_API_KEY` in the environment (required; the script exits 2 without it). @@ -47,7 +81,7 @@ python3 scripts/runpod_run_job.py \ ``` Always validate with `--dry-run` first: it prints the resolved pod spec as JSON -(image digest, GPU, disk, env keys redacted, the full `dockerEntrypoint` chain) +(image digest, GPU, disk, env keys redacted, the full `entrypoint` chain) without any API call or cost. Key flags: @@ -59,9 +93,8 @@ Key flags: - `--cloud-type` -- `COMMUNITY` (default, cheaper) or `SECURE`. - `--env KEY=VALUE` -- extra pod env vars, repeatable. - `--timeout-min` -- hard wall-clock cap; the pod is terminated at timeout. -- `--min-download` -- minimum host download speed (Mbps, default 700). Community - hosts below this stall for tens of minutes pulling a large image; the boot - timeout then recycles onto a better host (see `--max-hosts`). +- `--min-download` -- deprecated compatibility flag; warns and is ignored. V2 + removed host bandwidth placement filters. The boot timeout still bounds pulls. - `--allowed-cuda "12.8,12.9,13.0"` -- CUDA versions the host driver must offer; a host whose driver is older than the image's CUDA fails container start silently. @@ -72,7 +105,7 @@ Key flags: - `--probe-only` -- skip clone+wrapper; boot the image, print `nvidia-smi`, and exit as soon as real container uptime is observed. Use this to isolate boot/image reliability from wrapper logic before spending on a real run. -- `--no-entrypoint-override` -- do not set `dockerEntrypoint`; let the image's +- `--no-entrypoint-override` -- do not set `entrypoint`; let the image's own ENTRYPOINT/CMD run (diagnostic: isolates whether the override itself prevents container start). @@ -82,10 +115,10 @@ Key flags: The script owns the full pod lifecycle: REST `POST /pods` -> wait for REAL container uptime -> poll every 30s -> exit on pod EXITED -> and ALWAYS -`DELETE /pods/{id}` in a `finally` block, with 3 retries. A wedged or timed-out -run cannot silently keep billing. If termination fails after retries, the -script prints the console URL (https://www.runpod.io/console/pods) for a manual -kill -- verify. +`DELETE /pods/{id}` in a `finally` block, with up to 3 attempts. If all termination attempts fail, the launcher raises +an error with the pod ID and manual cleanup URL, preventing further host +retries or a successful exit while a pod may still be billing. Process death +can still bypass cleanup; sweep manually and verify. Exit codes: 0 = wrapper finished (pod EXITED), 1 = pod failed / boot timeout / wall-clock timeout / all `--max-hosts` boot attempts exhausted, 2 = bad @@ -112,19 +145,19 @@ workdir instead: The braces matter: a bare `cd A || cd B && clone` parses as `cd A || (cd B && clone)` and SKIPS the clone whenever `cd A` succeeds. -### 2. dockerEntrypoint override (why REST, not the SDK) +### 2. entrypoint override (why REST, not the SDK) Images that ship an ENTRYPOINT (unsloth's `/usr/local/bin/entrypoint.sh`) receive GraphQL `dockerArgs` as *arguments to the entrypoint*, which can crash-loop the container forever with uptime pinned at 0 while it bills as -RUNNING. The REST `dockerEntrypoint` field REPLACES the ENTRYPOINT so the job +RUNNING. The REST `entrypoint` field REPLACES the ENTRYPOINT so the job command actually runs. The SDK also embeds `docker_args` into its GraphQL mutation with zero escaping, so any double quote corrupts the API call. REST takes a JSON body: no quoting restrictions. -### 3. REST has no uptime; poll GraphQL +### 3. Historical v1 uptime limitation; retained GraphQL polling -The REST pod object carries no uptime field (only `desiredStatus`, +The v1 REST pod object carried no uptime field (only `desiredStatus`, `lastStartedAt`), so an uptime check against REST reads every pod as never-booted forever (six healthy-or-not pods were killed at the boot timeout by exactly that bug). Actual container runtime lives only in the GraphQL @@ -134,11 +167,11 @@ User-Agent (Cloudflare), so the poller sends an explicit UA. ### 4. Fail-hold: "ran and failed" vs "never booted" -RunPod has no logs API (`runpod-python#400`). On nonzero exit the job command +The v1 launcher had no logs API (`runpod-python#400`). On nonzero exit the job command prints the code and holds the container alive for `FAIL_HOLD_S` (300s) before exiting nonzero, so the uptime poller can tell "ran and failed" (uptime climbs to ~300s then EXITED) apart from a boot crash-loop (uptime stuck at 1-2s). -Because there is no log API, a wrapper that wants diagnostics from a failed run +Although v2 provides log streaming, this launcher retains GraphQL polling; a wrapper that wants diagnostics from a failed run must upload them itself before it exits -- see "Failure telemetry" below. ### 5. hf_xet download hang (cross-provider, not RunPod-specific) @@ -168,8 +201,17 @@ container and re-runs the whole job from the top. The launcher's `DELETE /pods/{id}` in the `finally` block is the only thing that breaks this loop. So if the launcher PROCESS dies before that `finally` runs (session end, `TaskStop`, killed babysitter), the pod keeps re-running the job indefinitely -and billing the whole time. Sweep it manually: `DELETE /v1/pods/`, confirm -HTTP 204, then re-query until the pod reads null. Hardening option worth +and billing the whole time. Sweep only the pod ID owned by your attempt: + +```bash +curl --fail-with-body --request DELETE \ + --url "https://api.runpod.io/v2/pods/" \ + --header "Authorization: Bearer $RUNPOD_API_KEY" +``` + +Expect HTTP 204 with no body. Verify using `GET /v2/pods/` (404 after +removal) and the console; list responses are now `{"pods": [...]}` with +pagination, so a missing ID on the first page alone is not confirmation. Hardening option worth considering for long unattended jobs: have the wrapper self-terminate at job end by calling the REST delete with its own `RUNPOD_POD_ID` (injected into every pod) and the API key, so pod teardown does not depend on the launcher @@ -257,7 +299,7 @@ runs/modal// # Modal training runs ### Failure telemetry -Because RunPod has no log API, a failed wrapper leaves zero diagnostics unless +This launcher does not fetch v2 logs, so a failed wrapper leaves no retained diagnostics unless it uploads them itself. The recommended pattern (see the Epistemic-Humility AL wrapper for a worked example): capture the wrapper's own stdout+stderr to a file from the first line (`exec > >(tee logfile) 2>&1`), and on ANY nonzero exit diff --git a/.claude/skills/fine-tuning/scripts/runpod_run_job.py b/.claude/skills/fine-tuning/scripts/runpod_run_job.py index e00786f77..212093027 100644 --- a/.claude/skills/fine-tuning/scripts/runpod_run_job.py +++ b/.claude/skills/fine-tuning/scripts/runpod_run_job.py @@ -6,13 +6,13 @@ image, then terminate the pod. Generic by design -- the repo, commit, wrapper, and image are all arguments; nothing here is project-specific. -Uses the RunPod REST API (https://rest.runpod.io/v1) rather than the GraphQL +Uses the RunPod REST API (https://api.runpod.io/v2) rather than the GraphQL SDK, for two hard-won reasons (2026-07-05 lane debugging, 4 dead pods): - 1. dockerEntrypoint override. Images that ship an ENTRYPOINT (e.g. + 1. entrypoint override. Images that ship an ENTRYPOINT (e.g. unsloth/unsloth's /usr/local/bin/entrypoint.sh) receive GraphQL dockerArgs as *arguments to the entrypoint*, which can crash-loop the container forever with uptime pinned at 0 while the pod bills as - RUNNING. The REST field dockerEntrypoint replaces the ENTRYPOINT so the + RUNNING. The REST field entrypoint replaces the ENTRYPOINT so the job command actually runs. 2. The SDK embeds docker_args into its GraphQL mutation with zero escaping (dockerArgs: "{docker_args}"), so any double quote corrupts the API @@ -30,7 +30,7 @@ --repo-url https://github.com/org/repo.git --commit \ --wrapper path/inside/repo/job.sh --wrapper-args "--stage extract" \ [--gpu "NVIDIA GeForce RTX 3090"] [--image ] \ - [--min-download 700] [--allowed-cuda "12.8,12.9,13.0"] \ + [--allowed-cuda "12.8,12.9,13.0"] \ [--timeout-min 180] [--probe-only] [--dry-run] """ @@ -43,7 +43,7 @@ import urllib.error import urllib.request -API_BASE = "https://rest.runpod.io/v1" +API_BASE = "https://api.runpod.io/v2" # Default image matches the tuner's runpod training backend pin. DEFAULT_IMAGE = ( @@ -51,9 +51,8 @@ "@sha256:5266c57be21059bfb407d80dc2f448868a5c2e2dbe7b2aa27780f48b48cbec39" ) POLL_INTERVAL_S = 30 -# Covers image pull + container start on a host passing --min-download; -# a ~20GB image at 700 Mbps pulls in ~4-5 min, so 15 min is generous and -# anything slower means we picked a bad host and should recycle. +# Covers image pull + container start. REST v2 has no download-speed filter; +# stalled pulls remain bounded by this timeout. BOOT_TIMEOUT_S = 900 # How long a failed job holds the container alive before exiting nonzero, so # the uptime poller can distinguish "ran and failed" (uptime climbs to this @@ -72,9 +71,9 @@ def parse_args() -> argparse.Namespace: ap.add_argument("--image", default=DEFAULT_IMAGE, help="container image (pin by digest)") ap.add_argument("--gpu", default="NVIDIA GeForce RTX 4090", help="RunPod gpu_type_id") ap.add_argument("--cloud-type", default="COMMUNITY", choices=["COMMUNITY", "SECURE"]) - ap.add_argument("--min-download", type=int, default=700, - help="minimum host download speed in Mbps; community hosts " - "below this stall for tens of minutes pulling large images") + ap.add_argument("--min-download", type=int, default=None, + help="deprecated: REST v2 removed the download-speed filter; " + "accepted with a warning for existing callers") ap.add_argument("--allowed-cuda", default="", help="comma-separated CUDA versions the host must offer " "(e.g. '12.8,12.9,13.0'); a host whose driver is older " @@ -90,7 +89,7 @@ def parse_args() -> argparse.Namespace: help="skip clone+wrapper; just print GPU info and exit " "(boot-reliability isolation test)") ap.add_argument("--no-entrypoint-override", action="store_true", - help="do not set dockerEntrypoint; let the image's own " + help="do not set entrypoint; let the image's own " "ENTRYPOINT/CMD run (isolates whether the override " "itself prevents container start)") ap.add_argument("--max-hosts", type=int, default=3, @@ -104,7 +103,7 @@ def parse_args() -> argparse.Namespace: def build_job_command(args: argparse.Namespace) -> str: - """The shell command the container runs (via dockerEntrypoint bash -lc). + """The shell command the container runs (via entrypoint bash -lc). The command runs as the image's default container user, which is NOT necessarily root: the unsloth image runs as unsloth:runtimeusers with @@ -201,12 +200,10 @@ def api(method: str, path: str, api_key: str, body: dict | None = None) -> dict: def poll_pod(api_key: str, pod_id: str) -> dict: """Return {status, uptime} for a pod. - Create/terminate go through REST, but boot polling CANNOT: the REST pod - object carries no uptime field at all (only desiredStatus/lastStartedAt), - so an uptime check against REST reads every pod as never-booted forever - (2026-07-05: six healthy-or-not pods were killed at the boot timeout by - exactly that bug). Actual container runtime lives only in the GraphQL - pod.runtime.uptimeInSeconds. + Create/terminate use REST v2. Retain the established GraphQL uptime + polling: v1 REST exposed desiredStatus/lastStartedAt, not container + uptime (2026-07-05: checking it killed six pods at the boot timeout). + This migration does not change the runtime observation contract. """ query = ('query{pod(input:{podId:"%s"}){desiredStatus ' "runtime{uptimeInSeconds}}}" % pod_id) @@ -232,20 +229,21 @@ def poll_pod(api_key: str, pod_id: str) -> dict: def build_pod_spec(args: argparse.Namespace) -> dict: spec = { "name": args.run_tag, - "imageName": args.image, - "gpuTypeIds": [args.gpu], - "gpuCount": 1, - "cloudType": args.cloud_type, - "containerDiskInGb": args.disk_gb, - "minDownloadMbps": args.min_download, + "image": args.image, + "gpu": {"id": args.gpu, "count": 1}, + "cloud": args.cloud_type, + "disk": args.disk_gb, + # Preserve v1's default writable /workspace volume explicitly. + "mounts": {"persistent": {"size": 20, "path": "/workspace"}}, "env": build_pod_env(args), } if not args.no_entrypoint_override: # Full ENTRYPOINT replacement: the image's own entrypoint never runs. - spec["dockerEntrypoint"] = ["bash", "-lc", build_job_command(args)] + spec["entrypoint"] = ["bash", "-lc"] + spec["cmd"] = [build_job_command(args)] cuda = [v.strip() for v in args.allowed_cuda.split(",") if v.strip()] if cuda: - spec["allowedCudaVersions"] = cuda + spec["gpu"]["allowedCudaVersions"] = cuda return spec @@ -259,14 +257,18 @@ def terminate(api_key: str, pod_id: str) -> None: except Exception as e: # noqa: BLE001 print(f"[runpod] terminate attempt {attempt + 1} failed: {e}") time.sleep(10) - print( - f"[runpod] WARNING: could not terminate pod {pod_id}; " - "kill it manually at https://www.runpod.io/console/pods" + raise RuntimeError( + f"Could not terminate pod {pod_id}; stop here to avoid more billing. " + f"Manually DELETE {API_BASE}/pods/{pod_id} or use " + "https://www.runpod.io/console/pods" ) def main() -> int: args = parse_args() + if args.min_download is not None: + print("WARNING: --min-download is ignored: REST v2 removed host bandwidth filters", + file=sys.stderr) if len(args.commit) != 40: print(f"ERROR: --commit must be a full 40-char sha (got {len(args.commit)} chars)") @@ -307,7 +309,7 @@ def run_once(args: argparse.Namespace, api_key: str, attempt: int) -> int | str: if not pod_id: print(f"ERROR: create pod returned no id: {pod}") return 1 - print(f"[runpod] pod {pod_id} created (${pod.get('costPerHr', '?')}/hr, attempt {attempt})") + print(f"[runpod] pod {pod_id} created (${pod.get('cost', '?')}/hr, attempt {attempt})") print(f"[runpod] console: https://www.runpod.io/console/pods/{pod_id}") # Boot wait, then completion poll. EXITED == the job command finished diff --git a/.skills/fine-tuning/reference/runpod-jobs.md b/.skills/fine-tuning/reference/runpod-jobs.md index ca377425c..1b18cb07f 100644 --- a/.skills/fine-tuning/reference/runpod-jobs.md +++ b/.skills/fine-tuning/reference/runpod-jobs.md @@ -12,12 +12,46 @@ This lane is for arbitrary wrapper jobs. Cloud TRAINING stays on the `reference/cloud-training.md`. The launcher (`scripts/runpod_run_job.py`) talks to the RunPod REST API -(`https://rest.runpod.io/v1`) for pod create/terminate and to the GraphQL API +(`https://api.runpod.io/v2`) for pod create/terminate and to the GraphQL API for runtime polling. It does NOT use the `runpod` Python SDK. This split was -forced by hard debugging (2026-07-05, 4 dead pods); see the gotchas below. +established by debugging (2026-07-05); the historical gotchas below describe +the v1 behavior. GraphQL uptime polling is retained in this migration. --- + +## REST v2 migration (issue #282) + +[RunPod's overview](https://docs.runpod.io/api-reference-v2/overview) states that +v1 is no longer available. This is a payload migration, not only a URL change: + +- [Create](https://docs.runpod.io/api-reference-v2/pods/create-a-pod): + `POST https://api.runpod.io/v2/pods`, Bearer auth, JSON body with `name`, + `image`, `gpu: {id, count, allowedCudaVersions?}`, `cloud`, `disk`, `env`, + `entrypoint` and `cmd`. The command is one element of `cmd`, preserving shell + quoting. `mounts.persistent: {size: 20, path: "/workspace"}` preserves v1's + default workspace volume (no network volume). A successful immediate create + returns HTTP 201 and a pod object with top-level `id`, `status`, and `cost`. + This launcher does not request queued deployment. +- [Terminate](https://docs.runpod.io/api-reference-v2/pods/terminate-a-pod): + `DELETE https://api.runpod.io/v2/pods/{id}`, no request body, HTTP 204 with no + response body. Cleanup uses this same endpoint on every exit path. +- [Migration guide](https://docs.runpod.io/api-reference-v2/migrate-from-v1): + no `minDownloadMbps` replacement; CUDA constraints move inside `gpu`. + Without `--no-entrypoint-override`, both `entrypoint` and `cmd` are explicit; + with that flag, both are omitted so image defaults apply. + +The training backend's dependency is `runpod>=1.7.0`, not an exact pin. +The 1.7.0 SDK pod create/get/terminate methods use GraphQL, as does the installed +1.12.0 SDK. No dependency change is required for the REST v1 shutdown. + +Live create → terminate validation remains an owner-run paid test: review a +`--dry-run` spec with a pinned commit and image, then run a single +`--probe-only --max-hosts 1` attempt with a short `--timeout-min`. Record the +created ID, confirm cleanup returns successfully, and verify that exact pod is +removed in the console/API. If interrupted or cleanup fails, use the sweep +command above immediately. Offline tests do not establish live GPU boot proof. + ## Requirements - `RUNPOD_API_KEY` in the environment (required; the script exits 2 without it). @@ -47,7 +81,7 @@ python3 scripts/runpod_run_job.py \ ``` Always validate with `--dry-run` first: it prints the resolved pod spec as JSON -(image digest, GPU, disk, env keys redacted, the full `dockerEntrypoint` chain) +(image digest, GPU, disk, env keys redacted, the full `entrypoint` chain) without any API call or cost. Key flags: @@ -59,9 +93,8 @@ Key flags: - `--cloud-type` -- `COMMUNITY` (default, cheaper) or `SECURE`. - `--env KEY=VALUE` -- extra pod env vars, repeatable. - `--timeout-min` -- hard wall-clock cap; the pod is terminated at timeout. -- `--min-download` -- minimum host download speed (Mbps, default 700). Community - hosts below this stall for tens of minutes pulling a large image; the boot - timeout then recycles onto a better host (see `--max-hosts`). +- `--min-download` -- deprecated compatibility flag; warns and is ignored. V2 + removed host bandwidth placement filters. The boot timeout still bounds pulls. - `--allowed-cuda "12.8,12.9,13.0"` -- CUDA versions the host driver must offer; a host whose driver is older than the image's CUDA fails container start silently. @@ -72,7 +105,7 @@ Key flags: - `--probe-only` -- skip clone+wrapper; boot the image, print `nvidia-smi`, and exit as soon as real container uptime is observed. Use this to isolate boot/image reliability from wrapper logic before spending on a real run. -- `--no-entrypoint-override` -- do not set `dockerEntrypoint`; let the image's +- `--no-entrypoint-override` -- do not set `entrypoint`; let the image's own ENTRYPOINT/CMD run (diagnostic: isolates whether the override itself prevents container start). @@ -82,10 +115,10 @@ Key flags: The script owns the full pod lifecycle: REST `POST /pods` -> wait for REAL container uptime -> poll every 30s -> exit on pod EXITED -> and ALWAYS -`DELETE /pods/{id}` in a `finally` block, with 3 retries. A wedged or timed-out -run cannot silently keep billing. If termination fails after retries, the -script prints the console URL (https://www.runpod.io/console/pods) for a manual -kill -- verify. +`DELETE /pods/{id}` in a `finally` block, with up to 3 attempts. If all termination attempts fail, the launcher raises +an error with the pod ID and manual cleanup URL, preventing further host +retries or a successful exit while a pod may still be billing. Process death +can still bypass cleanup; sweep manually and verify. Exit codes: 0 = wrapper finished (pod EXITED), 1 = pod failed / boot timeout / wall-clock timeout / all `--max-hosts` boot attempts exhausted, 2 = bad @@ -112,19 +145,19 @@ workdir instead: The braces matter: a bare `cd A || cd B && clone` parses as `cd A || (cd B && clone)` and SKIPS the clone whenever `cd A` succeeds. -### 2. dockerEntrypoint override (why REST, not the SDK) +### 2. entrypoint override (why REST, not the SDK) Images that ship an ENTRYPOINT (unsloth's `/usr/local/bin/entrypoint.sh`) receive GraphQL `dockerArgs` as *arguments to the entrypoint*, which can crash-loop the container forever with uptime pinned at 0 while it bills as -RUNNING. The REST `dockerEntrypoint` field REPLACES the ENTRYPOINT so the job +RUNNING. The REST `entrypoint` field REPLACES the ENTRYPOINT so the job command actually runs. The SDK also embeds `docker_args` into its GraphQL mutation with zero escaping, so any double quote corrupts the API call. REST takes a JSON body: no quoting restrictions. -### 3. REST has no uptime; poll GraphQL +### 3. Historical v1 uptime limitation; retained GraphQL polling -The REST pod object carries no uptime field (only `desiredStatus`, +The v1 REST pod object carried no uptime field (only `desiredStatus`, `lastStartedAt`), so an uptime check against REST reads every pod as never-booted forever (six healthy-or-not pods were killed at the boot timeout by exactly that bug). Actual container runtime lives only in the GraphQL @@ -134,11 +167,11 @@ User-Agent (Cloudflare), so the poller sends an explicit UA. ### 4. Fail-hold: "ran and failed" vs "never booted" -RunPod has no logs API (`runpod-python#400`). On nonzero exit the job command +The v1 launcher had no logs API (`runpod-python#400`). On nonzero exit the job command prints the code and holds the container alive for `FAIL_HOLD_S` (300s) before exiting nonzero, so the uptime poller can tell "ran and failed" (uptime climbs to ~300s then EXITED) apart from a boot crash-loop (uptime stuck at 1-2s). -Because there is no log API, a wrapper that wants diagnostics from a failed run +Although v2 provides log streaming, this launcher retains GraphQL polling; a wrapper that wants diagnostics from a failed run must upload them itself before it exits -- see "Failure telemetry" below. ### 5. hf_xet download hang (cross-provider, not RunPod-specific) @@ -168,8 +201,17 @@ container and re-runs the whole job from the top. The launcher's `DELETE /pods/{id}` in the `finally` block is the only thing that breaks this loop. So if the launcher PROCESS dies before that `finally` runs (session end, `TaskStop`, killed babysitter), the pod keeps re-running the job indefinitely -and billing the whole time. Sweep it manually: `DELETE /v1/pods/`, confirm -HTTP 204, then re-query until the pod reads null. Hardening option worth +and billing the whole time. Sweep only the pod ID owned by your attempt: + +```bash +curl --fail-with-body --request DELETE \ + --url "https://api.runpod.io/v2/pods/" \ + --header "Authorization: Bearer $RUNPOD_API_KEY" +``` + +Expect HTTP 204 with no body. Verify using `GET /v2/pods/` (404 after +removal) and the console; list responses are now `{"pods": [...]}` with +pagination, so a missing ID on the first page alone is not confirmation. Hardening option worth considering for long unattended jobs: have the wrapper self-terminate at job end by calling the REST delete with its own `RUNPOD_POD_ID` (injected into every pod) and the API key, so pod teardown does not depend on the launcher @@ -257,7 +299,7 @@ runs/modal// # Modal training runs ### Failure telemetry -Because RunPod has no log API, a failed wrapper leaves zero diagnostics unless +This launcher does not fetch v2 logs, so a failed wrapper leaves no retained diagnostics unless it uploads them itself. The recommended pattern (see the Epistemic-Humility AL wrapper for a worked example): capture the wrapper's own stdout+stderr to a file from the first line (`exec > >(tee logfile) 2>&1`), and on ANY nonzero exit diff --git a/.skills/fine-tuning/scripts/runpod_run_job.py b/.skills/fine-tuning/scripts/runpod_run_job.py index e00786f77..212093027 100644 --- a/.skills/fine-tuning/scripts/runpod_run_job.py +++ b/.skills/fine-tuning/scripts/runpod_run_job.py @@ -6,13 +6,13 @@ image, then terminate the pod. Generic by design -- the repo, commit, wrapper, and image are all arguments; nothing here is project-specific. -Uses the RunPod REST API (https://rest.runpod.io/v1) rather than the GraphQL +Uses the RunPod REST API (https://api.runpod.io/v2) rather than the GraphQL SDK, for two hard-won reasons (2026-07-05 lane debugging, 4 dead pods): - 1. dockerEntrypoint override. Images that ship an ENTRYPOINT (e.g. + 1. entrypoint override. Images that ship an ENTRYPOINT (e.g. unsloth/unsloth's /usr/local/bin/entrypoint.sh) receive GraphQL dockerArgs as *arguments to the entrypoint*, which can crash-loop the container forever with uptime pinned at 0 while the pod bills as - RUNNING. The REST field dockerEntrypoint replaces the ENTRYPOINT so the + RUNNING. The REST field entrypoint replaces the ENTRYPOINT so the job command actually runs. 2. The SDK embeds docker_args into its GraphQL mutation with zero escaping (dockerArgs: "{docker_args}"), so any double quote corrupts the API @@ -30,7 +30,7 @@ --repo-url https://github.com/org/repo.git --commit \ --wrapper path/inside/repo/job.sh --wrapper-args "--stage extract" \ [--gpu "NVIDIA GeForce RTX 3090"] [--image ] \ - [--min-download 700] [--allowed-cuda "12.8,12.9,13.0"] \ + [--allowed-cuda "12.8,12.9,13.0"] \ [--timeout-min 180] [--probe-only] [--dry-run] """ @@ -43,7 +43,7 @@ import urllib.error import urllib.request -API_BASE = "https://rest.runpod.io/v1" +API_BASE = "https://api.runpod.io/v2" # Default image matches the tuner's runpod training backend pin. DEFAULT_IMAGE = ( @@ -51,9 +51,8 @@ "@sha256:5266c57be21059bfb407d80dc2f448868a5c2e2dbe7b2aa27780f48b48cbec39" ) POLL_INTERVAL_S = 30 -# Covers image pull + container start on a host passing --min-download; -# a ~20GB image at 700 Mbps pulls in ~4-5 min, so 15 min is generous and -# anything slower means we picked a bad host and should recycle. +# Covers image pull + container start. REST v2 has no download-speed filter; +# stalled pulls remain bounded by this timeout. BOOT_TIMEOUT_S = 900 # How long a failed job holds the container alive before exiting nonzero, so # the uptime poller can distinguish "ran and failed" (uptime climbs to this @@ -72,9 +71,9 @@ def parse_args() -> argparse.Namespace: ap.add_argument("--image", default=DEFAULT_IMAGE, help="container image (pin by digest)") ap.add_argument("--gpu", default="NVIDIA GeForce RTX 4090", help="RunPod gpu_type_id") ap.add_argument("--cloud-type", default="COMMUNITY", choices=["COMMUNITY", "SECURE"]) - ap.add_argument("--min-download", type=int, default=700, - help="minimum host download speed in Mbps; community hosts " - "below this stall for tens of minutes pulling large images") + ap.add_argument("--min-download", type=int, default=None, + help="deprecated: REST v2 removed the download-speed filter; " + "accepted with a warning for existing callers") ap.add_argument("--allowed-cuda", default="", help="comma-separated CUDA versions the host must offer " "(e.g. '12.8,12.9,13.0'); a host whose driver is older " @@ -90,7 +89,7 @@ def parse_args() -> argparse.Namespace: help="skip clone+wrapper; just print GPU info and exit " "(boot-reliability isolation test)") ap.add_argument("--no-entrypoint-override", action="store_true", - help="do not set dockerEntrypoint; let the image's own " + help="do not set entrypoint; let the image's own " "ENTRYPOINT/CMD run (isolates whether the override " "itself prevents container start)") ap.add_argument("--max-hosts", type=int, default=3, @@ -104,7 +103,7 @@ def parse_args() -> argparse.Namespace: def build_job_command(args: argparse.Namespace) -> str: - """The shell command the container runs (via dockerEntrypoint bash -lc). + """The shell command the container runs (via entrypoint bash -lc). The command runs as the image's default container user, which is NOT necessarily root: the unsloth image runs as unsloth:runtimeusers with @@ -201,12 +200,10 @@ def api(method: str, path: str, api_key: str, body: dict | None = None) -> dict: def poll_pod(api_key: str, pod_id: str) -> dict: """Return {status, uptime} for a pod. - Create/terminate go through REST, but boot polling CANNOT: the REST pod - object carries no uptime field at all (only desiredStatus/lastStartedAt), - so an uptime check against REST reads every pod as never-booted forever - (2026-07-05: six healthy-or-not pods were killed at the boot timeout by - exactly that bug). Actual container runtime lives only in the GraphQL - pod.runtime.uptimeInSeconds. + Create/terminate use REST v2. Retain the established GraphQL uptime + polling: v1 REST exposed desiredStatus/lastStartedAt, not container + uptime (2026-07-05: checking it killed six pods at the boot timeout). + This migration does not change the runtime observation contract. """ query = ('query{pod(input:{podId:"%s"}){desiredStatus ' "runtime{uptimeInSeconds}}}" % pod_id) @@ -232,20 +229,21 @@ def poll_pod(api_key: str, pod_id: str) -> dict: def build_pod_spec(args: argparse.Namespace) -> dict: spec = { "name": args.run_tag, - "imageName": args.image, - "gpuTypeIds": [args.gpu], - "gpuCount": 1, - "cloudType": args.cloud_type, - "containerDiskInGb": args.disk_gb, - "minDownloadMbps": args.min_download, + "image": args.image, + "gpu": {"id": args.gpu, "count": 1}, + "cloud": args.cloud_type, + "disk": args.disk_gb, + # Preserve v1's default writable /workspace volume explicitly. + "mounts": {"persistent": {"size": 20, "path": "/workspace"}}, "env": build_pod_env(args), } if not args.no_entrypoint_override: # Full ENTRYPOINT replacement: the image's own entrypoint never runs. - spec["dockerEntrypoint"] = ["bash", "-lc", build_job_command(args)] + spec["entrypoint"] = ["bash", "-lc"] + spec["cmd"] = [build_job_command(args)] cuda = [v.strip() for v in args.allowed_cuda.split(",") if v.strip()] if cuda: - spec["allowedCudaVersions"] = cuda + spec["gpu"]["allowedCudaVersions"] = cuda return spec @@ -259,14 +257,18 @@ def terminate(api_key: str, pod_id: str) -> None: except Exception as e: # noqa: BLE001 print(f"[runpod] terminate attempt {attempt + 1} failed: {e}") time.sleep(10) - print( - f"[runpod] WARNING: could not terminate pod {pod_id}; " - "kill it manually at https://www.runpod.io/console/pods" + raise RuntimeError( + f"Could not terminate pod {pod_id}; stop here to avoid more billing. " + f"Manually DELETE {API_BASE}/pods/{pod_id} or use " + "https://www.runpod.io/console/pods" ) def main() -> int: args = parse_args() + if args.min_download is not None: + print("WARNING: --min-download is ignored: REST v2 removed host bandwidth filters", + file=sys.stderr) if len(args.commit) != 40: print(f"ERROR: --commit must be a full 40-char sha (got {len(args.commit)} chars)") @@ -307,7 +309,7 @@ def run_once(args: argparse.Namespace, api_key: str, attempt: int) -> int | str: if not pod_id: print(f"ERROR: create pod returned no id: {pod}") return 1 - print(f"[runpod] pod {pod_id} created (${pod.get('costPerHr', '?')}/hr, attempt {attempt})") + print(f"[runpod] pod {pod_id} created (${pod.get('cost', '?')}/hr, attempt {attempt})") print(f"[runpod] console: https://www.runpod.io/console/pods/{pod_id}") # Boot wait, then completion poll. EXITED == the job command finished diff --git a/tests/cloud/test_runpod_run_job.py b/tests/cloud/test_runpod_run_job.py new file mode 100644 index 000000000..7da0e5c02 --- /dev/null +++ b/tests/cloud/test_runpod_run_job.py @@ -0,0 +1,137 @@ +"""Offline REST v2 contract and billing cleanup tests for the skill launcher.""" +import importlib.util +import json +from pathlib import Path +import sys +from unittest.mock import MagicMock + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = Path('fine-tuning/scripts/runpod_run_job.py') + + +@pytest.fixture +def launcher(monkeypatch): + spec = importlib.util.spec_from_file_location('runpod_run_job', ROOT / '.skills' / SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + monkeypatch.setattr(module.time, 'sleep', lambda _: None) + monkeypatch.delenv('HF_TOKEN', raising=False) + return module + + +@pytest.fixture +def args(launcher, monkeypatch): + monkeypatch.setattr(sys, 'argv', ['runpod_run_job.py', '--run-tag', 'offline-test', + '--repo-url', 'https://github.com/test/repo.git', '--commit', 'a' * 40, + '--wrapper', 'job.sh']) + return launcher.parse_args() + + +def test_v2_create_spec(launcher, args): + args.allowed_cuda = '12.8, 12.9' + args.min_download = 700 # legacy callers must not send the removed field + spec = launcher.build_pod_spec(args) + assert spec == { + 'name': 'offline-test', 'image': args.image, + 'gpu': {'id': args.gpu, 'count': 1, 'allowedCudaVersions': ['12.8', '12.9']}, + 'cloud': 'COMMUNITY', 'disk': 60, + 'mounts': {'persistent': {'size': 20, 'path': '/workspace'}}, + 'env': {'RUN_TAG': 'offline-test', 'HF_HUB_DISABLE_XET': '1', + 'HF_HUB_ENABLE_HF_TRANSFER': '0'}, + 'entrypoint': ['bash', '-lc'], 'cmd': [launcher.build_job_command(args)], + } + + +def test_image_defaults_and_no_cuda(launcher, args): + args.no_entrypoint_override = True + spec = launcher.build_pod_spec(args) + assert 'entrypoint' not in spec and 'cmd' not in spec + assert spec['gpu'] == {'id': args.gpu, 'count': 1} + + +@pytest.mark.parametrize('method,path,body,response', [ + ('POST', '/pods', {'name': 'test', 'gpu': {'id': 'gpu', 'count': 1}}, + b'{"id":"pod-test","status":"PROVISIONING","cost":0.44}'), + ('DELETE', '/pods/pod-test', None, b''), +]) +def test_v2_http_contract(launcher, monkeypatch, method, path, body, response): + opened = MagicMock() + opened.return_value.__enter__.return_value.read.return_value = response + monkeypatch.setattr(launcher.urllib.request, 'urlopen', opened) + result = launcher.api(method, path, 'fake-key', body) + request = opened.call_args.args[0] + assert request.full_url == 'https://api.runpod.io/v2' + path + assert request.method == method + assert request.get_header('Authorization') == 'Bearer fake-key' + assert request.data == (json.dumps(body).encode() if body else None) + assert result == (json.loads(response) if response else {}) + + +@pytest.mark.parametrize('outcome', ['probe', 'exited', 'timeout', 'boot_fail', 'poll_exception']) +def test_cleanup_on_every_lifecycle_exit(launcher, args, monkeypatch, outcome): + calls = MagicMock(return_value={'id': 'pod-test', 'cost': 0.44}) + monkeypatch.setattr(launcher, 'api', calls) + poll = MagicMock(return_value={'status': 'EXITED', 'uptime': 1}) + monkeypatch.setattr(launcher, 'poll_pod', poll) + if outcome == 'probe': + args.probe_only = True + poll.return_value = {'status': 'RUNNING', 'uptime': 5} + elif outcome == 'timeout': + args.timeout_min = 0 + elif outcome == 'boot_fail': + poll.return_value = {'status': 'RUNNING', 'uptime': 0} + monkeypatch.setattr(launcher, 'BOOT_TIMEOUT_S', -1) + elif outcome == 'poll_exception': + poll.side_effect = KeyboardInterrupt + if outcome == 'poll_exception': + with pytest.raises(KeyboardInterrupt): + launcher.run_once(args, 'fake-key', 1) + else: + assert launcher.run_once(args, 'fake-key', 1) == { + 'probe': 0, 'exited': 0, 'timeout': 1, 'boot_fail': 'boot_fail'}[outcome] + assert calls.call_args_list[0].args == ('POST', '/pods', 'fake-key', launcher.build_pod_spec(args)) + assert calls.call_args_list[-1].args == ('DELETE', '/pods/pod-test', 'fake-key') + + +def test_cleanup_failure_prevents_next_host(launcher, args, monkeypatch): + calls = MagicMock(side_effect=[{'id': 'pod-test'}, RuntimeError('delete failed'), + RuntimeError('delete failed'), RuntimeError('delete failed')]) + monkeypatch.setattr(launcher, 'api', calls) + monkeypatch.setattr(launcher, 'parse_args', lambda: args) + monkeypatch.setenv('RUNPOD_API_KEY', 'fake-key') + monkeypatch.setattr(launcher, 'poll_pod', lambda *_: {'status': 'RUNNING', 'uptime': 0}) + monkeypatch.setattr(launcher, 'BOOT_TIMEOUT_S', -1) + with pytest.raises(RuntimeError, match='Could not terminate pod pod-test'): + launcher.main() + assert [c.args[0] for c in calls.call_args_list] == ['POST', 'DELETE', 'DELETE', 'DELETE'] + + +def test_termination_retries_transient_error(launcher, monkeypatch): + calls = MagicMock(side_effect=[RuntimeError('transient'), {}]) + monkeypatch.setattr(launcher, 'api', calls) + launcher.terminate('fake-key', 'pod-test') + assert calls.call_count == 2 + + +def test_legacy_download_flag_warns_and_dry_run_is_offline(launcher, args, monkeypatch, capsys): + args.min_download = 700 + args.dry_run = True + monkeypatch.setenv('HF_TOKEN', 'secret-fixture-token') + monkeypatch.setattr(launcher, 'parse_args', lambda: args) + opened = MagicMock(side_effect=AssertionError('must be offline')) + monkeypatch.setattr(launcher.urllib.request, 'urlopen', opened) + assert launcher.main() == 0 + output = capsys.readouterr() + assert '--min-download is ignored' in output.err + assert 'secret-fixture-token' not in output.out + assert json.loads(output.out)['env']['HF_TOKEN'] == '***' + opened.assert_not_called() + + +def test_skill_copies_identical(): + for relative in (SCRIPT, Path('fine-tuning/reference/runpod-jobs.md')): + canonical = (ROOT / '.skills' / relative).read_bytes() + for tree in ('.claude/skills', '.agents/skills'): + assert (ROOT / tree / relative).read_bytes() == canonical