diff --git a/.github/scripts/pip-audit.sh b/.github/scripts/pip-audit.sh new file mode 100755 index 0000000..4c9156a --- /dev/null +++ b/.github/scripts/pip-audit.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Dependency audit (A-40): install the package into a fresh venv the way CI does, freeze what got installed, and run +# pip-audit on exactly that set. Fails on any known vulnerability that is not in the allowlist (.pip-audit-ignore). +# +# .github/scripts/pip-audit.sh PIP_INSTALL_ARGS... e.g. .github/scripts/pip-audit.sh '.[test]' +# +# Allowlist format, one advisory per line (blank lines and lines starting with # are skipped): +# +# An entry past its review date fails the audit, so an accepted advisory is looked at again rather than forgotten. +# Env: PIP_AUDIT_IGNORE_FILE (default .pip-audit-ignore), PIP_AUDIT_VERSION (default 2.10.1). +set -euo pipefail +[ $# -gt 0 ] || { echo "usage: $0 PIP_INSTALL_ARGS..." >&2; exit 2; } +ignore_file="${PIP_AUDIT_IGNORE_FILE:-.pip-audit-ignore}" +tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT +py="${PYTHON:-python3}" + +# The allowlist: ids, with the review date enforced. +ignore_args=() +if [ -f "$ignore_file" ]; then + today="$(date -u +%F)"; expired=0 + while read -r id review reason; do + case "$id" in ''|'#'*) continue;; esac + [[ "$review" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || { echo "$ignore_file: $id has no review-by date (YYYY-MM-DD)" >&2; exit 2; } + [ -n "$reason" ] || { echo "$ignore_file: $id has no reason" >&2; exit 2; } + if [[ "$review" < "$today" ]]; then echo "::error::$ignore_file: $id was due for review on $review ($reason)"; expired=1; fi + echo "allowlisted: $id (review by $review): $reason" + ignore_args+=(--ignore-vuln "$id") + done < "$ignore_file" + [ "$expired" = 0 ] || exit 1 +fi + +# The audited set: what `pip install ARGS` puts into a clean venv (pip itself included), minus this project. +"$py" -m venv "$tmp/target" +"$tmp/target/bin/python" -m pip install --quiet --disable-pip-version-check --upgrade pip +"$tmp/target/bin/python" -m pip install --quiet --disable-pip-version-check "$@" +"$tmp/target/bin/python" -m pip freeze --all --exclude-editable | grep -v ' @ file://' > "$tmp/installed.txt" || true +echo "audited set ($(wc -l < "$tmp/installed.txt" | tr -d " ") packages, from: pip install $*):" +sed 's/^/ /' "$tmp/installed.txt" + +"$py" -m venv "$tmp/tool" +"$tmp/tool/bin/python" -m pip install --quiet --disable-pip-version-check "pip-audit==${PIP_AUDIT_VERSION:-2.10.1}" +"$tmp/tool/bin/pip-audit" --requirement "$tmp/installed.txt" --no-deps --disable-pip --progress-spinner off \ + --desc on ${ignore_args[@]+"${ignore_args[@]}"} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 69b32d1..dbb0b18 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,8 @@ permissions: jobs: test: - runs-on: ubuntu-latest + # ubuntu-latest (26.04) has no Python 3.9 build; 24.04 still has every version the SDK supports. + runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: @@ -27,3 +28,16 @@ jobs: python -m pip install --upgrade pip build twine python -m build python -m twine check --strict dist/* + + # A-40: the SDK has no runtime dependencies; the audited set is what CI installs to build and check it (pip, build, + # twine and their dependencies). Fails on any advisory not in .pip-audit-ignore. + audit: + name: pip-audit + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: .github/scripts/pip-audit.sh . build twine diff --git a/.github/workflows/dependency-audit.yml b/.github/workflows/dependency-audit.yml new file mode 100644 index 0000000..d62ccd9 --- /dev/null +++ b/.github/workflows/dependency-audit.yml @@ -0,0 +1,60 @@ +# Weekly dependency audit (A-40): the same pip-audit as CI, on a schedule, against today's advisory database and today's +# resolution of the declared ranges. On failure it opens one issue labelled "dependencies", or comments on the one that +# is already open; it never closes an issue (a person does, after the fix lands). +name: dependency-audit + +on: + schedule: + - cron: "17 6 * * 1" # Mondays 06:17 UTC + workflow_dispatch: + +permissions: + contents: read + +jobs: + audit: + name: pip-audit + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: pip-audit (gate) + id: gate + run: | + set -o pipefail + .github/scripts/pip-audit.sh . build twine 2>&1 | tee audit.log + - uses: actions/upload-artifact@v4 + if: always() + with: + name: audit-log + path: "*.log" + if-no-files-found: ignore + + report: + name: open or update the issue + needs: audit + if: failure() + runs-on: ubuntu-latest + permissions: + issues: write + steps: + - name: Open or update the "dependencies" issue + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -euo pipefail + title="Weekly dependency audit failed" + body="The scheduled pip-audit found a vulnerability that is not in .pip-audit-ignore (or an allowlist entry is past its review date). Run: $RUN_URL (the log is the run's audit-log artifact). Fix by raising the pin, or add the advisory to .pip-audit-ignore with a reason and a review date." + gh label create dependencies --repo "$REPO" --color 0366d6 --description "Pull requests that update a dependency file" 2>/dev/null || true + n=$(gh issue list --repo "$REPO" --state open --label dependencies --search "in:title \"$title\"" --json number --jq '.[0].number // empty') + if [ -n "$n" ]; then + gh issue comment "$n" --repo "$REPO" --body "Still failing on $(date -u +%F): $RUN_URL" + echo "commented on #$n" + else + gh issue create --repo "$REPO" --title "$title" --label dependencies --body "$body" + fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 644a30a..ad888f2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -65,7 +65,8 @@ jobs: test: name: test the wheel on ${{ matrix.python }} needs: build - runs-on: ubuntu-latest + # ubuntu-latest (26.04) has no Python 3.9 build; 24.04 still has every version the SDK supports. + runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: diff --git a/.pip-audit-ignore b/.pip-audit-ignore new file mode 100644 index 0000000..480f35e --- /dev/null +++ b/.pip-audit-ignore @@ -0,0 +1,2 @@ +# Accepted pip-audit advisories (A-40). One per line: +# An entry past its review date fails the audit. Empty: nothing is accepted today. diff --git a/CHANGELOG.md b/CHANGELOG.md index 5466c87..9363cfc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,76 @@ All notable changes to the `drums` Python SDK. The SDK talks to drumsd over its HTTP API; the drumsd version each SDK version was built against is noted where it matters. +## 0.4.0 - unreleased (proposed; not on PyPI) + +Post-D1 fixes for training clients (audit 2026-11-16), integrated in one release. Minor version: new API and one +behaviour change (429 replies are retried, with an off switch); nothing is removed and no dependency is added. Every +0.3 call keeps its signature and meaning. Built against drumsd 0.4.2 and the gateway routes of Drums-Labs/drums #41 +(trainer runs), #43 (desktop tokens), #46 (task-set tasks) and #49 (`GET /v1/limits`); against an older gateway each +feature falls back as described below. + +### Changed + +- **429 replies are retried on every call** (A-29, #11). A 429 (the gateway's per-key rate limit, or no capacity + right now: nothing was started) is retried for every method, step, screenshot, verify, create and fork included, + waiting at least the reply's `Retry-After` (seconds or an HTTP date), with jittered exponential backoff, for at + most 60 s of waiting per call (or 20 retries). `drums.RetryPolicy(max_wait_s, max_attempts, base_s, cap_s, jitter)` + via `connect(..., retry=...)`; `DRUMS_RETRY_MAX_WAIT_S` sets the budget and `0` restores the 0.3.0 behaviour + (raise at once). `drums mcp` waits at most 10 s. `Overloaded` carries `retry_after` and `retries`. A GET that gets + a 503 honours `Retry-After`; a POST that gets a 503 is still never retried. + +### Added + +- **Desktop tokens** (A-30, #14; design note "control plane out of the data path", 3.1). `drums.connect(url, key)` + keeps its signature. With a Drums API key (`drums_sk_...`) the client asks the gateway once how it authenticates + (`GET /auth`, no credential). When the gateway says `token` or `both`, the key is sent once to the console's + token URL (https, or loopback http; the same transport and redirect rules as every other request) and the gateway + only ever receives the short-lived desktop token. The token is renewed before it expires (the console's + `renew_after_s`, else 5 min before expiry) and once after a 401, then the call is sent again. The exchange and + every renewal use the client's `RetryPolicy` (a 429 waits for its `Retry-After`; in `token` mode, with no fallback, + a 5xx or a dropped connection is retried within the same budget) and the certifi fallback below. In `both` mode an + unreachable console falls back to the API key at once (and tries the exchange again after a minute); in `token` + mode it raises `DaemonUnavailable` naming the console, and a refused key raises `AuthError`. A key sent before the + gateway's mode was known (the discovery request got no answer) is retried once after a 401. A drumsd token, or a + gateway in `api_key` mode, works exactly as before. Neither the key nor the token appears in a repr + (`repr(client)` shows the auth kind only) or an error message. +- **macOS certificates** (A-07, #11). When the system store cannot verify the gateway or the console and `certifi` + is installed, the client switches to certifi's CA bundle once (for both) and prints one line naming the server; + without certifi it raises the new `CertificateError` (a `DaemonUnavailable`) with the fix + (`Install Certificates.command` or `pip install certifi`). No new dependency. +- **Run object** (A-36, #12, matching the gateway's trainer runs). `with client.run(name, kind="training", + task_set=..., config=..., desktops_provisioned=N) as run:` opens a run (`POST /v1/runs`), + `run.step(step, reward=, zero_advantage_share=, rollouts=, desktops_busy=, desktops_provisioned=)` buffers points + sent at most once per 30 s (`PATCH /v1/runs/{id}`), and the block's end closes it (`POST /v1/runs/{id}/close`: + completed, failed with the exception, cancelled on Ctrl-C). Kinds: `training`, `rl`, `evaluation`, `eval`. + Desktops created inside carry `X-Drums-Run-Label` (the label the open reply names, which differs from the name + when another running run holds it) and `X-Drums-Run-Id`. A 409 on a heartbeat or close means the run has ended on + the gateway (closed, or lost after 30 min without a heartbeat): the SDK stops sending for it with one warning + (`run.ended`). A `config` that is not a JSON object or is over 16 KiB as JSON is sent as its `config_hash` and a + `config_summary` (scalar top-level values), with one warning. A 400 on open warns with the gateway's message and + leaves `run.id` None; only a 404 or 405 means the routes are missing. On a gateway without these routes, or with a key that has neither `runs:write` nor + `computers:write`, it is a no-op with one warning (`strict=True` raises `RunNotSupported`). + `client.run()` alone still returns the run's record; `get_run` and `open_run` are the explicit names. +- **`drums preflight`** (#13). `drums preflight --desktops N --hours H [--model-gpus 2:6] [--task-set ID] [--json]` + and `drums.preflight(...)`: gateway and console health, key validity, expiry and scopes, host capacity and + admission, rate limit (N x 0.5 requests/s, the D1 rule, `REQUESTS_PER_DESKTOP_S`), live-desktop quota, spend cap at + the projected desktop-hour cost, and the task set's registration and validation. A pass/fail table with a fix and a + console link per row; exit 1 on a failure (`--strict`: also on a warning or a row it could not check). Works in + desktop-token mode: the exchange runs first, so a console that cannot issue a token is an auth failure (a `both` + gateway on the key alone is a warning), and the console row defaults to the token URL's origin. Rate limit, quota, + spend cap, price and host admission come from `GET /v1/limits` (scope `usage:read`, Drums-Labs/drums#49); a + gateway without it gets "not checked" on those rows. +- **MCP custom tasks** (A-08, A-09, #15). `create_computer` and `load_task` take `task_set_id` + `task_id` (a task of + a registered set) besides `task` and `task_id`; a task document sent as a JSON string is accepted; new tools + `list_task_sets` and `get_task_set` (36 tools, the gateway's tools.json); `verify` on a computer with no task says + so. Needs the gateway route `GET /v1/task-sets/{id}/tasks/{task_id}` (Drums-Labs/drums#46). + +### CI + +- A `pip-audit` job on what CI installs, with an allowlist whose entries expire, and a weekly audit that opens an + issue on failure (A-40, #10). +- The test matrix (3.9 to 3.13) runs on `ubuntu-24.04`: `ubuntu-latest` is 26.04, which has no Python 3.9 build. + ## 0.3.0 - 2026-11-12 The MCP server and the `drums` command. The hosted MCP endpoint on the gateway (`/mcp`) is live already; diff --git a/README.md b/README.md index 256a36b..b9dbc32 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,37 @@ Use a score only when `valid` is `True`. With the default `strict=True`, `verify for an invalid episode instead of returning a reward. A `401` raises `drums.AuthError`: the key is mistyped, revoked or expired. The full walkthrough is the [docs quickstart](https://docs.drums.run/quickstart). +## Preflight: can this run start? + +Before you pay for GPUs, check that the gateway, your key and your workspace can carry the run: + +```bash +drums preflight --desktops 128 --hours 3 --task-set [--model-gpus 2:6] [--json] +``` + +```python +report = drums.preflight(desktops=128, hours=3, task_set=task_set_id) +print(report.table()); assert report.ok +``` + +| Check | Passes when | +|---|---| +| gateway | `GET /v1/health` answers, in under 2 s (over 20 s fails: the control plane is overloaded) | +| console | the console answers (by default the console that issues desktop tokens, else `console.drums.run`) | +| auth | the key is accepted, not revoked, and does not expire before the run ends; on a gateway in desktop-token mode, the console issued a token for it (`both` mode on the key alone is a warning) | +| scopes | `computers:read` and `computers:write` (required; `computers:write` also opens runs); `usage:read` (warned: `GET /v1/limits` needs it) | +| host capacity, admission | the bound host has N free desktops, drumsd is ok, the host takes creates and no image checkpoint is stale | +| rate limit | the per-key limit is at least N x 0.5 requests/s with a burst of N (the D1 rule: about 0.5 requests per second per active desktop, `drums._preflight.REQUESTS_PER_DESKTOP_S`) | +| quota | the workspace's live-desktop limit leaves room for N | +| spend cap | spent + N x H x the desktop-hour price stays under the cap | +| task set | registered for the workspace and validated on a host (oracle accepted, none rejected) | + +Every row that is not a pass says how to fix it and links the console page (`--workspace ` or `DRUMS_WORKSPACE` +fills in the workspace). The exit status is 1 when a check failed, 0 otherwise; `--strict` also fails on a warning or +on a row that could not be checked. Rate limit, quota and spend cap come from the gateway's `GET /v1/limits` summary +(scope `usage:read`); a gateway that does not serve it yet says so on those rows ("not checked") instead of guessing, +and `--desktop-hour-usd` supplies the price for the cost projection. Preflight only reads; it creates nothing. + ## How it works ```mermaid @@ -115,8 +146,27 @@ save is *capture* and fork is *branch*. They are the same things. 30 minutes unused), so a crashed trainer does not hold a host. - **Validity.** Every episode starts with a gate report (isolation, mounts, network, limits, state hash, processes alive after resume). `Reward.valid` is `True` only when every gate passed and the computer was never quarantined. -- **Retries.** GET requests are retried while the server is unreachable (up to `retry_s`, default 60 s). POST and - DELETE are never retried: after a lost reply the outcome is unknown, so check `client.envs()` before trying again. +- **Retries.** GET requests are retried while the server is unreachable (up to `retry_s`, default 60 s). After a + lost reply to a POST or DELETE the outcome is unknown, so those are not retried; check `client.envs()` before + trying again. A 429 (the per-key rate limit, or no capacity right now) means nothing was started, so every call + (step, screenshot, verify, create, fork, ...) is retried, waiting at least the reply's `Retry-After` with jittered + backoff, for at most 60 s of waiting per call: `drums.RetryPolicy(max_wait_s=..., max_attempts=..., base_s=..., + cap_s=..., jitter=...)`, passed as `connect(..., retry=...)`. `RetryPolicy(max_wait_s=0)` or + `DRUMS_RETRY_MAX_WAIT_S=0` turns it off. `drums mcp` waits at most 10 s, so a chat turn does not hang. +- **Certificates.** python.org's macOS Python has no root certificates until you run `Install Certificates.command` + (in `/Applications/Python 3.x/`), so the first HTTPS call fails with `CERTIFICATE_VERIFY_FAILED` even though + `curl` works. When the system store cannot verify the server and `certifi` is installed (`pip install certifi`), + the client retries once with certifi's CA bundle and prints one line saying so; without certifi it raises + `CertificateError` with the same fix. The token exchange below shares the fallback. +- **Desktop tokens.** `drums.connect(url, key)` is unchanged. With a Drums API key (`drums_sk_...`) the client asks + the gateway once how it authenticates (`GET /auth`, no credential sent). When the gateway says `token` or + `both`, the key goes once to the console's token URL and the gateway only ever receives the short-lived desktop + token, so the data path does not need the control-plane database. The token is renewed before it expires and once + after a 401. The exchange uses the same retry policy (a 429 waits for its `Retry-After`; in `token` mode a 5xx or a + dropped connection is retried too) and the same HTTPS and redirect rules as every other call. In `both` mode a + console that does not answer falls back to the key; in `token` mode it raises `DaemonUnavailable` naming the + console. A plain `drumsd`, a drumsd token or a gateway in `api_key` mode work exactly as before. Neither the key + nor the token appears in a repr or an error. ## Computers @@ -203,17 +253,54 @@ page = client.runs(kind="scripted_test", status="completed", limit=20) for run in page["items"]: print(run["id"], run["status"], run.get("stop_reason")) -run = client.run(page["items"][0]["id"]) # status, counts and events of one run +run = client.get_run(page["items"][0]["id"]) # status, counts and events of one run (also client.run()) new = client.create_run(spec, idempotency_key="nightly-2026-11-13") # spec: the request the console shows ``` +### Your own training loop as a run + +A trainer that drives desktops itself (prime-rl, verifiers, your own loop) opens a run object, so the console shows +the run (task set, config hash, steps, reward, zero-advantage share, rollouts, desktops busy, cost) instead of a list +of anonymous computers: + +```python +with client.run("qwen27b-d2", kind="training", task_set=task_set_id, config=cfg, desktops_provisioned=128) as run: + for step in range(num_steps): + ... # your rollouts and optimizer step + run.step(step, reward=mean_reward, zero_advantage_share=zero_adv, rollouts=n, desktops_busy=busy) +``` + +- `kind` is `training` (or `rl`) or `evaluation` (or `eval`). `desktops_provisioned` is shown against + `desktops_busy` on the run page, so idle desktops are visible; `run.step()` takes its own `desktops_provisioned=` + too. + +- `run.step()` only records the point; the points are sent at most once per 30 s (`flush_s=`) and once more on close. +- The block's end closes the run: `completed`, `failed` with the exception's text if the block raised, `cancelled` + on Ctrl-C. A process that exits with the run still open closes it as `failed` (bounded to 10 s). +- Desktops created while the run is open carry its label (`X-Drums-Run-Label`, and `X-Drums-Run-Id`; fork children + inherit it), so the Computers page can filter them by run. The label is the run's name, or the one the gateway's + open reply names (`run.label`) when another running run already holds that name. +- `config` goes up as is when it is a JSON object of at most 16 KiB. Otherwise only its `config_hash` (sha256 of + its canonical JSON) and a `config_summary` (its scalar top-level values) are sent, with one warning. +- A 400 on open is the gateway refusing that body: one warning with the gateway's message, `run.id` stays None, and + training goes on (`strict=True` raises `BadRequest`). Only a 404 or 405 means the gateway has no run routes. +- A 409 on a heartbeat or on close means the run has ended on the gateway (closed elsewhere, or marked lost after + 30 min without a heartbeat). The SDK stops sending for it with one warning (`run.ended` says why); training goes on. +- On a gateway without the run routes (`POST /v1/runs` for training runs, `PATCH /v1/runs/{id}`, + `POST /v1/runs/{id}/close`), or with a key that has neither `runs:write` nor `computers:write`, the run is a no-op + with one warning and training goes on; `strict=True` raises `drums.RunNotSupported` instead. The labels still apply. + Runs, evaluations, API keys and the audit log exist on the Drums gateway only; against a plain `drumsd` these methods raise `drums.NotFound`. Concepts: [runs and evaluations](https://docs.drums.run/concepts/runs-and-evaluations). ## MCP -Drums publishes one MCP server with 34 tools: the workspace (computers, snapshots, tasks, runs, API keys, audit log) -and the desktop itself (GUI, screenshot, shell, files, verify, fork, reset). Two ways to reach it: +Drums publishes one MCP server with 36 tools: the workspace (computers, snapshots, tasks, task sets, runs, API keys, +audit log) and the desktop itself (GUI, screenshot, shell, files, verify, fork, reset). `create_computer` and +`load_task` take your own tasks too: `task` (a whole task document, as an object or a JSON string), `task_set_id` + +`task_id` (a task of a set registered in the console or with `POST /v1/task-sets`; `list_task_sets` and +`get_task_set` find them), or `task_id` alone (an OSWorld task). `verify` on a computer with no task says so. Two ways +to reach it: | Transport | Where it runs | Address | |---|---|---| @@ -322,8 +409,9 @@ reply), `message` and `body`. Errors about a computer carry its record and gate | `Conflict` | 409: the computer's state does not allow this operation | | `NotQuiescent` | 409: fork or save found no safe moment to capture; nothing was captured | | `CheckpointStale` | 409: the template's checkpoint predates this runtime; the installer must run again | -| `Overloaded` | 429: the host is near its memory limit; nothing was started, try again later | +| `Overloaded` | 429: rate limited, host full or near its memory limit; nothing was started. Raised after the retries ran out (`retry_after`, `retries`) | | `DaemonUnavailable` | the server did not answer; after a POST, call `env.refresh()` | +| `CertificateError` | the server's TLS certificate could not be verified (`hint` says how to fix it); a subclass of `DaemonUnavailable` | | `GuestError` | 502: the desktop's guest did not answer or refused the action | | `ActionFailed` | the action ran and exited non-zero (`returncode`, `output`, `error`) | | `EnvFailed` | a create, reset or fork child did not come up ready (`record`, `gates`, `cause`) | @@ -344,10 +432,11 @@ causes and fixes: [errors](https://docs.drums.run/reference/errors). | `DRUMS_TOKEN` | SDK, `drums mcp` | the API key (`drums_sk_...`); sent as `Authorization: Bearer` | | `DRUMS_TOKEN_FILE` | `drums mcp` | a file holding the token, read when `DRUMS_TOKEN` is unset; then `/etc/drums/token` | | `DRUMS_ALLOW_INSECURE_HTTP` | SDK, `drums mcp` | `1` sends the token over plain HTTP to a host that is not loopback | +| `DRUMS_RETRY_MAX_WAIT_S` | SDK, `drums mcp` | seconds a call may spend waiting out 429 replies (default 60; `drums mcp` 10); `0` turns the retries off | | `DRUMSD_URL` | SDK | older name for `DRUMS_URL`, read when `DRUMS_URL` is unset | `drums.connect(url, token, timeout=900, retry_s=60, check=True, close_on_exit=True, handle_signals=True, -allow_insecure_http=None)` takes the same values as arguments. In CI, store the key in the secret store and expose +allow_insecure_http=None, retry=None)` takes the same values as arguments. In CI, store the key in the secret store and expose it only as `DRUMS_TOKEN` to the job that needs it ([API keys guide](https://docs.drums.run/guides/api-keys)). ## Development @@ -371,6 +460,22 @@ python3 -m twine check --strict dist/* Please read [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request. +## Upgrading from 0.3 + +Nothing breaks: every 0.3 call keeps its signature and meaning, and no dependency is added. What changes when you +upgrade to 0.4.0: + +- **429 replies are retried** (up to 60 s of waiting per call, honouring `Retry-After`) instead of raising at once. + If your trainer has its own backoff around `Overloaded`, keep it or set `DRUMS_RETRY_MAX_WAIT_S=0` for the 0.3 + behaviour. +- **Desktop tokens** are used by themselves when the gateway asks for them; keep passing your API key as before. +- **New:** `client.run(name, kind="training", ...)` (your training loop as a run in the console), + `drums preflight` / `drums.preflight(...)`, `drums.RetryPolicy`, `drums.CertificateError`, `drums.RunNotSupported`, + and in `drums mcp` custom tasks by `task_set_id` + `task_id` plus `list_task_sets` and `get_task_set`. +- `client.run()` with nothing else still returns the run's record, as in 0.3. + +Details per change: [CHANGELOG.md](CHANGELOG.md). + ## Versioning and changelog Versions follow `MAJOR.MINOR.PATCH`. While the major version is 0, a minor release may change an interface and says diff --git a/drums/__init__.py b/drums/__init__.py index 35ee461..c6e4d30 100644 --- a/drums/__init__.py +++ b/drums/__init__.py @@ -18,8 +18,16 @@ cgroup limits, state hash, processes alive after resume, ...). An episode is valid only when every gate passed and the env was never quarantined (`Reward.valid`; the reasons are in `Reward.invalid_reasons`). `verify()` always carries the verdict; by default it raises InvalidEpisode instead of returning a reward from an invalid episode. -Retries: drumsd itself retries only failures that happened before any restored process ran; the SDK retries only GET -requests while drumsd is unreachable. Everything else is raised with the gate report. +Retries: drumsd itself retries only failures that happened before any restored process ran. The SDK retries GET +requests while drumsd is unreachable, and any request (step, screenshot, verify, create, ...) the server refused with +429 (rate limited, or no capacity right now: nothing was started), waiting at least the reply's Retry-After, with +jittered backoff, within `RetryPolicy.max_wait_s` (default 60 s; `retry=RetryPolicy(max_wait_s=0)` or +$DRUMS_RETRY_MAX_WAIT_S=0 turns it off). Everything else is raised with the gate report. + +TLS: when the system certificate store cannot verify the server (python.org's macOS Python ships without root +certificates until "Install Certificates.command" runs), the client retries the handshake once with certifi's CA +bundle if certifi is installed, and says so in one line on stderr; without certifi it raises CertificateError with +the fix. Cleanup: envs and saved states have leases on the server (default: reaped after 30 min unused; `idle_timeout=` and `ttl=` on create/fork/save change that, 0 = never), so a crashed trainer does not hold the host forever. The client @@ -30,10 +38,14 @@ import base64 import concurrent.futures as cf +import email.utils import ipaddress import json import os +import random +import ssl import struct +import sys import time import urllib.error import urllib.parse @@ -44,11 +56,13 @@ import threading import warnings -from .errors import (ActionFailed, AuthError, BadRequest, BatchError, CheckerError, CheckpointStale, Conflict, DaemonUnavailable, DrumsError, EnvFailed, # noqa: F401 +from .errors import (ActionFailed, AuthError, BadRequest, BatchError, CertificateError, CheckerError, CheckpointStale, Conflict, DaemonUnavailable, DrumsError, EnvFailed, # noqa: F401 EnvGone, ForkError, GateFailed, GuestError, InsecureTransport, InvalidEpisode, NotFound, NotQuiescent, Overloaded, RedirectRefused, RestoreFailed, TaskSetupFailed, TaskUnsupported) +from . import runs as _runs +from .runs import Run, RunNotSupported -__version__ = "0.3.0" +__version__ = "0.4.0" DEFAULT_URL = os.environ.get("DRUMS_URL") or os.environ.get("DRUMSD_URL") or "http://127.0.0.1:7070" DEFAULT_IMAGE = "osworld-ubuntu" @@ -57,6 +71,8 @@ "RestoreFailed", "GateFailed", "TaskSetupFailed", "ForkError", "BatchError", "InvalidEpisode", "CheckerError", "NotQuiescent", "Overloaded", "CheckpointStale", "TaskUnsupported", "InsecureTransport", "RedirectRefused", "check_transport"] +__all__ += ["Run", "RunNotSupported"] + _STATUS = {400: BadRequest, 401: AuthError, 404: NotFound, 409: Conflict, 410: EnvGone, 422: BadRequest, 429: Overloaded, 502: GuestError, 503: DaemonUnavailable} @@ -146,8 +162,264 @@ def redirect_request(self, req, fp, code, msg, headers, newurl): return super().redirect_request(req, fp, 307 if code == 308 else code, msg, headers, newurl) +class RetryPolicy: + """How a Client retries a request the server refused with 429: the gateway's per-key rate limit (`rate_limited`), + or no capacity right now (`overloaded`: host full, memory admission, too many creates in flight). A 429 means + nothing was started, so every method is retried, POSTs included (step, verify, create, fork, ...). + + Each wait is at least the reply's Retry-After (seconds or an HTTP date), else `base_s * 2**attempt`, capped at + `cap_s`, plus up to `jitter` (a fraction) of random extra so many desktops do not retry in lockstep. The client + gives up (raises the 429's error, e.g. Overloaded, with `.retry_after`) after `max_attempts` retries or when the + next wait would take the call past `max_wait_s` seconds of waiting. `max_wait_s=0` turns retries off (the 0.3.0 + behaviour). The default budget is 60 s, or $DRUMS_RETRY_MAX_WAIT_S when set.""" + + def __init__(self, max_wait_s: float = 60.0, max_attempts: int = 20, base_s: float = 0.5, cap_s: float = 30.0, + jitter: float = 0.25): + self.max_wait_s, self.max_attempts, self.base_s, self.cap_s, self.jitter = max_wait_s, max_attempts, base_s, cap_s, jitter + + @classmethod + def from_env(cls) -> "RetryPolicy": + v = os.environ.get("DRUMS_RETRY_MAX_WAIT_S", "").strip() + try: + return cls(max_wait_s=max(0.0, float(v))) if v else cls() + except ValueError: + return cls() + + def wait(self, attempt: int, retry_after: float | None) -> float: + """Seconds to wait before retry number `attempt` (0-based).""" + base = min(self.cap_s, self.base_s * (2 ** attempt)) + if retry_after is not None: + base = max(retry_after, min(base, retry_after + self.base_s)) # the server's number, not our backoff, leads + return base + random.uniform(0, self.jitter * max(base, self.base_s)) + + def __repr__(self): + return (f"RetryPolicy(max_wait_s={self.max_wait_s}, max_attempts={self.max_attempts}, base_s={self.base_s}, " + f"cap_s={self.cap_s}, jitter={self.jitter})") + + +__all__ += ["RetryPolicy", "CertificateError"] + + +def _retry_after(headers) -> float | None: + """A Retry-After header in seconds (delta-seconds or an HTTP date), None when absent or not understood.""" + v = headers.get("Retry-After") if headers is not None else None + if not v: + return None + v = v.strip() + try: + return max(0.0, float(v)) + except ValueError: + pass + try: + when = email.utils.parsedate_to_datetime(v) + except (TypeError, ValueError, IndexError): + return None + if when is None: + return None + return max(0.0, when.timestamp() - time.time()) + + +def _is_cert_failure(e: BaseException) -> bool: + reason = getattr(e, "reason", e) + return isinstance(reason, ssl.SSLCertVerificationError) or isinstance(e, ssl.SSLCertVerificationError) + + +def _certifi_context(): + """An SSL context with certifi's CA bundle, or None when certifi is not installed.""" + try: + import certifi # noqa: PLC0415 + except ImportError: + return None + return ssl.create_default_context(cafile=certifi.where()) + + +_CERT_HINT = ("python.org's macOS Python has no root certificates until you run \"Install Certificates.command\" " + "(in /Applications/Python 3.x/); or `pip install certifi` and the SDK uses it automatically") +API_KEY_PREFIX = "drums_sk_" +TOKEN_RENEW_BEFORE_S = 300.0 + + +class _Credentials: + """The credential the caller passed and, when the gateway advertises desktop tokens, the token exchanged for it. + + A Drums API key (`drums_sk_...`) given to a gateway in `token` or `both` mode (GET /auth) is sent once to + the console's token URL; the gateway then gets only the short-lived desktop token, renewed before it expires (at + the console's `renew_after_s`, else 5 min before `expires_in`) and once after a 401. Any other credential (a drumsd + token) is sent as it is and nothing is discovered. Neither value is ever part of a repr, a log line or an error + message: errors name the origin and the HTTP status only. + + The exchange (and every renewal) uses the client's transport: the certifi fallback when the system certificate + store cannot verify the console, and the client's RetryPolicy for a 429 (waiting at least its Retry-After). In + `token` mode, where there is no fallback, a 5xx or a dropped connection is retried within the same budget too; + asking for a token twice only mints a second token, so it is always safe to repeat.""" + + def __init__(self, key: str | None): + self._key = key + self._lock = threading.Lock() + self._mode = None if key and key.startswith(API_KEY_PREFIX) else "plain" + self._token_url = None + self._token = None + self._renew_at = 0.0 + self._expires_at = 0.0 + self._next_try = 0.0 # `both` mode with the console away: try the exchange again after this + self.last_error: str | None = None # why the last exchange failed (origin and status only), for preflight + + def __repr__(self): + return f"" + + __str__ = __repr__ + + @property + def kind(self) -> str: + if not self._key: + return "none" + if self._mode == "plain": + return "token" + if self._mode in ("token", "both"): + return "desktop token" if self._token else "api key (token exchange pending)" + return "api key" + + @property + def using_token(self) -> bool: + return self._token is not None + + @property + def mode(self) -> str | None: + """`plain` (a drumsd token), `api_key`, `token`, `both`, or None while the gateway's mode is not known yet.""" + return self._mode + + @property + def token_url(self) -> str | None: + return self._token_url + + @property + def undiscovered(self) -> bool: + """An API key whose gateway mode is not known yet (the discovery request did not get an answer).""" + return bool(self._key) and self._mode is None + + def invalidate(self): + with self._lock: + self._token, self._renew_at, self._expires_at = None, 0.0, 0.0 + + def bearer(self, client) -> str | None: + """The value for `Authorization: Bearer`, exchanging or renewing the desktop token when needed.""" + if not self._key: + return None + if self._mode == "plain": + return self._key + if self._mode is None: + self._discover(client) + if self._mode not in ("token", "both"): + return self._key + with self._lock: + now = time.time() + if self._token and now < self._renew_at: + return self._token + if not self._token and self._mode == "both" and now < self._next_try: + return self._key + # a renewal while the old token is still good, or `both` mode (the key still works), need not wait long + has_fallback = (self._token is not None and now < self._expires_at - 30) or self._mode == "both" + try: + self._exchange(client, now, patient=not has_fallback) + except (AuthError, InsecureTransport, RedirectRefused): + raise + except DrumsError as e: + self.last_error = e.message + # renewal failed while the old token is still valid: keep using it until it expires + if self._token and now < self._expires_at - 30: + return self._token + if self._mode == "both": # the gateway still takes the API key; retry the exchange in a minute + self._next_try = now + 60.0 + return self._key + raise + self.last_error = None + return self._token + + def _discover(self, client): + """GET /auth once (no credential). A definite answer is remembered; a network failure is not.""" + req = urllib.request.Request(client.url + "/auth", method="GET", headers={"Accept": "application/json"}) + try: + with client._opener.open(req, timeout=min(client.timeout, 15.0)) as r: + info = json.loads(r.read() or b"null") + except urllib.error.HTTPError as e: + e.close() + self._mode = "api_key" # drumsd, or a gateway without token support + return + except (RedirectRefused, urllib.error.URLError, ConnectionError, TimeoutError, OSError, ValueError) as e: + if _is_cert_failure(e) and client._use_certifi(): + return self._discover(client) # once: _use_certifi is False the second time + return # unknown for now; the request itself will report the transport problem + mode = info.get("auth_mode") if isinstance(info, dict) else None + url = info.get("token_url") if isinstance(info, dict) else None + if mode in ("token", "both") and isinstance(url, str) and url: + check_transport(url, self._key, client.allow_insecure_http) + self._mode, self._token_url = mode, url + else: + self._mode = "api_key" + + def _exchange(self, client, now: float, patient: bool = True): + """POST the key to the token URL. A 429 is retried under the client's RetryPolicy (at least its Retry-After); + with `patient` (token mode and no valid token: nothing else would work) a 5xx or a dropped connection is too. + A failed certificate check switches the client to certifi's bundle once, as for the gateway.""" + url = self._token_url + origin = _origin_text(url) + policy = client.retry + waited, attempt = 0.0, 0 + + def backoff(ra) -> bool: + nonlocal waited, attempt + if policy is None or attempt >= policy.max_attempts: + return False + w = policy.wait(attempt, ra) + if waited + w > policy.max_wait_s: + return False + attempt += 1 + waited += w + time.sleep(w) + return True + + while True: + opener = client._build_opener(self._key) + req = urllib.request.Request(url, data=b"", method="POST", + headers={"Authorization": f"Bearer {self._key}", "Accept": "application/json", "Content-Length": "0"}) + try: + with opener.open(req, timeout=min(client.timeout, 30.0)) as r: + body = json.loads(r.read() or b"null") + break + except urllib.error.HTTPError as e: + status = e.code + ra = _retry_after(e.headers) + e.close() + if status == 401: + raise AuthError(401, f"the console at {origin} refused the API key (missing, invalid, revoked or expired)") from None + if (status == 429 or (patient and status >= 500)) and backoff(ra): + continue + err = DaemonUnavailable(status, f"could not exchange the API key for a desktop token at {origin} (HTTP {status})") + err.retry_after = ra + raise err from None + except (urllib.error.URLError, ConnectionError, TimeoutError, OSError) as e: + if _is_cert_failure(e): + if client._use_certifi(origin): + continue + raise CertificateError(origin, str(getattr(e, "reason", e)), + "certifi's bundle could not verify it either" if client._certifi else _CERT_HINT) from None + if patient and backoff(None): + continue + raise DaemonUnavailable(0, f"could not exchange the API key for a desktop token at {origin}: {type(e).__name__}") from None + except ValueError: + raise DaemonUnavailable(0, f"the token reply from {origin} was not JSON") from None + tok = body.get("token") if isinstance(body, dict) else None + if not isinstance(tok, str) or not tok: + raise DaemonUnavailable(0, f"the token reply from {origin} had no token") + life = float(body.get("expires_in") or 3600) + renew_after = body.get("renew_after_s") + renew_after = float(renew_after) if isinstance(renew_after, (int, float)) else max(life - TOKEN_RENEW_BEFORE_S, life / 2) + self._token, self._renew_at, self._expires_at = tok, now + max(0.0, min(renew_after, life)), now + life + + def connect(url: str | None = None, token: str | None = None, *, timeout: float = 900.0, retry_s: float = 60.0, check: bool = True, - close_on_exit: bool = True, handle_signals: bool = True, allow_insecure_http: bool | None = None) -> "Client": + close_on_exit: bool = True, handle_signals: bool = True, allow_insecure_http: bool | None = None, + retry: "RetryPolicy | None" = None) -> "Client": """A client for one drumsd. `url`/`token` default to $DRUMS_URL / $DRUMS_TOKEN. With check=True the token is tried at once (AuthError / DaemonUnavailable here rather than on the first create). A token is only sent over https, or over plain http to localhost / 127.0.0.0/8 / ::1; any other http URL raises @@ -155,9 +427,10 @@ def connect(url: str | None = None, token: str | None = None, *, timeout: float close_on_exit=True: the envs this client created and did not close are closed when the process exits (atexit) or when the client is used as a context manager and the block ends. handle_signals=True: SIGTERM and SIGHUP exit through that cleanup too, when their handler is still the default one (never replaces a handler you installed; - main thread only). A `kill -9` cannot be caught: the server-side leases reap those envs.""" + main thread only). A `kill -9` cannot be caught: the server-side leases reap those envs. + retry: how 429 replies are retried on every call (RetryPolicy; default RetryPolicy.from_env()).""" c = Client(url or DEFAULT_URL, token if token is not None else os.environ.get("DRUMS_TOKEN"), timeout=timeout, retry_s=retry_s, - close_on_exit=close_on_exit, handle_signals=handle_signals, allow_insecure_http=allow_insecure_http) + close_on_exit=close_on_exit, handle_signals=handle_signals, allow_insecure_http=allow_insecure_http, retry=retry) if check: c.health() return c @@ -184,8 +457,10 @@ class Client: """A connection to one drumsd (use drums.connect). Creates envs, lists them, and reads health and metrics.""" def __init__(self, url: str = DEFAULT_URL, token: str | None = None, timeout: float = 900.0, retry_s: float = 60.0, - close_on_exit: bool = False, handle_signals: bool = False, allow_insecure_http: bool | None = None): + close_on_exit: bool = False, handle_signals: bool = False, allow_insecure_http: bool | None = None, + retry: RetryPolicy | None = None): self.url, self.timeout, self.retry_s = url.rstrip("/"), timeout, retry_s + self.retry = retry if retry is not None else RetryPolicy.from_env() self.token = token if token is not None else os.environ.get("DRUMS_TOKEN") check_transport(self.url, self.token, allow_insecure_http) # InsecureTransport: a token over plain http off-loopback if allow_insecure_http is None: @@ -193,14 +468,21 @@ def __init__(self, url: str = DEFAULT_URL, token: str | None = None, timeout: fl self.allow_insecure_http = bool(allow_insecure_http) # redirects: same origin only, MAX_REDIRECTS hops, check_transport on every hop (RedirectRefused otherwise) self._opener = urllib.request.build_opener(_RedirectPolicy(self.token, self.allow_insecure_http)) + self._certifi = False # True once the system store failed and certifi's bundle is in use + self._certifi_ctx = None + self._cred = _Credentials(self.token) # API key -> desktop token exchange when the gateway asks for it self._owned: dict[str, None] = {} # ids of envs this client created and has not closed (insertion order) self._owned_lock = threading.Lock() + self._runs: list = [] # open Run objects, innermost last: creates carry its label self.close_on_exit = close_on_exit if close_on_exit: atexit.register(self._close_at_exit) if handle_signals: _install_signal_exit() + def __repr__(self): + return f"" # never the key or the token + # cleanup ---------------------------------------------------------------------------------------------------------- def _own(self, env_id): if env_id: @@ -262,19 +544,50 @@ def __exit__(self, *exc): self.close() # transport -------------------------------------------------------------------------------------------------------- + def _use_certifi(self, origin: str | None = None) -> bool: + """Switch this client to certifi's CA bundle (once; the gateway and the token exchange share it). False when + certifi is missing or already in use. `origin` is the server whose certificate failed (default: the gateway).""" + if self._certifi: + return False + ctx = _certifi_context() + if ctx is None: + return False + self._certifi_ctx = ctx + self._opener = self._build_opener(self.token) + self._certifi = True + sys.stderr.write(f"drums: the system certificate store could not verify {origin or _origin_text(self.url)}; using certifi's CA bundle " + "(to fix Python's own store on macOS, run \"Install Certificates.command\")\n") + return True + + def _build_opener(self, token: str | None): + """An opener with the same-origin redirect policy for `token`, and certifi's bundle once the client uses it.""" + handlers = [_RedirectPolicy(token, self.allow_insecure_http)] + if self._certifi_ctx is not None: + handlers.append(urllib.request.HTTPSHandler(context=self._certifi_ctx)) + return urllib.request.build_opener(*handlers) + def call(self, method: str, path: str, body=None, raw: bool = False, timeout: float | None = None, headers: dict | None = None): """One request. GETs are retried while drumsd is unreachable (up to retry_s: a restarting drumsd comes back and - reconciles); other methods are never retried, since their outcome is unknown after a dropped connection. + reconciles); other methods are not retried after a dropped connection, since their outcome is unknown. + A 429 (rate limited, or no capacity right now: nothing was started) is retried for every method by + `self.retry` (RetryPolicy), waiting at least the reply's Retry-After. A failed TLS certificate check is + retried once with certifi's CA bundle when certifi is installed (the handshake failed before anything was + sent), else raises CertificateError with the fix. `headers` are added to the request (e.g. Idempotency-Key). A redirect is followed only to the same origin (scheme, host, port), at most MAX_REDIRECTS hops; any other redirect raises RedirectRefused unfollowed.""" data = None if body is None else json.dumps(body).encode() headers = {"Content-Type": "application/json", **(headers or {})} - if self.token: - headers["Authorization"] = f"Bearer {self.token}" deadline = time.monotonic() + (self.retry_s if method == "GET" else 0.0) delay = 0.25 + policy = self.retry + waited_429, attempt_429 = 0.0, 0 + renewed = False while True: + bearer = self._cred.bearer(self) + if bearer: + headers["Authorization"] = f"Bearer {bearer}" req = urllib.request.Request(self.url + path, data=data, method=method, headers=headers) + pause = delay try: with self._opener.open(req, timeout=timeout or self.timeout) as r: b = r.read() @@ -286,8 +599,23 @@ def call(self, method: str, path: str, body=None, raw: bool = False, timeout: fl msg = body_j.get("error", text) if isinstance(body_j, dict) else text except ValueError: body_j, msg = None, text + ra = _retry_after(e.headers) + if e.code == 429 and policy is not None and attempt_429 < policy.max_attempts: + w = policy.wait(attempt_429, ra) + if waited_429 + w <= policy.max_wait_s: + attempt_429 += 1 + waited_429 += w + time.sleep(w) + continue + if e.code == 401 and (self._cred.using_token or self._cred.undiscovered) and not renewed: + # the token expired, was revoked or its signing key rotated, or the key went out before the + # gateway's auth mode was known (a token-mode gateway refuses keys): discover and exchange once + # more (a 401 is refused before anything ran, so even a POST is safe to send again) + renewed = True + self._cred.invalidate() + continue if e.code == 503 and time.monotonic() < deadline: - pass + pause = max(delay, min(ra, max(0.0, deadline - time.monotonic()))) if ra is not None else delay else: cls = _STATUS.get(e.code, DrumsError) if e.code == 409 and isinstance(body_j, dict) and body_j.get("code") == "not_quiescent": @@ -298,12 +626,21 @@ def call(self, method: str, path: str, body=None, raw: bool = False, timeout: fl cls = TaskUnsupported if e.code == 409 and "slot is destroyed" in str(msg): # drumsd < 0.4.2 cls = EnvGone - raise cls(e.code, msg, body_j) from None + err = cls(e.code, msg, body_j) + err.retry_after = ra + if e.code == 429: + err.retries = attempt_429 + raise err from None except (urllib.error.URLError, ConnectionError, TimeoutError, OSError) as e: + if _is_cert_failure(e): + if self._use_certifi(): + continue + raise CertificateError(_origin_text(self.url), str(getattr(e, "reason", e)), + "certifi's bundle could not verify it either" if self._certifi else _CERT_HINT) from None if time.monotonic() >= deadline: what = "the outcome is unknown; call env.refresh()" if method != "GET" else f"retried for {self.retry_s:.0f} s" raise DaemonUnavailable(0, f"drumsd at {self.url} unreachable on {method} {path} ({what}): {getattr(e, 'reason', e)}") from None - time.sleep(delay) + time.sleep(pause) delay = min(delay * 2, 2.0) # daemon ----------------------------------------------------------------------------------------------------------- @@ -376,10 +713,43 @@ def create_run(self, spec: dict, idempotency_key: str | None = None) -> dict: headers = {"Idempotency-Key": idempotency_key} if idempotency_key else None return self.call("POST", "/v1/runs", spec, headers=headers) - def run(self, run_id: str) -> dict: + def get_run(self, run_id: str) -> dict: """One run (GET /v1/runs/{id}): its row, the attempts summary and the last events.""" return self.call("GET", f"/v1/runs/{urllib.parse.quote(str(run_id))}") + def open_run(self, name: str, kind: str = "training", *, task_set=None, config=None, flush_s: float = 30.0, + strict: bool = False, label: str | None = None, desktops_provisioned: int | None = None) -> "Run": + """A Run (drums.runs.Run): `with client.open_run(name, kind="training", task_set=..., config=...) as run:` opens + it on the gateway, `run.step(step, reward=..., zero_advantage_share=..., rollouts=..., desktops_busy=...)` + records a point (sent at most once per `flush_s` s), and the block's end closes it (failed when the block + raised). Desktops created while it is open carry its label (the one the gateway's open reply names). + `desktops_provisioned` is sent on open (and step() takes its own). On a gateway without run routes it is a + no-op with one warning (strict=True raises instead); a 409 on a heartbeat or close means the run ended on + the gateway, and the SDK stops sending for it.""" + return Run(self, name, kind, task_set=task_set, config=config, flush_s=flush_s, strict=strict, label=label, + desktops_provisioned=desktops_provisioned) + + def run(self, name_or_id: str, kind: str | None = None, **kw): + """`client.run(name, kind="training", task_set=..., config=...)` -> a Run to use as a context manager + (see open_run). `client.run(run_id)` with a run UUID and nothing else is the 0.3 call: the run's record + (GET /v1/runs/{id}, also `get_run`).""" + if kind is None and not kw and _runs.is_uuid(name_or_id): + return self.get_run(name_or_id) + return self.open_run(name_or_id, kind or "training", **kw) + + def _push_run(self, run): + self._runs.append(run) + + def _pop_run(self, run): + try: + self._runs.remove(run) + except ValueError: + pass + + def _run_headers(self) -> dict | None: + runs = self._runs + return runs[-1].headers() if runs else None + def api_keys(self) -> dict: """The workspace's API keys, metadata only (GET /v1/api-keys): {"items": [{id, name, prefix, scopes, ...}]}.""" return self.call("GET", "/v1/api-keys") @@ -428,7 +798,7 @@ def create(self, image: str = DEFAULT_IMAGE, task=None, *, from_state=None, setu body["idle_timeout_s"] = idle_timeout if ttl is not None: body["ttl_s"] = ttl - e = Env(self, self.call("POST", "/v1/slots", body)) + e = Env(self, self.call("POST", "/v1/slots", body, headers=self._run_headers())) self._own(e.record.get("id")) e._check_up() return e @@ -878,3 +1248,8 @@ def env(task: dict | None = None, *, from_state: str | None = None, checkpoint: e = Env(c, rec) e._check_up() return e + + +from ._preflight import PreflightReport, preflight # noqa: E402 (needs Client defined above) + +__all__ += ["preflight", "PreflightReport"] diff --git a/drums/_preflight.py b/drums/_preflight.py new file mode 100644 index 0000000..d6ff4ac --- /dev/null +++ b/drums/_preflight.py @@ -0,0 +1,585 @@ +"""`drums preflight` / `drums.preflight(...)`: before any GPU is paid for, check that the gateway, the key and the +workspace can carry N desktops for H hours. Every block of the D1 run (rate limit, spend cap, live-desktop quota, +host capacity, control-plane health, a task set nobody had validated) would have shown up here. + + drums preflight --desktops 128 --hours 3 --task-set 0b5c2a52-... [--model-gpus 2:6] [--json] + + report = drums.preflight(desktops=128, hours=3, task_set="0b5c2a52-...") + if not report.ok: + print(report.table()) + +What is checked, and where the numbers come from (only reads; nothing is created): + + gateway GET /v1/health answers, how fast (control-plane health; the gateway reads the database to answer) + console the console URL answers (sign-in page) + auth the key is accepted, not revoked, and does not expire during the run (GET /v1/api-keys, by prefix); + on a gateway in desktop-token mode (GET /auth says token or both), the key is exchanged at the + console first, so a console that cannot issue a token shows up here, not as a gateway failure + scopes computers:read + computers:write (required; computers:write also opens runs); usage:read wanted + host capacity free desktops on the bound host >= N (GET /v1/health `capacity`), and the host takes creates + (drumsd ok, no stale image checkpoint) + rate limit the per-key limit vs N x REQUESTS_PER_DESKTOP_S, and its burst vs N x BURST_PER_DESKTOP + quota the workspace's live-desktop limit, minus what is live now, >= N + spend cap spent this period + N x H x the desktop-hour price <= the cap + task set (with --task-set) registered for this workspace, and validated (oracle accepted, none rejected) + +The rate limit, quota, spend cap and price come from `GET /v1/limits` (scope usage:read; Drums-Labs/drums#49, shape +in `_limits_view`). On a gateway that does not serve it yet, those rows say "not checked" and why, and +`--desktop-hour-usd` supplies the price for the projection. A row that could not be checked never fails the +preflight; `--strict` does. +""" +from __future__ import annotations + +import json +import os +import re +import time +import urllib.error +import urllib.parse +import urllib.request + +from .errors import AuthError, DrumsError, NotFound + +#: D1 rule of thumb (2026-11-16, 128 desktops on Qwen3.5-27B): each ACTIVE desktop costs about one action and one +#: screenshot per turn every few seconds through the gateway, about 0.5 requests per second (128 desktops needed about +#: 60 req/s). A run of N desktops needs a per-key rate of at least N x this. +REQUESTS_PER_DESKTOP_S = 0.5 +#: A run's start: every desktop is created and takes its first screenshot within a few seconds, so the burst +#: (bucket size) should hold about one request per desktop. +BURST_PER_DESKTOP = 1.0 +#: The gateway's default per-key limit (RATE_LIMIT_PER_S / RATE_LIMIT_BURST unset): a pilot setting. +DEFAULT_RATE_PER_S, DEFAULT_RATE_BURST = 20, 60 +REQUIRED_SCOPES = ("computers:read", "computers:write") +#: runs:write is not wanted: the gateway opens trainer runs with computers:write too (Drums-Labs/drums#41) +WANTED_SCOPES = {"usage:read": "usage and cost reads (and GET /v1/limits, so the quota and spend rows) are refused"} +#: /v1/health slower than this is a warning, ten times slower a failure (the 2026-11-16 outage answered in 10 to 90 s) +HEALTH_SLOW_S = 2.0 +DEFAULT_CONSOLE_URL = "https://console.drums.run" + +PASS, FAIL, WARN, SKIP, INFO = "pass", "fail", "warn", "not checked", "info" +_KEY = re.compile(r"^drums_sk_([a-z2-7]{12})_") +_UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I) + + +class Check: + """One row: `name`, `status` (pass, fail, warn, not checked, info), `detail`, and for anything but a pass the + `fix` and a console `link`.""" + + def __init__(self, name: str, status: str, detail: str, fix: str | None = None, link: str | None = None): + self.name, self.status, self.detail, self.fix, self.link = name, status, detail, fix, link + + def to_dict(self) -> dict: + return {"name": self.name, "status": self.status, "detail": self.detail, "fix": self.fix, "link": self.link} + + def __repr__(self): + return f"" + + +class PreflightReport: + """The checks, in order. `ok` is False when any check failed; `exit_code(strict)` is what `drums preflight` + returns (1 on a failure; with strict also on a warning or a row that could not be checked).""" + + def __init__(self, desktops: int, hours: float, checks: list, need: dict): + self.desktops, self.hours, self.checks, self.need = desktops, hours, checks, need + + @property + def ok(self) -> bool: + return not any(c.status == FAIL for c in self.checks) + + def exit_code(self, strict: bool = False) -> int: + if not self.ok: + return 1 + if strict and any(c.status in (WARN, SKIP) for c in self.checks): + return 1 + return 0 + + def to_dict(self) -> dict: + return {"ok": self.ok, "desktops": self.desktops, "hours": self.hours, "need": self.need, + "checks": [c.to_dict() for c in self.checks]} + + def table(self) -> str: + w = max(len(c.name) for c in self.checks) if self.checks else 5 + lines = [f"drums preflight: {self.desktops} desktops for {self.hours:g} h", "", + f"{'CHECK'.ljust(w)} {'RESULT'.ljust(11)} DETAIL"] + for c in self.checks: + lines.append(f"{c.name.ljust(w)} {c.status.upper().ljust(11)} {c.detail}") + todo = [c for c in self.checks if c.status in (FAIL, WARN, SKIP) and (c.fix or c.link)] + if todo: + lines += ["", "To do:"] + for c in todo: + lines.append(f" [{c.status}] {c.name}: {c.fix or ''}{(' ' + c.link) if c.link else ''}") + n_fail = sum(c.status == FAIL for c in self.checks) + n_skip = sum(c.status == SKIP for c in self.checks) + lines += ["", ("PASS" if self.ok else f"FAIL ({n_fail} check{'s' if n_fail != 1 else ''} failed)") + + (f"; {n_skip} could not be checked" if n_skip else "")] + return "\n".join(lines) + "\n" + + +def parse_model_gpus(v) -> dict | None: + """'8' (total), '2:6' or '2,6' (inference:trainer) -> {"inference", "trainer", "total"}; None for None.""" + if v is None or v == "": + return None + if isinstance(v, int): + return {"inference": None, "trainer": None, "total": v} + parts = [p for p in re.split(r"[:,]", str(v).strip()) if p != ""] + try: + nums = [int(p) for p in parts] + except ValueError: + raise ValueError(f"--model-gpus takes a GPU count (8) or inference:trainer (2:6); got {v!r}") from None + if not nums or any(n < 0 for n in nums) or len(nums) > 2: + raise ValueError(f"--model-gpus takes a GPU count (8) or inference:trainer (2:6); got {v!r}") + if len(nums) == 1: + return {"inference": None, "trainer": None, "total": nums[0]} + return {"inference": nums[0], "trainer": nums[1], "total": nums[0] + nums[1]} + + +def _num(d, *keys): + for k in keys: + v = d.get(k) if isinstance(d, dict) else None + if isinstance(v, (int, float)) and not isinstance(v, bool): + return float(v) + if isinstance(v, str): + try: + return float(v) + except ValueError: + pass + return None + + +def _limits_view(doc) -> dict: + """The fields preflight reads from `GET /v1/limits` (served by Drums-Labs/drums#49; any of them may be missing, + and the gateway's extra fields are ignored): + + {"workspace": {"max_live_computers", "live_computers", "max_spend_usd", "spent_usd", "period_end", + "rate_limit_profile"}, + "rate_limit": {"per_s", "burst"}, + "price": {"desktop_hour_usd"}, + "host": {"id", "status", "max_desktops", "live", "free", "admission"}} + + `host.admission` is open, busy (the create gate is full right now), full, down (drumsd did not answer), or the + host status when it is not active. `host.live` / `free` may lag a burst of creates by up to 30 s. + """ + d = doc if isinstance(doc, dict) else {} + ws = d.get("workspace") if isinstance(d.get("workspace"), dict) else d + rl = d.get("rate_limit") if isinstance(d.get("rate_limit"), dict) else {} + price = d.get("price") if isinstance(d.get("price"), dict) else {} + host = d.get("host") if isinstance(d.get("host"), dict) else {} + return { + "max_live": _num(ws, "max_live_computers", "max_live"), + "live": _num(ws, "live_computers", "live"), + "max_spend": _num(ws, "max_spend_usd"), + "cap_set": "max_spend_usd" in ws, + "spent": _num(ws, "spent_usd", "period_spend_usd"), + "period_end": ws.get("period_end"), + "rate_per_s": _num(rl, "per_s", "rate_per_s"), + "rate_burst": _num(rl, "burst"), + "desktop_hour_usd": _num(price, "desktop_hour_usd", "usd_per_desktop_hour"), + "host_id": host.get("id"), + "host_status": host.get("status"), + "host_admission": host.get("admission"), + "host_max": _num(host, "max_desktops"), + "host_live": _num(host, "live"), + "host_free": _num(host, "free"), + "rate_profile": ws.get("rate_limit_profile") if isinstance(ws.get("rate_limit_profile"), str) else None, + } + + +class _Links: + def __init__(self, console: str, workspace: str | None): + self.console, self.ws = console.rstrip("/"), workspace + + def page(self, path: str, what: str) -> str: + if self.ws: + return f"{self.console}/w/{urllib.parse.quote(self.ws)}/{path}" + return f"{self.console} ({what})" + + +def _console_up(url: str, timeout: float) -> tuple: + """(ok, detail, fix) for a GET of the console's sign-in page; no token is sent. A failed certificate check is tried + again with certifi's bundle when certifi is installed (python.org's macOS Python has no root certificates).""" + import ssl # noqa: PLC0415 + req = urllib.request.Request(url.rstrip("/") + "/sign-in", method="GET", headers={"User-Agent": "drums-preflight"}) + t0 = time.monotonic() + ctx = None + for _ in range(2): + try: + with urllib.request.urlopen(req, timeout=timeout, context=ctx) as r: # noqa: S310 (the user's or the default https URL) + return r.status < 500, f"HTTP {r.status} in {time.monotonic() - t0:.1f} s", None + except urllib.error.HTTPError as e: + return e.code < 500, f"HTTP {e.code} in {time.monotonic() - t0:.1f} s", "the console is failing: wait before launching" + except (urllib.error.URLError, OSError) as e: + reason = getattr(e, "reason", e) + if isinstance(reason, ssl.SSLCertVerificationError): + if ctx is None: + try: + import certifi # noqa: PLC0415 + ctx = ssl.create_default_context(cafile=certifi.where()) + continue + except ImportError: + pass + return False, "TLS certificate not verified by this Python", ("on macOS run \"Install Certificates.command\" " + "(in /Applications/Python 3.x/) or pip install certifi") + return False, f"no answer ({reason})", "the console is down: wait before launching" + return False, "no answer", "the console is down: wait before launching" + + +def preflight(desktops: int, hours: float, *, model_gpus=None, task_set: str | None = None, url: str | None = None, + token: str | None = None, console_url: str | None = None, workspace: str | None = None, + desktop_hour_usd: float | None = None, gpu_hour_usd: float | None = None, client=None, + check_console: bool = True, timeout: float = 20.0) -> PreflightReport: + """Check that the gateway, the key and the workspace can carry `desktops` desktops for `hours` hours. + + url/token default to $DRUMS_URL / $DRUMS_TOKEN (or pass a `client`); console_url to $DRUMS_CONSOLE_URL or + https://console.drums.run; workspace (the console slug, for links) to $DRUMS_WORKSPACE. desktop_hour_usd + overrides the gateway's desktop-hour price; gpu_hour_usd with model_gpus adds the GPU cost to the projection + (GPUs are not billed by Drums, so they are not checked against the spend cap). Reads only; never raises for a + failed check (see the report), only for bad arguments.""" + from . import Client # noqa: PLC0415 (import cycle) + + if not isinstance(desktops, int) or desktops < 1: + raise ValueError("desktops must be a positive integer") + if not isinstance(hours, (int, float)) or hours <= 0: + raise ValueError("hours must be a positive number") + gpus = parse_model_gpus(model_gpus) + if client is None: + client = Client(url or os.environ.get("DRUMS_URL") or "", token if token is not None else os.environ.get("DRUMS_TOKEN"), + timeout=timeout, retry_s=3.0) + tok = client.token or "" + # desktop-token mode: GET /auth, then the key goes to the console's token URL. Do it first, so a console that + # cannot issue a token is reported as such and not as "the gateway is down". + cred = client._cred + token_err = None + try: + cred.bearer(client) + except AuthError as e: + token_err = e + except DrumsError as e: + if cred.mode in ("token", "both"): + token_err = e + token_mode = cred.mode if cred.mode in ("token", "both") else None + token_origin = _origin(cred.token_url) if cred.token_url else None + console = (console_url or os.environ.get("DRUMS_CONSOLE_URL") or token_origin or DEFAULT_CONSOLE_URL).rstrip("/") + links = _Links(console, workspace or os.environ.get("DRUMS_WORKSPACE")) + need_rate = desktops * REQUESTS_PER_DESKTOP_S + need_burst = desktops * BURST_PER_DESKTOP + need = {"requests_per_s": need_rate, "burst": need_burst, "requests_per_desktop_s": REQUESTS_PER_DESKTOP_S, + "desktop_hours": desktops * hours} + checks: list = [] + add = checks.append + + # ---- token exchange (gateways in desktop-token mode) ------------------------------------------------------------ + if token_err is not None: + add(Check("gateway", PASS, f"{client.url} answers (auth mode {token_mode or 'token'})")) + if isinstance(token_err, AuthError): + add(Check("auth", FAIL, f"the console refused the key when asked for a desktop token: {token_err.message}", + "create a key (or check DRUMS_TOKEN has no stray space or newline)", links.page("api-keys", "API keys"))) + else: + add(Check("auth", FAIL, f"no desktop token: {token_err.message}", + "this gateway takes desktop tokens only; the console must answer to issue one: wait, or report it", + token_origin or console)) + return _finish(desktops, hours, checks, need, gpus, gpu_hour_usd, check_console, console, timeout) + + # ---- gateway (control plane) + auth ------------------------------------------------------------------------------ + health, t0 = None, time.monotonic() + try: + health = client.call("GET", "/v1/health", timeout=timeout) + took = time.monotonic() - t0 + if took > HEALTH_SLOW_S * 10: + add(Check("gateway", FAIL, f"/v1/health answered in {took:.1f} s: the control plane is overloaded", + "wait for it to recover before launching; a run would see 503s", links.page("overview", "Overview"))) + elif took > HEALTH_SLOW_S: + add(Check("gateway", WARN, f"/v1/health answered in {took:.1f} s (slow; normal is well under {HEALTH_SLOW_S:g} s)", + "launch with fewer desktops first, or wait", links.page("overview", "Overview"))) + else: + add(Check("gateway", PASS, f"{client.url} answered in {took:.2f} s (drumsd {health.get('version', '?') if isinstance(health, dict) else '?'})")) + except AuthError as e: + add(Check("gateway", PASS, f"{client.url} answers")) + add(Check("auth", FAIL, f"the key was refused: {e.message}", + "create a key (or check DRUMS_TOKEN has no stray space or newline)", links.page("api-keys", "API keys"))) + return _finish(desktops, hours, checks, need, gpus, gpu_hour_usd, check_console, console, timeout) + except DrumsError as e: + if e.status == 403: + add(Check("gateway", PASS, f"{client.url} answers")) + add(Check("auth", FAIL, f"the key was refused here: {e.message}", + "use the gateway URL of the key's own workspace (shown with the key in the console)", links.page("api-keys", "API keys"))) + return _finish(desktops, hours, checks, need, gpus, gpu_hour_usd, check_console, console, timeout) + add(Check("gateway", FAIL, f"{client.url or '(no DRUMS_URL)'}: {e.message if e.status else e}", + "check DRUMS_URL (it ends in /gw for Drums Cloud) and that the gateway is up", links.page("overview", "Overview"))) + return _finish(desktops, hours, checks, need, gpus, gpu_hour_usd, check_console, console, timeout, auth_unknown=True) + health = health if isinstance(health, dict) else {} + + # the key's own row: scopes and expiry + m = _KEY.match(tok) + key_row = None + try: + rows = (client.call("GET", "/v1/api-keys", timeout=timeout) or {}).get("items") or [] + key_row = next((r for r in rows if m and r.get("prefix") == m.group(1)), None) + except DrumsError as e: + add(Check("auth", PASS, f"the key is accepted (its metadata could not be read: {e.message})")) + if key_row is not None: + exp = key_row.get("expires_at") + exp_s = _epoch(exp) if exp else None + if key_row.get("revoked_at"): + add(Check("auth", FAIL, "the key is revoked", "create a new key", links.page("api-keys", "API keys"))) + elif exp_s is not None and exp_s < time.time() + hours * 3600: + left = max(0.0, (exp_s - time.time()) / 3600) + add(Check("auth", FAIL, f"the key expires in {left:.1f} h, before the {hours:g} h run ends ({exp})", + "create a key that outlives the run", links.page("api-keys", "API keys"))) + else: + add(_auth_pass(f"key {key_row.get('name') or m.group(1)!s} accepted" + (f", expires {exp}" if exp else ", no expiry"), + cred, token_mode, token_origin, links)) + scopes = set(key_row.get("scopes") or []) + missing = [s for s in REQUIRED_SCOPES if s not in scopes] + wanted = [s for s in WANTED_SCOPES if s not in scopes] + if missing: + add(Check("scopes", FAIL, f"missing {', '.join(missing)} (has {', '.join(sorted(scopes)) or 'none'})", + "create a key with computers:read and computers:write", links.page("api-keys", "API keys"))) + elif wanted: + add(Check("scopes", WARN, f"no {', '.join(wanted)}: " + "; ".join(WANTED_SCOPES[s] for s in wanted), + f"add {', '.join(wanted)} to the key", links.page("api-keys", "API keys"))) + else: + add(Check("scopes", PASS, ", ".join(sorted(scopes)))) + else: + if not any(c.name == "auth" for c in checks): + add(_auth_pass("the key is accepted", cred, token_mode, token_origin, links)) + add(Check("scopes", SKIP, "the key's row was not found by its prefix, so its scopes and expiry are unknown", + "check the key's scopes on the API keys page", links.page("api-keys", "API keys"))) + + # ---- the limits summary (rate limit, quota, spend, price) ------------------------------------------------------- + lim, lim_why = None, None + try: + lim = _limits_view(client.call("GET", "/v1/limits", timeout=timeout)) + except NotFound: + lim_why = "this gateway does not publish GET /v1/limits yet" + except DrumsError as e: + if e.status == 403: + lim_why = "the key has no usage:read, which GET /v1/limits needs" + else: + lim_why = f"GET /v1/limits failed: {e.message if e.status else e}" + + # host capacity + admission + cap = health.get("capacity") if isinstance(health.get("capacity"), dict) else {} + live, mx = _num(cap, "live"), _num(cap, "max") + if (mx is None or live is None) and lim and lim["host_max"] is not None: + mx = lim["host_max"] + live = lim["host_live"] if lim["host_live"] is not None else (mx - lim["host_free"] if lim["host_free"] is not None else None) + if mx is not None and live is not None: + free = int(mx - live) + if free >= desktops: + add(Check("host capacity", PASS, f"{free} of {int(mx)} desktops free on the bound host")) + else: + add(Check("host capacity", FAIL, f"{free} of {int(mx)} desktops free on the bound host; {desktops} needed", + f"close idle desktops, or ask for a bigger host (or run {max(free, 0)} desktops)", links.page("computers", "Computers"))) + else: + add(Check("host capacity", SKIP, "the health reply carries no capacity")) + stale = [c.get("id") for c in health.get("checkpoints") or [] if isinstance(c, dict) and c.get("stale_reason")] + host_status = lim.get("host_status") if lim else None + admission = lim.get("host_admission") if lim else None + if health.get("ok") is False or admission == "down": + add(Check("admission", FAIL, "drumsd on the bound host reports not ok: creates will be refused", + "the host needs an operator; report it with the request id", links.page("overview", "Overview"))) + elif host_status and host_status != "active": + add(Check("admission", FAIL, f"the bound host is {host_status}: new desktops are refused", "wait, or ask for another host", + links.page("overview", "Overview"))) + elif stale: + add(Check("admission", WARN, f"stale image checkpoints (creates from them are refused): {', '.join(map(str, stale))}", + "use another image or ask an operator to reinstall it", links.page("templates", "Desktop images"))) + else: + add(Check("admission", PASS, "drumsd ok, no stale checkpoint" + (f", host {host_status}" if host_status else "") + + (f", creates {admission}" if admission and admission != "open" else ""))) + + # rate limit + if lim and lim["rate_per_s"] is not None: + per_s, burst = lim["rate_per_s"], lim["rate_burst"] + if per_s < need_rate or (burst is not None and burst < need_burst): + add(Check("rate limit", FAIL, f"{per_s:g} req/s, burst {burst if burst is not None else '?'}: {desktops} desktops need about " + f"{need_rate:g} req/s and a burst of {need_burst:g} ({REQUESTS_PER_DESKTOP_S:g} req/s per active desktop)", + "ask for a training rate profile", links.page("usage", "Usage"))) + else: + add(Check("rate limit", PASS, f"{per_s:g} req/s, burst {burst if burst is not None else '?'}; need about {need_rate:g} req/s" + + (f" (profile {lim['rate_profile']})" if lim.get("rate_profile") else ""))) + else: + verdict = WARN if need_rate > DEFAULT_RATE_PER_S or need_burst > DEFAULT_RATE_BURST else SKIP + add(Check("rate limit", verdict, f"not checked ({lim_why or 'GET /v1/limits has no rate_limit'}); {desktops} desktops need about " + f"{need_rate:g} req/s, burst {need_burst:g}. The gateway's default is {DEFAULT_RATE_PER_S} req/s, burst {DEFAULT_RATE_BURST}", + "confirm the per-key limit of your host with support before a large run" if verdict == WARN else None)) + + # quota + if lim and lim["max_live"] is not None: + in_use = lim["live"] or 0.0 + if lim["max_live"] - in_use >= desktops: + add(Check("quota", PASS, f"{int(lim['max_live'] - in_use)} more live desktops allowed (limit {int(lim['max_live'])}, {int(in_use)} live)")) + else: + add(Check("quota", FAIL, f"the workspace may run {int(lim['max_live'])} live desktops ({int(in_use)} live now); {desktops} needed", + "ask for a higher live-desktop quota", links.page("usage", "Usage"))) + else: + add(Check("quota", SKIP, f"not checked ({lim_why or 'GET /v1/limits has no max_live_computers'})", + "see the workspace's live-desktop limit", links.page("usage", "Usage"))) + + # spend + price = desktop_hour_usd if desktop_hour_usd is not None else (lim["desktop_hour_usd"] if lim else None) + if price is not None: + projected = desktops * hours * float(price) + need["desktop_hour_usd"] = float(price) + need["projected_desktop_usd"] = round(projected, 2) + if lim and lim["cap_set"]: + cap_usd, spent = lim["max_spend"], lim["spent"] or 0.0 + if cap_usd is None: + add(Check("spend cap", PASS, f"no cap; projected {projected:,.2f} USD ({desktops} x {hours:g} h x {price:g} USD)")) + elif spent + projected > cap_usd: + add(Check("spend cap", FAIL, f"{spent:,.2f} spent + {projected:,.2f} projected > cap {cap_usd:,.2f} USD " + f"({desktops} x {hours:g} h x {price:g} USD per desktop-hour)", + f"raise the cap to at least {spent + projected:,.0f} USD or run fewer desktop-hours", links.page("usage", "Usage"))) + else: + add(Check("spend cap", PASS, f"{spent:,.2f} spent + {projected:,.2f} projected <= cap {cap_usd:,.2f} USD")) + else: + add(Check("spend cap", SKIP, f"projected {projected:,.2f} USD ({desktops} x {hours:g} h x {price:g} USD); the cap was not checked " + f"({lim_why or 'GET /v1/limits has no max_spend_usd'})", + f"make sure the spend cap leaves at least {projected:,.0f} USD", links.page("usage", "Usage"))) + else: + add(Check("spend cap", SKIP, f"not checked: no desktop-hour price ({lim_why or 'GET /v1/limits has no price'}); " + f"{desktops * hours:g} desktop-hours", "pass --desktop-hour-usd to project the cost", links.page("usage", "Usage"))) + + # task set + if task_set: + add(_task_set_check(client, task_set, lim, links, timeout)) + + return _finish(desktops, hours, checks, need, gpus, gpu_hour_usd, check_console, console, timeout) + + +def _origin(url: str) -> str: + u = urllib.parse.urlsplit(url) + return f"{u.scheme}://{u.netloc}" + + +def _auth_pass(detail: str, cred, token_mode, token_origin, links) -> Check: + """The auth row once the gateway accepted the request: say how (desktop token or API key).""" + if token_mode and cred.using_token: + return Check("auth", PASS, f"{detail}; desktop token from {token_origin} (gateway auth mode {token_mode})") + if token_mode == "both": + return Check("auth", WARN, f"{detail}, but as the API key: the gateway takes desktop tokens and the exchange " + f"failed ({cred.last_error or 'no token'})", + "the run works on the key; check the console answers so the data path does not depend on it", + token_origin or links.console) + return Check("auth", PASS, detail) + + +def _task_set_check(client, task_set: str, lim, links, timeout) -> Check: + try: + if _UUID.match(task_set): + ts = client.call("GET", f"/v1/task-sets/{urllib.parse.quote(task_set)}", timeout=timeout) + else: + items = (client.call("GET", "/v1/task-sets?limit=200", timeout=timeout) or {}).get("items") or [] + hit = [t for t in items if t.get("name") == task_set] + if not hit: + return Check("task set", FAIL, f"no task set named {task_set!r} in this workspace", + "register it (drums_tasks register, or Tasks > New in the console)", links.page("tasks", "Tasks")) + ts = hit[0] + except NotFound: + return Check("task set", FAIL, f"task set {task_set} is not registered for this workspace", + "register it (drums_tasks register, or Tasks > New in the console)", links.page("tasks", "Tasks")) + except DrumsError as e: + return Check("task set", SKIP, f"could not read task set {task_set}: {e.message if e.status else e}") + tid = ts.get("id") or task_set + link = links.page(f"tasks/{tid}", "Tasks") + v = ts.get("validation") if isinstance(ts.get("validation"), dict) else None + name = f"{ts.get('name') or tid} ({ts.get('task_count', '?')} tasks)" + if not v and ts.get("platform"): + return Check("task set", WARN, f"{name} is a platform set with no validation record for this host", + "validate the tasks you train on (oracle 1.0, near misses 0.0) before a long run", link) + if not v: + return Check("task set", FAIL, f"{name} is registered but was never validated on a host", + "run the validator on the host (oracle 1.0 and every near miss 0.0) and register the result", link) + acc, rej = int(v.get("accepted") or 0), int(v.get("rejected") or 0) + host = v.get("host_id") + where = f"on {host}" if host else "on a host" + if acc == 0 or rej > 0: + return Check("task set", FAIL, f"{name}: validation {where} accepted {acc}, rejected {rej}", + "fix or drop the rejected tasks and validate again", link) + bound = lim.get("host_id") if lim else None + if bound and host and bound != host: + return Check("task set", WARN, f"{name}: validated on {host}, but this workspace is bound to {bound}", + "validate it on the bound host", link) + return Check("task set", PASS, f"{name}: validated {where} at {v.get('at', '?')}, accepted {acc}, rejected 0" + + ("" if bound else " (the bound host could not be compared)")) + + +def _finish(desktops, hours, checks, need, gpus, gpu_hour_usd, check_console, console, timeout, auth_unknown=False) -> PreflightReport: + if check_console: + ok, detail, fix = _console_up(console, min(timeout, 10.0)) + checks.insert(1 if checks else 0, Check("console", PASS if ok else FAIL, f"{console}: {detail}", None if ok else fix, + None if ok else console)) + if auth_unknown: + checks.append(Check("auth", SKIP, "not checked: the gateway did not answer")) + if gpus: + split = f"{gpus['inference']} inference + {gpus['trainer']} trainer" if gpus["inference"] is not None else f"{gpus['total']}" + detail = f"{split} GPUs for the model (not billed by Drums)" + if gpu_hour_usd is not None: + gpu_usd = gpus["total"] * hours * float(gpu_hour_usd) + need["projected_gpu_usd"] = round(gpu_usd, 2) + detail += f"; projected {gpu_usd:,.2f} USD at {gpu_hour_usd:g} USD per GPU-hour" + detail += (". In D1 (Qwen3.5-27B, 2 inference + 6 trainer GPUs) the trainer kept 36 to 47 of 128 desktops in " + "flight; size N to what your trainer keeps in flight") + checks.append(Check("model GPUs", INFO, detail)) + return PreflightReport(desktops, hours, checks, need) + + +def _epoch(iso: str) -> float | None: + import datetime as dt # noqa: PLC0415 + try: + s = iso.replace("Z", "+00:00") + d = dt.datetime.fromisoformat(s) + if d.tzinfo is None: + d = d.replace(tzinfo=dt.timezone.utc) + return d.timestamp() + except (ValueError, AttributeError): + return None + + +def add_arguments(ap): + ap.add_argument("--desktops", type=int, required=True, metavar="N", help="desktops the run keeps live") + ap.add_argument("--hours", type=float, required=True, metavar="H", help="how long the run lasts") + ap.add_argument("--model-gpus", metavar="G", help="GPUs for the model: a count (8) or inference:trainer (2:6)") + ap.add_argument("--task-set", metavar="ID", help="a registered task set (id or name) the run uses") + ap.add_argument("--desktop-hour-usd", type=float, metavar="USD", help="desktop-hour price for the projection (default: the gateway's)") + ap.add_argument("--gpu-hour-usd", type=float, metavar="USD", help="with --model-gpus: GPU-hour price, for the total projection") + ap.add_argument("--url", metavar="URL", help="the gateway URL (default $DRUMS_URL)") + ap.add_argument("--console-url", metavar="URL", help=f"the console (default $DRUMS_CONSOLE_URL or {DEFAULT_CONSOLE_URL})") + ap.add_argument("--workspace", metavar="SLUG", help="the console workspace slug, for links (default $DRUMS_WORKSPACE)") + ap.add_argument("--no-console", action="store_true", help="do not check that the console answers") + ap.add_argument("--strict", action="store_true", help="exit 1 also on a warning or a check that could not run") + ap.add_argument("--json", action="store_true", help="print the report as JSON") + ap.add_argument("--allow-insecure-http", action="store_true", help="allow the token over plain http to a non-loopback host") + return ap + + +def run(a, out, err) -> int: + from . import Client # noqa: PLC0415 + from .errors import InsecureTransport # noqa: PLC0415 + from .mcp import read_token # noqa: PLC0415 + + url = (a.url or os.environ.get("DRUMS_URL") or "").strip() + token = read_token() + if not url: + err.write("drums preflight: no gateway URL: pass --url or set DRUMS_URL (Drums Cloud: https:///gw)\n") + return 2 + if not token: + err.write("drums preflight: no key: set DRUMS_TOKEN (or DRUMS_TOKEN_FILE)\n") + return 2 + if a.desktops < 1 or a.hours <= 0: + err.write("drums preflight: --desktops must be at least 1 and --hours above 0\n") + return 2 + try: + parse_model_gpus(a.model_gpus) + client = Client(url, token, timeout=20.0, retry_s=3.0, allow_insecure_http=True if a.allow_insecure_http else None) + except ValueError as e: + err.write(f"drums preflight: {e}\n") + return 2 + except InsecureTransport as e: + err.write(f"drums preflight: {e}\n") + return 2 + rep = preflight(a.desktops, a.hours, model_gpus=a.model_gpus, task_set=a.task_set, client=client, console_url=a.console_url, + workspace=a.workspace, desktop_hour_usd=a.desktop_hour_usd, gpu_hour_usd=a.gpu_hour_usd, + check_console=not a.no_console) + out.write(json.dumps(rep.to_dict(), indent=2) + "\n" if a.json else rep.table()) + return rep.exit_code(a.strict) diff --git a/drums/cli.py b/drums/cli.py index 1d18bc0..efcb0e0 100644 --- a/drums/cli.py +++ b/drums/cli.py @@ -2,6 +2,7 @@ drums mcp [--env ID] [--url URL] [--create] [--task FILE] # the MCP server on stdio (== python -m drums.mcp) drums mcp --print-config claude|claude-local|cursor|codex # a client config snippet (placeholders, never a key) + drums preflight --desktops N --hours H [--model-gpus 2:6] [--task-set ID] [--json] # can this run start? (exit 1: no) drums version """ from __future__ import annotations @@ -45,6 +46,8 @@ def build_parser() -> argparse.ArgumentParser: ap = argparse.ArgumentParser(prog="drums", description="Drums: isolated desktops for computer-use agents.") sub = ap.add_subparsers(dest="command", metavar="command") add_arguments(sub.add_parser("mcp", help="run the MCP server on stdio (or print a client config with --print-config)")) + from ._preflight import add_arguments as preflight_arguments + preflight_arguments(sub.add_parser("preflight", help="check that the gateway, key and workspace can carry N desktops for H hours")) sub.add_parser("version", help="print the SDK version") return ap @@ -55,6 +58,9 @@ def main(argv=None) -> int: if a.command == "version": sys.stdout.write(f"drums {__version__}\n") return 0 + if a.command == "preflight": + from ._preflight import run as preflight_run + return preflight_run(a, sys.stdout, sys.stderr) if a.command == "mcp": from .mcp import run return run(a) diff --git a/drums/errors.py b/drums/errors.py index 119d136..c198eca 100644 --- a/drums/errors.py +++ b/drums/errors.py @@ -5,6 +5,9 @@ class DrumsError(Exception): """Base class. `status` is the HTTP status (0 when no reply), `message` the server's error text.""" + #: seconds the server asked the client to wait (its Retry-After header), when the reply had one + retry_after = None + def __init__(self, status: int, message: str, body=None): super().__init__(f"drumsd HTTP {status}: {message}" if status else message) self.status, self.message, self.body = status, message, body @@ -75,9 +78,14 @@ class Conflict(DrumsError): class Overloaded(DrumsError): - """429 `overloaded`: drumsd refused a create, save or fork because the host is near its memory limit (or under - memory pressure, or the state tmpfs is nearly full). Nothing was started; try again later. `reason` is memory, - memory_pressure or state_space; `admission` has the numbers (available, in flight, needed, floor).""" + """429: nothing was started. From drumsd (`overloaded`): a create, save or fork was refused because the host is + near its memory limit (or under memory pressure, or the state tmpfs is nearly full); `reason` is memory, + memory_pressure or state_space and `admission` has the numbers (available, in flight, needed, floor). From the + gateway: `rate_limited` (the per-key request rate) or `overloaded` (host full, too many creates in flight). + The client already retried it under its RetryPolicy; `retry_after` is the server's last Retry-After (seconds) + and `retries` how many retries were made.""" + + retries = 0 def __init__(self, status: int, message: str, body=None): super().__init__(status, message, body) @@ -115,6 +123,17 @@ class DaemonUnavailable(DrumsError): """drumsd did not answer (down, restarting, network). For a POST the outcome is unknown: call env.refresh().""" +class CertificateError(DaemonUnavailable): + """The server's TLS certificate could not be verified, so nothing was sent. Most often python.org's macOS Python, + which has no root certificates until "Install Certificates.command" runs; the client already retried with + certifi's CA bundle when certifi is installed. `origin` is scheme://host:port, `hint` the fix. A subclass of + DaemonUnavailable, so `except DaemonUnavailable` still catches it.""" + + def __init__(self, origin: str, reason: str, hint: str): + super().__init__(0, f"TLS certificate verification failed for {origin} ({reason}): {hint}") + self.origin, self.reason, self.hint = origin, reason, hint + + class GuestError(DrumsError): """502: the desktop's guest server did not answer or refused the action.""" diff --git a/drums/mcp.py b/drums/mcp.py index 7630b48..4568e5e 100644 --- a/drums/mcp.py +++ b/drums/mcp.py @@ -30,8 +30,8 @@ import sys import urllib.parse -from . import Client, Env, __version__, connect -from .errors import DrumsError, InsecureTransport, NotFound +from . import Client, Env, RetryPolicy, __version__, connect +from .errors import BadRequest, DrumsError, InsecureTransport, NotFound from .hybrid import HybridTools PROTOCOL = "2025-06-18" @@ -139,6 +139,23 @@ def _check(v, schema: dict, label: str): return None +NO_TASK = "no task loaded on this computer: use load_task (task, task_set_id + task_id, or task_id), or create_computer with a task" + + +def coerce_json_objects(schema: dict, args: dict) -> None: + """Some MCP clients send an object argument as a JSON string: for a property whose schema is an object, a string + that parses to a JSON object is replaced by that object before validation (as the gateway's server does).""" + for k, s in (schema.get("properties") or {}).items(): + v = args.get(k) + if isinstance(s, dict) and s.get("type") == "object" and isinstance(v, str) and v.lstrip().startswith("{"): + try: + parsed = json.loads(v) + except ValueError: + continue + if isinstance(parsed, dict): + args[k] = parsed + + def validate(schema: dict, args) -> str | None: """The first schema violation of a tool's arguments, naming the field; None when they are fine.""" if not isinstance(args, dict): @@ -221,12 +238,22 @@ def _gateway(self, method: str, path: str, body=None, headers=None): raise def _task_doc(self, args: dict, required: bool): + """`task` (a whole document), `task_set_id` + `task_id` (a task of a registered set), or `task_id` alone (an + OSWorld task from the host's checkout). The same rules and messages as the gateway's server.""" if isinstance(args.get("task"), dict): return args["task"] + if args.get("task_set_id"): + if not args.get("task_id"): + raise ToolError("task_set_id needs task_id: the id of a task in that set (get_task_set lists them)") + q = urllib.parse.quote + try: + return self._gateway("GET", f"/v1/task-sets/{q(str(args['task_set_id']))}/tasks/{q(str(args['task_id']), safe='')}") + except NotFound as e: + raise ToolError(f"{e.message}: task_set_id {args['task_set_id']}, task_id {args['task_id']}") from None if args.get("task_id"): return self._api("GET", f"/v1/tasks/{urllib.parse.quote(str(args['task_id']))}") if required: - raise ToolError("one of task_id or task is required") + raise ToolError("one of task (a task document), task_set_id + task_id, or task_id (an OSWorld task) is required") return None def _checkpoints(self) -> list: @@ -280,6 +307,13 @@ def list_tasks(self, a): def get_task(self, a): return self._api("GET", f"/v1/tasks/{urllib.parse.quote(a['task_id'])}") + def list_task_sets(self, a): + r = self._gateway("GET", "/v1/task-sets" + _q(limit=a.get("limit") or 50)) + return {"task_sets": _rows(r, "task_sets"), "next": r.get("next_cursor") if isinstance(r, dict) else None} + + def get_task_set(self, a): + return self._gateway("GET", f"/v1/task-sets/{urllib.parse.quote(a['task_set_id'])}") + def _list_runs(self, a, kind=None): return self._gateway("GET", "/v1/runs" + _q(kind=kind, status=a.get("status"), limit=a.get("limit") or 50)) @@ -320,7 +354,20 @@ def read_audit_log(self, a): # desktop tools ------------------------------------------------------------------------------------------------------ def verify(self, a): - r = self._env(a["computer_id"]).verify(strict=False) + env = self._env(a["computer_id"]) + try: + r = env.verify(strict=False) + except BadRequest as e: + # drumsd answers 400 to a verify with no task (or a task without an OSWorld checker): say which (A-08) + if e.status != 400: + raise + try: + rec = env.refresh() + except DrumsError: + raise e from None + if not isinstance(rec.get("task"), dict): + raise ToolError(NO_TASK) from None + raise ToolError("the loaded task has no checker this host can run (it is not an OSWorld-format task with an evaluator)") from None return {"score": r.score, "valid": r.valid, "trusted": r.trusted, "audit_flags": r.audit_flags, "checker_error": r.checker_error} def fork(self, a): @@ -360,6 +407,8 @@ def call(self, name: str, args) -> list: args["computer_id"] = self.default_computer_id if tool.get("destructive") and not (isinstance(args, dict) and args.get("confirm") is True): raise ToolError(f"refused: pass confirm: true to {name}") + if isinstance(args, dict): + coerce_json_objects(tool["inputSchema"], args) problem = validate(tool["inputSchema"], args) if problem: raise ToolError(problem) @@ -463,10 +512,12 @@ def run(a) -> int: if a.env and a.create: sys.stderr.write("drums mcp: --env and --create exclude each other\n") return 2 - # retry_s: an unreachable server fails a tool call within seconds (a trainer's 60 s is too long for a chat turn) + # retry_s / retry: an unreachable or rate-limited server fails a tool call within seconds (a trainer's 60 s is too + # long for a chat turn); $DRUMS_RETRY_MAX_WAIT_S still wins when set + retry = RetryPolicy.from_env() if os.environ.get("DRUMS_RETRY_MAX_WAIT_S", "").strip() else RetryPolicy(max_wait_s=10.0) try: c = connect(a.url or os.environ.get("DRUMS_URL"), read_token(), check=False, close_on_exit=bool(a.create), retry_s=5.0, - allow_insecure_http=True if a.allow_insecure_http else None) + allow_insecure_http=True if a.allow_insecure_http else None, retry=retry) except InsecureTransport as e: sys.stderr.write(f"drums mcp: {e}\n") # names the host and the opt-ins, never the token return 2 diff --git a/drums/mcp_tools.json b/drums/mcp_tools.json index 50bcff9..f5b7533 100644 --- a/drums/mcp_tools.json +++ b/drums/mcp_tools.json @@ -27,13 +27,14 @@ "name": "create_computer", "layer": "workspace", "scope": "computers:write", - "description": "Start a new isolated desktop (computer) from a template or a snapshot, optionally with a task loaded. Returns the computer record; its `id` is the computer_id every desktop tool takes. The desktop is ready when state is `ready` and validity is `valid`.", + "description": "Start a new isolated desktop (computer) from a template or a snapshot, optionally with a task loaded. The task is one of: `task` (a whole task document, for tasks you wrote or generated), `task_set_id` + `task_id` (a task of a set registered in the console or with POST /v1/task-sets; see list_task_sets), or `task_id` alone (an OSWorld task from list_tasks). Returns the computer record; its `id` is the computer_id every desktop tool takes. The desktop is ready when state is `ready` and validity is `valid`.", "inputSchema": { "type": "object", "properties": { "template": { "type": "string", "description": "A template checkpoint from list_templates (for example osworld-ubuntu) or a snapshot id from list_snapshots.", "minLength": 1, "maxLength": 200 }, - "task_id": { "type": "string", "description": "A task id from list_tasks to load into the desktop at start (its setup runs before the episode).", "maxLength": 200 }, - "task": { "type": "object", "description": "A full task document (OSWorld format) instead of task_id.", "additionalProperties": true }, + "task_id": { "type": "string", "description": "With task_set_id: a task id of that set. Alone: an OSWorld task id from list_tasks. Its setup runs before the episode.", "maxLength": 200 }, + "task_set_id": { "type": "string", "description": "A registered task set from list_task_sets; with task_id, the task to load from it.", "pattern": "^[0-9a-fA-F-]{36}$" }, + "task": { "type": "object", "description": "A whole task document (OSWorld format: id, instruction, config, evaluator, ...) instead of task_id.", "additionalProperties": true }, "ttl_s": { "type": "integer", "description": "Lifetime in seconds; the computer is closed when it expires (0 or absent: the workspace default).", "minimum": 0, "maximum": 2592000 }, "setup": { "type": "boolean", "description": "Run the task's setup (default true when a task is given)." } }, @@ -133,17 +134,41 @@ "additionalProperties": false } }, + { + "name": "list_task_sets", + "layer": "workspace", + "scope": "computers:read", + "description": "List the task sets this workspace can use: the ones it registered (console Tasks page, POST /v1/task-sets, the drums-verifiers task factory) and the platform sets, with id, name, task_count and validation. get_task_set lists a set's task ids.", + "inputSchema": { + "type": "object", + "properties": { "limit": { "type": "integer", "minimum": 1, "maximum": 200, "default": 50 } }, + "additionalProperties": false + } + }, + { + "name": "get_task_set", + "layer": "workspace", + "scope": "computers:read", + "description": "One task set with its items (task_id, instruction, related_apps). Pass its id as task_set_id and an item's task_id to create_computer or load_task to run that task.", + "inputSchema": { + "type": "object", + "properties": { "task_set_id": { "type": "string", "pattern": "^[0-9a-fA-F-]{36}$" } }, + "required": ["task_set_id"], + "additionalProperties": false + } + }, { "name": "load_task", "layer": "desktop", "scope": "computers:write", - "description": "Load a task into a running computer (runs its setup and starts a new episode). After this, `verify` scores the desktop against this task's checker.", + "description": "Load a task into a running computer (runs its setup and starts a new episode): `task` (a whole task document), `task_set_id` + `task_id` (a task of a registered set), or `task_id` alone (an OSWorld task). After this, `verify` scores the desktop against this task's checker.", "inputSchema": { "type": "object", "properties": { "computer_id": { "type": "string", "minLength": 1, "maxLength": 64 }, - "task_id": { "type": "string", "maxLength": 200 }, - "task": { "type": "object", "additionalProperties": true } + "task_id": { "type": "string", "description": "With task_set_id: a task id of that set. Alone: an OSWorld task id from list_tasks.", "maxLength": 200 }, + "task_set_id": { "type": "string", "description": "A registered task set from list_task_sets; with task_id, the task to load from it.", "pattern": "^[0-9a-fA-F-]{36}$" }, + "task": { "type": "object", "description": "A whole task document (OSWorld format) instead of task_id.", "additionalProperties": true } }, "required": ["computer_id"], "additionalProperties": false @@ -442,7 +467,7 @@ "name": "verify", "layer": "desktop", "scope": "computers:write", - "description": "Score the desktop's current state with the loaded task's checker: score (0..1), valid (every gate of the episode passed), trusted, audit flags.", + "description": "Score the desktop's current state with the loaded task's checker: score (0..1), valid (every gate of the episode passed), trusted, audit flags. On a computer with no task loaded it says so: load one with load_task first.", "inputSchema": { "type": "object", "properties": { "computer_id": { "type": "string", "minLength": 1, "maxLength": 64 } }, diff --git a/drums/runs.py b/drums/runs.py new file mode 100644 index 0000000..6870775 --- /dev/null +++ b/drums/runs.py @@ -0,0 +1,360 @@ +"""The run object: a training (or evaluation) run the SDK opens, feeds and closes, so the console's Runs page can show +it (task set, config hash, step counter, reward, zero-advantage share, rollouts, desktops busy, cost) instead of a +list of anonymous computers (audit A-36). + + with client.run("qwen27b-d2", kind="training", task_set=task_set_id, config=cfg) as run: + for step in range(steps): + ... + run.step(step, reward=mean_reward, zero_advantage_share=zero_adv, rollouts=n, desktops_busy=busy) + +Wire (gateway routes; the SDK feature-detects them and is a no-op with one warning on a gateway without them): + + POST /v1/runs {name, kind, task_set_id | task_set, config, config_hash, label, desktops_provisioned?} + -> {run_id | id, label, ...} (Idempotency-Key header: a retried open returns the same + run). The reply's `label` is the one in use: when a running run already holds the + label the gateway gives this one `