From cbc689bdf0ce20f62c675bb2cb5677acbd0d707e Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 18:50:07 -0500 Subject: [PATCH 01/23] ci: pip-audit gate on what CI installs, with an allowlist that expires, and a weekly audit that opens an issue on failure (A-40) --- .github/scripts/pip-audit.sh | 43 ++++++++++++++++++ .github/workflows/ci.yml | 13 ++++++ .github/workflows/dependency-audit.yml | 60 ++++++++++++++++++++++++++ .pip-audit-ignore | 2 + 4 files changed, 118 insertions(+) create mode 100755 .github/scripts/pip-audit.sh create mode 100644 .github/workflows/dependency-audit.yml create mode 100644 .pip-audit-ignore 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..59e47f6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,3 +27,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/.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. From 7d816486668b7fe4aa18932ff6b9038d79dc2b81 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 18:52:38 -0500 Subject: [PATCH 02/23] client: retry 429 replies on every call, honouring Retry-After with jittered backoff (RetryPolicy, DRUMS_RETRY_MAX_WAIT_S); fall back to certifi when the system certificate store fails, else CertificateError with the fix --- README.md | 20 ++- drums/__init__.py | 150 ++++++++++++++++++++-- drums/errors.py | 25 +++- drums/mcp.py | 8 +- tests/test_client.py | 16 ++- tests/test_retry_certs.py | 261 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 455 insertions(+), 25 deletions(-) create mode 100644 tests/test_retry_certs.py diff --git a/README.md b/README.md index 256a36b..a3a9a8f 100644 --- a/README.md +++ b/README.md @@ -115,8 +115,18 @@ 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. ## Computers @@ -322,8 +332,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 +355,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 diff --git a/drums/__init__.py b/drums/__init__.py index 35ee461..f559402 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,7 +56,7 @@ 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) @@ -55,7 +67,7 @@ __all__ = ["ActionFailed", "connect", "Client", "Env", "Reward", "Observation", "StepResult", "State", "ForkResult", "env", "__version__", "DrumsError", "AuthError", "BadRequest", "NotFound", "EnvGone", "Conflict", "DaemonUnavailable", "GuestError", "EnvFailed", "RestoreFailed", "GateFailed", "TaskSetupFailed", "ForkError", "BatchError", "InvalidEpisode", "CheckerError", "NotQuiescent", "Overloaded", - "CheckpointStale", "TaskUnsupported", "InsecureTransport", "RedirectRefused", "check_transport"] + "CheckpointStale", "TaskUnsupported", "InsecureTransport", "RedirectRefused", "check_transport", "RetryPolicy", "CertificateError"] _STATUS = {400: BadRequest, 401: AuthError, 404: NotFound, 409: Conflict, 410: EnvGone, 422: BadRequest, 429: Overloaded, 502: GuestError, 503: DaemonUnavailable} @@ -146,8 +158,81 @@ 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})") + + +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") + + 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 +240,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 +270,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,6 +281,7 @@ 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._owned: dict[str, None] = {} # ids of envs this client created and has not closed (insertion order) self._owned_lock = threading.Lock() self.close_on_exit = close_on_exit @@ -262,9 +351,26 @@ def __exit__(self, *exc): self.close() # transport -------------------------------------------------------------------------------------------------------- + def _use_certifi(self) -> bool: + """Switch this client to certifi's CA bundle (once). False when certifi is missing or already in use.""" + if self._certifi: + return False + ctx = _certifi_context() + if ctx is None: + return False + self._opener = urllib.request.build_opener(_RedirectPolicy(self.token, self.allow_insecure_http), urllib.request.HTTPSHandler(context=ctx)) + self._certifi = True + sys.stderr.write(f"drums: the system certificate store could not verify {_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 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() @@ -273,8 +379,11 @@ def call(self, method: str, path: str, body=None, raw: bool = False, timeout: fl 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 while True: 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 +395,16 @@ 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 == 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 +415,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 ----------------------------------------------------------------------------------------------------------- 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..838e46d 100644 --- a/drums/mcp.py +++ b/drums/mcp.py @@ -30,7 +30,7 @@ import sys import urllib.parse -from . import Client, Env, __version__, connect +from . import Client, Env, RetryPolicy, __version__, connect from .errors import DrumsError, InsecureTransport, NotFound from .hybrid import HybridTools @@ -463,10 +463,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/tests/test_client.py b/tests/test_client.py index a490920..5015d73 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -345,13 +345,23 @@ async def main(): took = asyncio.run(main()) self.assertLess(took, 3 * delay, f"{n} concurrent steps of {delay} s took {took:.2f} s") - def test_overloaded_is_typed_and_not_retried(self): + def test_overloaded_is_typed_and_not_retried_with_retries_off(self): + c = drums.connect(self.url, TOKEN, retry_s=1, close_on_exit=False, retry=drums.RetryPolicy(max_wait_s=0)) n = len([c for c in Fake.calls if c[1] == "/v1/slots"]) with self.assertRaises(drums.Overloaded) as cm: - self.c.create(image="full") + c.create(image="full") self.assertEqual(cm.exception.reason, "memory") self.assertEqual(cm.exception.admission["floor_mib"], 40000) - self.assertEqual(len([c for c in Fake.calls if c[1] == "/v1/slots"]), n + 1) # a POST is never retried + self.assertEqual(len([c for c in Fake.calls if c[1] == "/v1/slots"]), n + 1) # RetryPolicy(max_wait_s=0): no retry + + def test_overloaded_is_retried_within_the_budget_then_raised(self): + c = drums.connect(self.url, TOKEN, retry_s=1, close_on_exit=False, retry=drums.RetryPolicy(max_wait_s=0.3, base_s=0.05, jitter=0)) + n = len([c for c in Fake.calls if c[1] == "/v1/slots"]) + with self.assertRaises(drums.Overloaded) as cm: + c.create(image="full") + tries = len([c for c in Fake.calls if c[1] == "/v1/slots"]) - n + self.assertGreater(tries, 1) # a 429 started nothing: retried + self.assertEqual(cm.exception.retries, tries - 1) def test_a_failed_action_raises_with_its_exit_status(self): e = self.c.create() diff --git a/tests/test_retry_certs.py b/tests/test_retry_certs.py new file mode 100644 index 0000000..7e324bf --- /dev/null +++ b/tests/test_retry_certs.py @@ -0,0 +1,261 @@ +"""Retry-After on every call (429 from the gateway's rate limit or no capacity, for GET and POST alike), the retry +budget and its off switch, and the TLS fallback to certifi's CA bundle (A-07). Localhost fakes only.""" +import email.utils +import io +import json +import os +import ssl +import sys +import threading +import time +import unittest +import urllib.error +import urllib.request +from contextlib import redirect_stderr +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest import mock + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) +import drums # noqa: E402 + +TOKEN = "t" * 43 +PNG = b"\x89PNG\r\n\x1a\n" + b"\x00\x00\x00\rIHDR" + (8).to_bytes(4, "big") + (8).to_bytes(4, "big") + b"\x08\x02\x00\x00\x00" + + +class Limited(BaseHTTPRequestHandler): + """Every path answers 429 `rate_limited` (with `retry_after`, when set) for its first `refuse` requests, then 200.""" + refuse = 0 + retry_after = "0" + seen = [] + lock = threading.Lock() + down_503 = 0 + + def log_message(self, *a): + pass + + def _reply(self, code, obj=None, raw=None, headers=None): + b = raw if raw is not None else json.dumps(obj).encode() + self.send_response(code) + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.send_header("Content-Length", str(len(b))) + self.end_headers() + self.wfile.write(b) + + def _handle(self): + n = int(self.headers.get("Content-Length") or 0) + if n: + self.rfile.read(n) + with Limited.lock: + Limited.seen.append((self.command, self.path, time.monotonic())) + hits = sum(1 for m, p, _ in Limited.seen if p == self.path and m == self.command) + down = Limited.down_503 + if down: + Limited.down_503 -= 1 + if down: + return self._reply(503, {"error": "starting", "code": "retryable_infrastructure_failure"}, headers={"Retry-After": "0.2"}) + if hits <= Limited.refuse: + h = {"Retry-After": Limited.retry_after} if Limited.retry_after is not None else {} + return self._reply(429, {"error": "too many requests; slow down", "code": "rate_limited"}, headers=h) + if self.path.endswith("/screenshot"): + return self._reply(200, raw=PNG) + if self.path.endswith("/step"): + return self._reply(200, {"result": {"returncode": 0}, "episode": 1, "validity": {"verdict": "valid"}}) + if self.path.endswith("/verify"): + return self._reply(200, {"slot": "s1", "score": 1.0, "valid": True, "validity": {"verdict": "valid"}}) + return self._reply(200, {"id": "s1", "state": "ready", "episode": 1, "validity": {"verdict": "valid"}}) + + do_GET = do_POST = do_DELETE = _handle + + +class RetryAfter(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.srv = ThreadingHTTPServer(("127.0.0.1", 0), Limited) + threading.Thread(target=cls.srv.serve_forever, daemon=True).start() + cls.url = f"http://127.0.0.1:{cls.srv.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.srv.shutdown() + + def setUp(self): + Limited.seen.clear() + Limited.refuse, Limited.retry_after, Limited.down_503 = 0, "0", 0 + + def client(self, **kw): + return drums.Client(self.url, TOKEN, retry_s=1, retry=drums.RetryPolicy(**{"base_s": 0.02, "jitter": 0, **kw})) + + def env(self, c): + return drums.Env(c, {"id": "s1", "state": "ready"}) + + def test_step_screenshot_verify_create_are_all_retried_after_a_429(self): + Limited.refuse = 2 + c = self.client() + e = self.env(c) + self.assertEqual(e.step("pyautogui.click(1, 1)").result["returncode"], 0) + self.assertEqual(e.screenshot(), PNG) + self.assertEqual(e.verify().score, 1.0) + self.assertEqual(c.create().id, "s1") + for method, path in (("POST", "/v1/slots/s1/step"), ("GET", "/v1/slots/s1/screenshot"), ("POST", "/v1/slots/s1/verify"), ("POST", "/v1/slots")): + self.assertEqual(sum(1 for m, p, _ in Limited.seen if (m, p) == (method, path)), 3, path) + + def test_the_wait_honours_retry_after(self): + Limited.refuse, Limited.retry_after = 1, "0.4" + c = self.client() + t0 = time.monotonic() + self.env(c).step("pyautogui.click(1, 1)") + self.assertGreaterEqual(time.monotonic() - t0, 0.4) + t = [ts for m, p, ts in Limited.seen if p.endswith("/step")] + self.assertGreaterEqual(t[1] - t[0], 0.38) + + def test_retry_after_as_an_http_date(self): + when = email.utils.formatdate(time.time() + 1.2, usegmt=True) + self.assertGreater(drums._retry_after({"Retry-After": when}), 0.0) + self.assertLessEqual(drums._retry_after({"Retry-After": when}), 1.2) + self.assertEqual(drums._retry_after({"Retry-After": "3"}), 3.0) + self.assertIsNone(drums._retry_after({"Retry-After": "soon"})) + self.assertIsNone(drums._retry_after({})) + + def test_the_budget_runs_out_and_the_error_says_how_long_to_wait(self): + Limited.refuse, Limited.retry_after = 100, "0.1" + c = self.client(max_wait_s=0.35) + t0 = time.monotonic() + with self.assertRaises(drums.Overloaded) as cm: + self.env(c).step("pyautogui.click(1, 1)") + self.assertLess(time.monotonic() - t0, 1.5) + self.assertEqual(cm.exception.status, 429) + self.assertEqual(cm.exception.retry_after, 0.1) + self.assertGreaterEqual(cm.exception.retries, 2) + self.assertEqual(sum(1 for _, p, _ in Limited.seen if p.endswith("/step")), cm.exception.retries + 1) + + def test_max_attempts_bounds_the_retries(self): + Limited.refuse = 100 + with self.assertRaises(drums.Overloaded) as cm: + self.env(self.client(max_attempts=3)).screenshot() + self.assertEqual(cm.exception.retries, 3) + + def test_off_switch_kwarg_and_environment(self): + Limited.refuse = 1 + with self.assertRaises(drums.Overloaded): + self.env(self.client(max_wait_s=0)).step("x") + Limited.seen.clear() + with mock.patch.dict(os.environ, {"DRUMS_RETRY_MAX_WAIT_S": "0"}): + c = drums.Client(self.url, TOKEN) + self.assertEqual(c.retry.max_wait_s, 0.0) + with self.assertRaises(drums.Overloaded): + self.env(c).step("x") + with mock.patch.dict(os.environ, {"DRUMS_RETRY_MAX_WAIT_S": "12.5"}): + self.assertEqual(drums.Client(self.url, TOKEN).retry.max_wait_s, 12.5) + with mock.patch.dict(os.environ, {"DRUMS_RETRY_MAX_WAIT_S": "nonsense"}): + self.assertEqual(drums.Client(self.url, TOKEN).retry.max_wait_s, 60.0) + self.assertEqual(drums.connect(self.url, TOKEN, check=False, close_on_exit=False, handle_signals=False, + retry=drums.RetryPolicy(max_wait_s=5)).retry.max_wait_s, 5) + + def test_jitter_spreads_the_waits(self): + p = drums.RetryPolicy(base_s=0.5, jitter=0.25) + waits = {round(p.wait(0, 1.0), 6) for _ in range(50)} + self.assertGreater(len(waits), 10) + self.assertTrue(all(1.0 <= w <= 1.0 + 0.25 * 1.5 + 1e-9 for w in waits), waits) + q = drums.RetryPolicy(base_s=0.5, cap_s=4, jitter=0) + self.assertEqual([q.wait(i, None) for i in range(5)], [0.5, 1.0, 2.0, 4.0, 4.0]) + + def test_a_get_503_waits_for_its_retry_after(self): + Limited.down_503 = 1 + c = self.client() + t0 = time.monotonic() + self.assertEqual(c.call("GET", "/v1/health")["id"], "s1") + self.assertGreaterEqual(time.monotonic() - t0, 0.2) + + def test_a_post_503_is_still_not_retried(self): + Limited.down_503 = 1 + with self.assertRaises(drums.DaemonUnavailable): + self.client().call("POST", "/v1/slots", {"checkpoint": "x"}) + self.assertEqual(len(Limited.seen), 1) + + +class _Resp(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *a): + self.close() + + +class _Opener: + def __init__(self, outcomes): + self.outcomes, self.urls = list(outcomes), [] + + def open(self, req, timeout=None): + self.urls.append(req.full_url) + o = self.outcomes.pop(0) + if isinstance(o, BaseException): + raise o + return _Resp(o) + + +def cert_failure(): + return urllib.error.URLError(ssl.SSLCertVerificationError(1, "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate")) + + +class CertifiFallback(unittest.TestCase): + def test_a_failed_system_store_switches_to_certifi_once_with_a_hint(self): + c = drums.Client("https://gw.example/gw", TOKEN) + c._opener = _Opener([cert_failure()]) + good = _Opener([b'{"ok": true}', b'{"ok": true}']) + err = io.StringIO() + with mock.patch.object(drums, "_certifi_context", return_value=ssl.create_default_context()), \ + mock.patch.object(drums.urllib.request, "build_opener", return_value=good) as build, redirect_stderr(err): + self.assertEqual(c.call("POST", "/v1/slots/s1/step", {"action": {}}), {"ok": True}) # safe: nothing was sent + self.assertEqual(c.health(), {"ok": True}) + self.assertEqual(build.call_count, 1) + self.assertTrue(c._certifi) + lines = err.getvalue().strip().splitlines() + self.assertEqual(len(lines), 1) + self.assertIn("certifi", lines[0]) + self.assertIn("https://gw.example:443", lines[0]) + self.assertIn("Install Certificates.command", lines[0]) + self.assertNotIn(TOKEN, err.getvalue()) + + def test_without_certifi_the_error_names_the_fix_and_is_not_retried(self): + c = drums.Client("https://gw.example/gw", TOKEN, retry_s=30) + c._opener = _Opener([cert_failure()]) + t0 = time.monotonic() + with mock.patch.object(drums, "_certifi_context", return_value=None): + with self.assertRaises(drums.CertificateError) as cm: + c.health() + self.assertLess(time.monotonic() - t0, 1.0) # a GET is not retried for retry_s on a cert failure + self.assertIsInstance(cm.exception, drums.DaemonUnavailable) + msg = str(cm.exception) + self.assertIn("Install Certificates.command", msg) + self.assertIn("pip install certifi", msg) + self.assertIn("gw.example", msg) + self.assertNotIn(TOKEN, msg) + + def test_when_certifi_fails_too_the_error_says_so(self): + c = drums.Client("https://gw.example/gw", TOKEN) + c._opener = _Opener([cert_failure()]) + with mock.patch.object(drums, "_certifi_context", return_value=ssl.create_default_context()), \ + mock.patch.object(drums.urllib.request, "build_opener", return_value=_Opener([cert_failure()])), redirect_stderr(io.StringIO()): + with self.assertRaises(drums.CertificateError) as cm: + c.health() + self.assertIn("certifi's bundle could not verify it either", str(cm.exception)) + + def test_the_certifi_opener_keeps_the_redirect_policy(self): + c = drums.Client("https://gw.example/gw", TOKEN) + built = [] + real = urllib.request.build_opener + + def spy(*handlers): + built.append(handlers) + return real(*handlers) + with mock.patch.object(drums, "_certifi_context", return_value=ssl.create_default_context()), \ + mock.patch.object(drums.urllib.request, "build_opener", side_effect=spy), redirect_stderr(io.StringIO()): + self.assertTrue(c._use_certifi()) + self.assertFalse(c._use_certifi()) # once + self.assertTrue(any(isinstance(h, drums._RedirectPolicy) for h in built[0])) + self.assertTrue(any(isinstance(h, urllib.request.HTTPSHandler) for h in built[0])) + + +if __name__ == "__main__": + unittest.main() From d73a139b037647647357f916433ed22c49b57fa7 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 18:54:45 -0500 Subject: [PATCH 03/23] ci: run the Python matrix on ubuntu-24.04; ubuntu-latest is 26.04 and has no Python 3.9 (main fails the same way) --- .github/workflows/ci.yml | 3 ++- .github/workflows/release.yml | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 59e47f6..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: 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: From 45cca7dd5f9191fac72861c6aca432cbfef8efb6 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:00:02 -0500 Subject: [PATCH 04/23] run object: client.run(name, kind=..., task_set=..., config=...) opens a run, buffers step() points and flushes at most once per 30 s, closes on exit, labels the desktops created inside; a no-op with one warning on a gateway without the run routes --- README.md | 24 +++- drums/__init__.py | 39 +++++- drums/runs.py | 283 +++++++++++++++++++++++++++++++++++++++++++ tests/test_runs.py | 296 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 638 insertions(+), 4 deletions(-) create mode 100644 drums/runs.py create mode 100644 tests/test_runs.py diff --git a/README.md b/README.md index 256a36b..34344d1 100644 --- a/README.md +++ b/README.md @@ -203,10 +203,32 @@ 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) 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) +``` + +- `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 name as their label (`X-Drums-Run-Label`; fork children inherit + it), so the Computers page can filter them by run. +- 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 without `runs: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). diff --git a/drums/__init__.py b/drums/__init__.py index 35ee461..65715a5 100644 --- a/drums/__init__.py +++ b/drums/__init__.py @@ -44,9 +44,11 @@ import threading import warnings +from . import runs as _runs from .errors import (ActionFailed, AuthError, BadRequest, BatchError, CheckerError, CheckpointStale, Conflict, DaemonUnavailable, DrumsError, EnvFailed, # noqa: F401 EnvGone, ForkError, GateFailed, GuestError, InsecureTransport, InvalidEpisode, NotFound, NotQuiescent, Overloaded, RedirectRefused, RestoreFailed, TaskSetupFailed, TaskUnsupported) +from .runs import Run, RunNotSupported __version__ = "0.3.0" DEFAULT_URL = os.environ.get("DRUMS_URL") or os.environ.get("DRUMSD_URL") or "http://127.0.0.1:7070" @@ -55,7 +57,7 @@ __all__ = ["ActionFailed", "connect", "Client", "Env", "Reward", "Observation", "StepResult", "State", "ForkResult", "env", "__version__", "DrumsError", "AuthError", "BadRequest", "NotFound", "EnvGone", "Conflict", "DaemonUnavailable", "GuestError", "EnvFailed", "RestoreFailed", "GateFailed", "TaskSetupFailed", "ForkError", "BatchError", "InvalidEpisode", "CheckerError", "NotQuiescent", "Overloaded", - "CheckpointStale", "TaskUnsupported", "InsecureTransport", "RedirectRefused", "check_transport"] + "CheckpointStale", "TaskUnsupported", "InsecureTransport", "RedirectRefused", "check_transport", "Run", "RunNotSupported"] _STATUS = {400: BadRequest, 401: AuthError, 404: NotFound, 409: Conflict, 410: EnvGone, 422: BadRequest, 429: Overloaded, 502: GuestError, 503: DaemonUnavailable} @@ -195,6 +197,7 @@ def __init__(self, url: str = DEFAULT_URL, token: str | None = None, timeout: fl self._opener = urllib.request.build_opener(_RedirectPolicy(self.token, self.allow_insecure_http)) 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) @@ -376,10 +379,40 @@ 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) -> "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. On a gateway without run routes it is a no-op + with one warning (strict=True raises instead).""" + return Run(self, name, kind, task_set=task_set, config=config, flush_s=flush_s, strict=strict, label=label) + + 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 +461,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 diff --git a/drums/runs.py b/drums/runs.py new file mode 100644 index 0000000..bb3b9bf --- /dev/null +++ b/drums/runs.py @@ -0,0 +1,283 @@ +"""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} -> {run_id | id, ...} + (Idempotency-Key header: a retried open returns the same run) + PATCH /v1/runs/{id} {steps: [{step, reward, zero_advantage_share, rollouts, desktops_busy, at, extra?}]} + POST /v1/runs/{id}/close {status: completed | failed | cancelled, error, steps_total} + +Buffering: `step()` only records the point; the buffer is sent at most once per `flush_s` seconds (default 30), from +inside the next `step()` call that finds the interval passed, and once more on close. A failed send keeps the +points for the next one (at most `MAX_BUFFER` points are kept; the oldest go first and are counted in `dropped`). +Nothing here raises into the training loop unless `strict=True`: a run the gateway cannot record is a warning, not +a crashed job. An AuthError (the key itself is wrong) is always raised, since every other call would fail too. + +Desktops: while a run is open, every `client.create()` / `create_many()` sends `X-Drums-Run-Label: ` (the +gateway stores it as the computer's label, shown and filterable in the console; fork children inherit it) and, +once the gateway gave the run an id, `X-Drums-Run-Id: `. +""" +from __future__ import annotations + +import atexit +import datetime as _dt +import hashlib +import json +import re +import threading +import time +import urllib.parse +import uuid +import warnings + +from .errors import AuthError, BadRequest, DrumsError, NotFound + +DEFAULT_FLUSH_S = 30.0 +MAX_BUFFER = 10_000 +LABEL_MAX = 120 # the gateway keeps at most 120 characters of a run label +RUN_KINDS = ("training", "evaluation", "rl", "scripted_test") +_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) + + +def is_uuid(v) -> bool: + return isinstance(v, str) and bool(_UUID.match(v)) + + +def config_hash(config) -> str | None: + """sha256 of the canonical JSON of `config` (sorted keys, no spaces); None when there is no config.""" + if config is None: + return None + text = json.dumps(config, sort_keys=True, separators=(",", ":"), default=str) + return hashlib.sha256(text.encode()).hexdigest() + + +def _now_iso() -> str: + return _dt.datetime.now(_dt.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") + + +class RunNotSupported(DrumsError): + """The gateway has no run routes yet (or the key lacks runs:write); raised only with strict=True.""" + + +class Run: + """One run on the gateway. Make it with `client.run(name, kind=..., ...)` (or `client.open_run`); use it as a + context manager, or call `open()` and `close()` yourself. + + `id` is the gateway's run id (None until opened, or when the gateway cannot record runs), `supported` False + when the gateway has no run routes (then every method is a no-op), `steps_total` the number of step() calls, + `last` the last point, `dropped` points lost to a full buffer.""" + + def __init__(self, client, name: str, kind: str = "training", *, task_set=None, config=None, flush_s: float = DEFAULT_FLUSH_S, + strict: bool = False, label: str | None = None, clock=time.monotonic): + if not isinstance(name, str) or not name.strip(): + raise BadRequest(400, "a run needs a name") + if kind not in RUN_KINDS: + raise BadRequest(400, f"kind must be one of {', '.join(RUN_KINDS)}; got {kind!r}") + self.client, self.name, self.kind = client, name.strip(), kind + self.task_set = task_set + self.config = config + self.config_hash = config_hash(config) + self.flush_s = float(flush_s) + self.strict = strict + self.label = (label or self.name)[:LABEL_MAX] + self.id: str | None = None + self.record: dict = {} + self.supported: bool | None = None # None: not tried yet + self.status = "new" # new -> open -> closed + self.steps_total = 0 + self.last: dict | None = None + self.dropped = 0 + self.idempotency_key = str(uuid.uuid4()) + self._buf: list = [] + self._lock = threading.Lock() + self._clock = clock + self._last_flush: float | None = None + self._warned: set = set() + self._labelled = False + self._timeout = None # per-call timeout; short at interpreter exit + + # ---- helpers ------------------------------------------------------------------------------------------------------ + def _warn(self, key: str, msg: str): + if key in self._warned: + return + self._warned.add(key) + warnings.warn(f"drums run {self.name!r}: {msg}", RuntimeWarning, stacklevel=3) + + def _unsupported(self, why: str, e: Exception | None = None): + self.supported = False + if self.strict: + raise RunNotSupported(getattr(e, "status", 0) or 0, f"the gateway cannot record runs: {why}") from e + self._warn("unsupported", f"not recorded on the gateway ({why}); training goes on, desktops still get the run label") + + def headers(self) -> dict: + """The headers a create sends while this run is open.""" + h = {"X-Drums-Run-Label": self.label} + if self.id: + h["X-Drums-Run-Id"] = self.id + return h + + # ---- lifecycle ---------------------------------------------------------------------------------------------------- + def open(self) -> "Run": + """POST /v1/runs. Idempotent. On a gateway without run routes the run is a no-op (one warning).""" + if self.status == "new": + self.status = "open" + self.client._push_run(self) + self._labelled = True + atexit.register(self._at_exit) + if self.id or self.supported is False: + return self + body = {"name": self.name, "kind": self.kind, "config": self.config, "config_hash": self.config_hash, "label": self.label} + if self.task_set is not None: + body["task_set_id" if is_uuid(self.task_set) else "task_set"] = self.task_set + try: + r = self.client.call("POST", "/v1/runs", body, headers={"Idempotency-Key": self.idempotency_key}, + timeout=self._timeout) + except AuthError: + self.status = "closed" + self._release() + raise + except (BadRequest, NotFound) as e: # 400/404/405/422: today's gateway (RunSpec only) or a plain drumsd + self._unsupported(f"POST /v1/runs answered {e.status}: {e.message}", e) + return self + except DrumsError as e: + if e.status == 403: + self._unsupported(f"forbidden: {e.message} (the key needs runs:write)", e) + return self + if self.strict: + raise + self._warn("open", f"could not open the run yet ({e}); retrying at the next flush") + return self + rid = (r or {}).get("run_id") or (r or {}).get("id") if isinstance(r, dict) else None + if not rid: + self._unsupported("POST /v1/runs gave no run id") + return self + self.id, self.record, self.supported = str(rid), r, True + return self + + def step(self, step: int, reward: float | None = None, zero_advantage_share: float | None = None, rollouts: int | None = None, + desktops_busy: int | None = None, **extra) -> None: + """Record one trainer step. Sent with the others at most once per `flush_s` seconds (and on close).""" + if self.status == "closed": + self._warn("closed", "step() after close() is ignored") + return + if self.status == "new": + self.open() + point = {"step": int(step), "at": _now_iso()} + for k, v in (("reward", reward), ("zero_advantage_share", zero_advantage_share), ("rollouts", rollouts), ("desktops_busy", desktops_busy)): + if v is not None: + point[k] = v + if extra: + point["extra"] = extra + with self._lock: + self.steps_total += 1 + self.last = point + if self.supported is False: + return + self._buf.append(point) + if len(self._buf) > MAX_BUFFER: + over = len(self._buf) - MAX_BUFFER + del self._buf[:over] + self.dropped += over + due = self._last_flush is None or self._clock() - self._last_flush >= self.flush_s + if due: + self.flush() + + def flush(self) -> bool: + """Send the buffered points now (PATCH /v1/runs/{id}). True when nothing is left to send.""" + if self.supported is False: + return True + if not self.id: + self.open() + if not self.id: + self._last_flush = self._clock() + return self.supported is False + with self._lock: + pts, self._buf = self._buf, [] + self._last_flush = self._clock() + if not pts: + return True + try: + self.client.call("PATCH", f"/v1/runs/{urllib.parse.quote(self.id)}", {"steps": pts}, timeout=self._timeout) + return True + except AuthError: + raise + except (BadRequest, NotFound) as e: + if e.status in (404, 405) and "method not allowed" in str(e.message): + self._unsupported(f"PATCH /v1/runs/{{id}} answered {e.status}: {e.message}", e) + return True + with self._lock: + self._buf[:0] = pts + if self.strict: + raise + self._warn("flush", f"could not send steps ({e}); keeping them for the next flush") + return False + except DrumsError as e: + with self._lock: + self._buf[:0] = pts + if self.strict: + raise + self._warn("flush", f"could not send steps ({e}); keeping them for the next flush") + return False + + def close(self, status: str = "completed", error: str | None = None) -> None: + """Flush, then POST /v1/runs/{id}/close. Idempotent. `status`: completed, failed or cancelled.""" + if status not in ("completed", "failed", "cancelled"): + raise BadRequest(400, f"status must be completed, failed or cancelled; got {status!r}") + if self.status == "closed": + return + try: + if self.status == "new": + return + self.flush() + if self.id and self.supported: + body = {"status": status, "error": (error or None) and str(error)[:1000], "steps_total": self.steps_total} + try: + self.client.call("POST", f"/v1/runs/{urllib.parse.quote(self.id)}/close", body, timeout=self._timeout) + except AuthError: + raise + except DrumsError as e: + if self.strict: + raise + self._warn("close", f"could not close the run on the gateway ({e}); it stays open there until it times out") + finally: + self.status = "closed" + self._release() + + def _release(self): + if self._labelled: + self.client._pop_run(self) + self._labelled = False + try: + atexit.unregister(self._at_exit) + except Exception: # noqa: BLE001 + pass + + def _at_exit(self): + # bounded: a gateway that does not answer must not hang the exit + self._timeout = 10.0 + try: + self.close("failed", "the process exited without closing the run") + except Exception: # noqa: BLE001 + pass + + def __enter__(self) -> "Run": + return self.open() + + def __exit__(self, et, ev, tb): + if et is None: + self.close("completed") + elif issubclass(et, KeyboardInterrupt): + self.close("cancelled", "KeyboardInterrupt") + else: + self.close("failed", f"{et.__name__}: {ev}") + return False + + def __repr__(self): + return f"" diff --git a/tests/test_runs.py b/tests/test_runs.py new file mode 100644 index 0000000..16394ae --- /dev/null +++ b/tests/test_runs.py @@ -0,0 +1,296 @@ +"""The run object (A-36): open on POST /v1/runs, buffered steps flushed at most once per flush_s by PATCH +/v1/runs/{id}, close on POST /v1/runs/{id}/close, the run label on creates while it is open, and a no-op with one +warning against a gateway that does not have these routes yet (today's gateway answers 400 to a training body and +404 "method not allowed" to PATCH). Localhost fakes only.""" +import json +import os +import sys +import threading +import unittest +import warnings +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) +import drums # noqa: E402 +from drums import runs # noqa: E402 + +TOKEN = "t" * 43 +RUN_ID = "7d4f0c1e-3b9a-4c55-9a1e-2f6b8c0d1e2f" + + +class Gw(BaseHTTPRequestHandler): + mode = "w3" # "w3": the run routes exist; "today": the 0.3 gateway; "down": 503 on runs + calls = [] + + def log_message(self, *a): + pass + + def _reply(self, code, obj): + b = json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Length", str(len(b))) + self.end_headers() + self.wfile.write(b) + + def _handle(self): + n = int(self.headers.get("Content-Length") or 0) + body = json.loads(self.rfile.read(n)) if n else None + Gw.calls.append({"method": self.command, "path": self.path, "body": body, "headers": dict(self.headers)}) + if self.headers.get("Authorization") != f"Bearer {TOKEN}": + return self._reply(401, {"error": "missing, invalid, revoked or expired API key", "code": "unauthenticated"}) + if self.path == "/v1/slots" and self.command == "POST": + return self._reply(201, {"id": f"c{len(Gw.calls)}", "state": "ready", "episode": 1, "validity": {"verdict": "pending"}}) + if self.path.startswith("/v1/runs"): + if Gw.mode == "down": + return self._reply(503, {"error": "the service is busy", "code": "retryable_infrastructure_failure"}) + if Gw.mode == "noscope": + return self._reply(403, {"error": "this key does not have the scope for this call", "code": "forbidden"}) + if Gw.mode == "today": + if self.command == "POST" and self.path == "/v1/runs": + return self._reply(400, {"error": "invalid run spec: task_ids Required", "code": "invalid_request"}) + return self._reply(404, {"error": "method not allowed on this path", "code": "not_found"}) + if self.command == "POST" and self.path == "/v1/runs": + return self._reply(201, {"run_id": RUN_ID, "status": "running", "created": True}) + if self.command == "PATCH" and self.path == f"/v1/runs/{RUN_ID}": + return self._reply(200, {"run_id": RUN_ID, "steps_recorded": len(body["steps"])}) + if self.command == "POST" and self.path == f"/v1/runs/{RUN_ID}/close": + return self._reply(200, {"run_id": RUN_ID, "status": body["status"]}) + if self.command == "GET" and self.path == f"/v1/runs/{RUN_ID}": + return self._reply(200, {"run": {"id": RUN_ID}}) + return self._reply(404, {"error": "no such route", "code": "not_found"}) + + do_GET = do_POST = do_PATCH = do_DELETE = _handle + + +class Clock: + def __init__(self): + self.t = 1000.0 + + def __call__(self): + return self.t + + +class RunObject(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.srv = ThreadingHTTPServer(("127.0.0.1", 0), Gw) + threading.Thread(target=cls.srv.serve_forever, daemon=True).start() + cls.url = f"http://127.0.0.1:{cls.srv.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.srv.shutdown() + + def setUp(self): + Gw.calls.clear() + Gw.mode = "w3" + self.c = drums.Client(self.url, TOKEN, retry_s=0.2) + + def calls(self, method, path_part): + return [c for c in Gw.calls if c["method"] == method and path_part in c["path"]] + + def run_obj(self, **kw): + clock = Clock() + r = runs.Run(self.c, "qwen27b-d2", "training", task_set="0b5c2a52-77a0-4c0e-9a39-0a7a0f3c1d10", config={"lr": 1e-5, "k": 6}, + clock=clock, **kw) + return r, clock + + def test_open_step_flush_close(self): + r, clock = self.run_obj() + with r: + self.assertEqual(r.id, RUN_ID) + r.step(0, reward=0.25, zero_advantage_share=0.5, rollouts=64, desktops_busy=40) # first point: sent at once + for i in range(1, 6): + clock.t += 5 + r.step(i, reward=0.3) # inside 30 s: buffered + self.assertEqual(len(self.calls("PATCH", "/v1/runs/")), 1) + clock.t += 30 + r.step(6, reward=0.4) # 30 s later: one flush + self.assertEqual(len(self.calls("PATCH", "/v1/runs/")), 2) + r.step(7, reward=0.5) + patches = self.calls("PATCH", "/v1/runs/") + self.assertEqual(len(patches), 3) # the last one on close + sent = [p["step"] for c in patches for p in c["body"]["steps"]] + self.assertEqual(sent, list(range(8))) + first = patches[0]["body"]["steps"][0] + self.assertEqual({k: first[k] for k in ("step", "reward", "zero_advantage_share", "rollouts", "desktops_busy")}, + {"step": 0, "reward": 0.25, "zero_advantage_share": 0.5, "rollouts": 64, "desktops_busy": 40}) + self.assertTrue(first["at"].endswith("Z")) + opened = self.calls("POST", "/v1/runs")[0] + self.assertEqual(opened["path"], "/v1/runs") + self.assertEqual(opened["body"]["kind"], "training") + self.assertEqual(opened["body"]["task_set_id"], "0b5c2a52-77a0-4c0e-9a39-0a7a0f3c1d10") + self.assertEqual(opened["body"]["config_hash"], runs.config_hash({"k": 6, "lr": 1e-5})) # key order does not matter + self.assertTrue(opened["headers"].get("Idempotency-Key")) + closed = self.calls("POST", "/close") + self.assertEqual(len(closed), 1) + self.assertEqual(closed[0]["body"], {"status": "completed", "error": None, "steps_total": 8}) + self.assertEqual(r.status, "closed") + + def test_never_more_than_one_flush_per_interval(self): + r, clock = self.run_obj() + r.open() + for i in range(1000): + clock.t += 0.1 # 100 s of steps, 10 per second + r.step(i, reward=0.1) + self.assertLessEqual(len(self.calls("PATCH", "/v1/runs/")), 1 + 100 // 30) + r.close() + self.assertEqual(sum(len(c["body"]["steps"]) for c in self.calls("PATCH", "/v1/runs/")), 1000) + + def test_an_exception_closes_the_run_failed_and_propagates(self): + r, _ = self.run_obj() + with self.assertRaises(ValueError): + with r: + r.step(0, reward=0.0) + raise ValueError("trainer blew up") + body = self.calls("POST", "/close")[0]["body"] + self.assertEqual(body["status"], "failed") + self.assertIn("ValueError: trainer blew up", body["error"]) + + def test_keyboard_interrupt_is_cancelled(self): + r, _ = self.run_obj() + with self.assertRaises(KeyboardInterrupt): + with r: + raise KeyboardInterrupt + self.assertEqual(self.calls("POST", "/close")[0]["body"]["status"], "cancelled") + + def test_creates_inside_the_run_carry_its_label_and_id(self): + self.c.create() + with self.c.run("label-me", kind="training", config={}) as r: + self.c.create() + with self.c.run("inner", kind="evaluation"): + self.c.create() + self.c.create() + self.c.create() + creates = [c["headers"] for c in self.calls("POST", "/v1/slots")] + self.assertEqual([h.get("X-Drums-Run-Label") for h in creates], [None, "label-me", "inner", "label-me", None]) + self.assertEqual(creates[1].get("X-Drums-Run-Id"), RUN_ID) + self.assertIsInstance(r, drums.Run) + + def test_on_todays_gateway_it_is_a_noop_with_one_warning_and_labels_still_apply(self): + Gw.mode = "today" + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + with self.c.run("d2", kind="training", task_set="factory-v1") as r: + for i in range(50): + r.step(i, reward=0.5) + self.c.create() + msgs = [str(x.message) for x in w if issubclass(x.category, RuntimeWarning)] + self.assertEqual(len(msgs), 1, msgs) + self.assertIn("not recorded on the gateway", msgs[0]) + self.assertFalse(r.supported) + self.assertIsNone(r.id) + self.assertEqual(r.steps_total, 50) + self.assertEqual(len(self.calls("POST", "/v1/runs")), 1) # tried once, never again + self.assertEqual(self.calls("PATCH", "/v1/runs"), []) + self.assertEqual(self.calls("POST", "/v1/runs")[0]["body"]["task_set"], "factory-v1") # a name, not an id + self.assertEqual(self.calls("POST", "/v1/slots")[0]["headers"].get("X-Drums-Run-Label"), "d2") + + def test_strict_raises_on_todays_gateway(self): + Gw.mode = "today" + with self.assertRaises(drums.RunNotSupported): + with self.c.run("d2", kind="training", strict=True): + pass + + def test_a_key_without_runs_write_is_a_warning(self): + Gw.mode = "noscope" + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + with self.c.run("d2", kind="training") as r: + r.step(0) + self.assertFalse(r.supported) + self.assertIn("runs:write", str(w[0].message)) + + def test_a_gateway_that_is_down_keeps_the_points_and_opens_later(self): + Gw.mode = "down" + r, clock = self.run_obj() + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + r.open() + r.step(0, reward=0.1) + r.step(1, reward=0.2) + self.assertIsNone(r.id) + self.assertIsNone(r.supported) + Gw.mode = "w3" + clock.t += 31 + r.step(2, reward=0.3) + self.assertEqual(r.id, RUN_ID) + self.assertEqual([p["step"] for p in self.calls("PATCH", "/v1/runs/")[0]["body"]["steps"]], [0, 1, 2]) + r.close() + + def test_a_failed_flush_keeps_the_points(self): + r, clock = self.run_obj() + r.open() + Gw.mode = "down" + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + r.step(0, reward=0.1) + Gw.mode = "w3" + clock.t += 31 + r.step(1, reward=0.2) + ok = [c for c in self.calls("PATCH", "/v1/runs/")][-1] + self.assertEqual([p["step"] for p in ok["body"]["steps"]], [0, 1]) + r.close() + + def test_the_buffer_is_bounded(self): + Gw.mode = "down" + r, _ = self.run_obj() + old = runs.MAX_BUFFER + runs.MAX_BUFFER = 5 + try: + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + for i in range(12): + r.step(i) + finally: + runs.MAX_BUFFER = old + self.assertEqual(len(r._buf), 5) + self.assertEqual(r.dropped, 7) + self.assertEqual(r.last["step"], 11) + + def test_client_run_with_a_uuid_alone_is_the_03_read(self): + self.assertEqual(self.c.run(RUN_ID), {"run": {"id": RUN_ID}}) + self.assertEqual(self.c.get_run(RUN_ID), {"run": {"id": RUN_ID}}) + self.assertIsInstance(self.c.run("my-run"), drums.Run) # a name: a Run (not opened yet) + self.assertIsInstance(self.c.run(RUN_ID, kind="training"), drums.Run) + self.assertEqual(Gw.calls[-1]["method"], "GET") # building a Run sends nothing + + def test_bad_arguments(self): + with self.assertRaises(drums.BadRequest): + self.c.open_run("", kind="training") + with self.assertRaises(drums.BadRequest): + self.c.open_run("x", kind="pretraining") + r = self.c.open_run("x") + with self.assertRaises(drums.BadRequest): + r.close("exploded") + + def test_close_is_idempotent_and_step_after_close_is_ignored(self): + r, _ = self.run_obj() + with r: + r.step(0) + r.close() + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + r.step(1) + self.assertEqual(len(self.calls("POST", "/close")), 1) + self.assertIn("after close", str(w[0].message)) + + def test_process_exit_closes_an_open_run_failed_with_a_short_timeout(self): + r, _ = self.run_obj() + r.open() + r.step(0) + r._at_exit() + self.assertEqual(r._timeout, 10.0) + body = self.calls("POST", "/close")[0]["body"] + self.assertEqual(body["status"], "failed") + self.assertIn("without closing", body["error"]) + + def test_a_wrong_key_raises(self): + c = drums.Client(self.url, "wrong", retry_s=0.2) + with self.assertRaises(drums.AuthError): + with c.run("x", kind="training"): + pass + + +if __name__ == "__main__": + unittest.main() From 2778f8cc438f5da5cc3f85bfb161934111aa150c Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:04:49 -0500 Subject: [PATCH 05/23] drums preflight: check gateway, console, key, scopes, host capacity, admission, rate limit, quota, spend cap and task set before a run; drums.preflight() in Python --- drums/__init__.py | 5 +- drums/_preflight.py | 517 ++++++++++++++++++++++++++++++++++++++++ drums/cli.py | 6 + tests/test_preflight.py | 306 ++++++++++++++++++++++++ 4 files changed, 833 insertions(+), 1 deletion(-) create mode 100644 drums/_preflight.py create mode 100644 tests/test_preflight.py diff --git a/drums/__init__.py b/drums/__init__.py index 35ee461..ab8e9d0 100644 --- a/drums/__init__.py +++ b/drums/__init__.py @@ -55,7 +55,7 @@ __all__ = ["ActionFailed", "connect", "Client", "Env", "Reward", "Observation", "StepResult", "State", "ForkResult", "env", "__version__", "DrumsError", "AuthError", "BadRequest", "NotFound", "EnvGone", "Conflict", "DaemonUnavailable", "GuestError", "EnvFailed", "RestoreFailed", "GateFailed", "TaskSetupFailed", "ForkError", "BatchError", "InvalidEpisode", "CheckerError", "NotQuiescent", "Overloaded", - "CheckpointStale", "TaskUnsupported", "InsecureTransport", "RedirectRefused", "check_transport"] + "CheckpointStale", "TaskUnsupported", "InsecureTransport", "RedirectRefused", "check_transport", "preflight", "PreflightReport"] _STATUS = {400: BadRequest, 401: AuthError, 404: NotFound, 409: Conflict, 410: EnvGone, 422: BadRequest, 429: Overloaded, 502: GuestError, 503: DaemonUnavailable} @@ -878,3 +878,6 @@ 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) diff --git a/drums/_preflight.py b/drums/_preflight.py new file mode 100644 index 0000000..eee6633 --- /dev/null +++ b/drums/_preflight.py @@ -0,0 +1,517 @@ +"""`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) + scopes computers:read + computers:write (required); runs:write (run object), usage:read (cost) 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`, a read-only summary the gateway does not serve +yet (expected shape in `_limits_view`). Until it does, 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") +WANTED_SCOPES = {"runs:write": "the run object (client.run) cannot record the run", + "usage:read": "usage and cost reads 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` (a proposal; any of them may be missing): + + {"workspace": {"max_live_computers", "live_computers", "max_spend_usd", "spent_usd", "period_end"}, + "rate_limit": {"per_s", "burst"}, + "price": {"desktop_hour_usd"}, + "host": {"id", "status", "max_desktops", "live"}} + """ + 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"), + } + + +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) + console = (console_url or os.environ.get("DRUMS_CONSOLE_URL") or DEFAULT_CONSOLE_URL).rstrip("/") + links = _Links(console, workspace or os.environ.get("DRUMS_WORKSPACE")) + 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 "" + 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 + + # ---- 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(Check("auth", PASS, f"key {key_row.get('name') or m.group(1)!s} accepted" + (f", expires {exp}" if exp else ", no expiry"))) + 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(Check("auth", PASS, "the key is accepted")) + 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: + 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 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 + if health.get("ok") is False: + 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 ""))) + + # 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")) + 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 _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: + 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/tests/test_preflight.py b/tests/test_preflight.py new file mode 100644 index 0000000..b0a7e91 --- /dev/null +++ b/tests/test_preflight.py @@ -0,0 +1,306 @@ +"""`drums preflight` / drums.preflight against a localhost fake gateway: today's gateway (no GET /v1/limits: those rows +say "not checked" and never fail), a gateway with the limits summary (every row decided), each failure with its fix +and link, the exit codes, --json, and no token in any output.""" +import contextlib +import datetime as dt +import io +import json +import os +import sys +import threading +import time +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) +import drums # noqa: E402 +from drums import _preflight as pf, cli # noqa: E402 + +PREFIX = "abcdefghijkl" +TOKEN = f"drums_sk_{PREFIX}_" + "Q" * 43 +TS = "0b5c2a52-77a0-4c0e-9a39-0a7a0f3c1d10" + + +def iso(hours_from_now): + return (dt.datetime.now(dt.timezone.utc) + dt.timedelta(hours=hours_from_now)).isoformat() + + +class Gw(BaseHTTPRequestHandler): + state = {} + + def log_message(self, *a): + pass + + def _reply(self, code, obj): + b = json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Length", str(len(b))) + self.end_headers() + self.wfile.write(b) + + def do_GET(self): + st = Gw.state + if self.path == "/sign-in": + return self._reply(st.get("console", 200), {}) + if self.headers.get("Authorization") != f"Bearer {TOKEN}": + return self._reply(401, {"error": "missing, invalid, revoked or expired API key", "code": "unauthenticated"}) + if st.get("binding"): + return self._reply(403, {"error": "this endpoint serves another compute pool", "code": "forbidden"}) + if self.path == "/v1/health": + time.sleep(st.get("health_delay", 0)) + return self._reply(200, {"ok": st.get("ok", True), "version": "0.4.3", "checkpoints": st.get("checkpoints", [{"id": "osworld-ubuntu", "stale_reason": None}]), + "capacity": {"live": st.get("live", 10), "max": st.get("max", 200)}}) + if self.path == "/v1/api-keys": + row = {"id": "k1", "name": "trainer", "prefix": PREFIX, "scopes": st.get("scopes", ["computers:read", "computers:write", "runs:write", "usage:read"]), + "expires_at": st.get("expires_at"), "revoked_at": None} + return self._reply(200, {"items": [{"id": "k0", "prefix": "zzzzzzzzzzzz", "scopes": []}, row]}) + if self.path == "/v1/limits": + if "limits" not in st: + return self._reply(404, {"error": "no such route", "code": "not_found"}) + return self._reply(200, st["limits"]) + if self.path.startswith("/v1/task-sets/"): + if self.path.endswith(TS) and "task_set" in st: + return self._reply(200, st["task_set"]) + return self._reply(404, {"error": "no such task set", "code": "not_found"}) + if self.path.startswith("/v1/task-sets"): + return self._reply(200, {"items": [st["task_set"]] if "task_set" in st else [], "next_cursor": None}) + return self._reply(404, {"error": "no such route", "code": "not_found"}) + + +LIMITS = {"workspace": {"max_live_computers": 256, "live_computers": 10, "max_spend_usd": 500, "spent_usd": 40}, + "rate_limit": {"per_s": 600, "burst": 1800}, "price": {"desktop_hour_usd": 0.1}, "host": {"id": "drums-prod-2", "status": "active"}} +VALID_SET = {"id": TS, "name": "factory-v1", "task_count": 48, "validation": {"host_id": "drums-prod-2", "accepted": 48, "rejected": 0, "at": "2026-11-16T05:00:00Z"}} + + +class Preflight(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.srv = ThreadingHTTPServer(("127.0.0.1", 0), Gw) + threading.Thread(target=cls.srv.serve_forever, daemon=True).start() + cls.url = f"http://127.0.0.1:{cls.srv.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.srv.shutdown() + + def setUp(self): + Gw.state = {} + + def pre(self, n=128, h=3.0, **kw): + kw.setdefault("check_console", False) + return drums.preflight(n, h, url=self.url, token=kw.pop("token", TOKEN), **kw) + + def row(self, rep, name): + hits = [c for c in rep.checks if c.name == name] + self.assertEqual(len(hits), 1, [c.name for c in rep.checks]) + return hits[0] + + def test_todays_gateway_passes_what_it_can_and_says_what_it_could_not_check(self): + rep = self.pre(16, 2.0) + self.assertTrue(rep.ok, rep.table()) + for name in ("gateway", "auth", "scopes", "host capacity", "admission"): + self.assertEqual(self.row(rep, name).status, "pass", name) + for name in ("rate limit", "quota", "spend cap"): + c = self.row(rep, name) + self.assertEqual(c.status, "not checked", name) + self.assertIn("does not publish GET /v1/limits", c.detail) + self.assertEqual(rep.exit_code(), 0) + self.assertEqual(rep.exit_code(strict=True), 1) + self.assertIn("3 could not be checked", rep.table()) + + def test_the_rate_rule_is_explicit(self): + self.assertEqual(pf.REQUESTS_PER_DESKTOP_S, 0.5) + rep = self.pre(128, 1.0) + self.assertEqual(rep.need["requests_per_s"], 64.0) + c = self.row(rep, "rate limit") + self.assertEqual(c.status, "warn") # 64 req/s > the 20/s default and nobody can tell us the real one + self.assertIn("64 req/s", c.detail) + self.assertIn("20 req/s", c.detail) + + def test_with_the_limits_summary_every_row_is_decided(self): + Gw.state = {"limits": LIMITS, "task_set": VALID_SET} + rep = self.pre(128, 3.0, task_set=TS) + self.assertTrue(rep.ok, rep.table()) + self.assertEqual({c.status for c in rep.checks}, {"pass"}, rep.table()) + self.assertEqual(rep.need["projected_desktop_usd"], 38.4) + self.assertEqual(rep.exit_code(strict=True), 0) + + def test_each_limit_fails_with_its_fix_and_link(self): + Gw.state = {"limits": {**LIMITS, "rate_limit": {"per_s": 20, "burst": 60}, "workspace": {"max_live_computers": 10, "live_computers": 0, + "max_spend_usd": 100, "spent_usd": 90}}} + rep = self.pre(128, 3.0, workspace="acme", console_url="https://console.example") + self.assertFalse(rep.ok) + for name, words in (("rate limit", "64 req/s"), ("quota", "10 live desktops"), ("spend cap", "cap 100.00")): + c = self.row(rep, name) + self.assertEqual(c.status, "fail", name) + self.assertIn(words, c.detail) + self.assertTrue(c.fix) + self.assertEqual(c.link, "https://console.example/w/acme/usage") + self.assertEqual(rep.exit_code(), 1) + self.assertIn("To do:", rep.table()) + + def test_the_price_flag_projects_the_cost(self): + rep = self.pre(128, 3.0, desktop_hour_usd=0.25) + c = self.row(rep, "spend cap") + self.assertEqual(c.status, "not checked") + self.assertIn("96.00 USD", c.detail) + self.assertEqual(rep.need["projected_desktop_usd"], 96.0) + + def test_host_capacity_and_admission(self): + Gw.state = {"live": 150, "max": 200} + self.assertEqual(self.row(self.pre(128), "host capacity").status, "fail") + Gw.state = {"ok": False} + self.assertEqual(self.row(self.pre(8), "admission").status, "fail") + Gw.state = {"checkpoints": [{"id": "osworld-ubuntu", "stale_reason": "runtime changed"}]} + self.assertEqual(self.row(self.pre(8), "admission").status, "warn") + Gw.state = {"limits": {**LIMITS, "host": {"id": "drums-prod-2", "status": "draining"}}} + self.assertEqual(self.row(self.pre(8), "admission").status, "fail") + + def test_key_expiring_during_the_run_or_missing_scopes(self): + Gw.state = {"expires_at": iso(1)} + c = self.row(self.pre(8, 3.0), "auth") + self.assertEqual(c.status, "fail") + self.assertIn("expires in", c.detail) + Gw.state = {"expires_at": iso(100)} + self.assertEqual(self.row(self.pre(8, 3.0), "auth").status, "pass") + Gw.state = {"scopes": ["computers:read"]} + self.assertEqual(self.row(self.pre(8), "scopes").status, "fail") + Gw.state = {"scopes": ["computers:read", "computers:write"]} + c = self.row(self.pre(8), "scopes") + self.assertEqual(c.status, "warn") + self.assertIn("runs:write", c.detail) + + def test_a_wrong_key_or_another_workspace(self): + rep = self.pre(8, token=f"drums_sk_{PREFIX}_" + "X" * 43) + self.assertEqual(self.row(rep, "auth").status, "fail") + self.assertFalse(rep.ok) + Gw.state = {"binding": True} + c = self.row(self.pre(8), "auth") + self.assertEqual(c.status, "fail") + self.assertIn("another compute pool", c.detail) + + def test_unreachable_gateway(self): + rep = drums.preflight(8, 1.0, url="http://127.0.0.1:9", token=TOKEN, check_console=False) + self.assertEqual(self.row(rep, "gateway").status, "fail") + self.assertEqual(self.row(rep, "auth").status, "not checked") + + def test_slow_control_plane_warns(self): + Gw.state = {"health_delay": 0.3} + old = pf.HEALTH_SLOW_S + pf.HEALTH_SLOW_S = 0.1 + try: + self.assertEqual(self.row(self.pre(8), "gateway").status, "warn") + finally: + pf.HEALTH_SLOW_S = old + + def test_task_set(self): + self.assertEqual(self.row(self.pre(8, task_set=TS), "task set").status, "fail") # not registered + Gw.state = {"task_set": {**VALID_SET, "validation": None}} + c = self.row(self.pre(8, task_set=TS), "task set") + self.assertEqual(c.status, "fail") + self.assertIn("never validated", c.detail) + Gw.state = {"task_set": {**VALID_SET, "validation": {**VALID_SET["validation"], "rejected": 2}}} + self.assertEqual(self.row(self.pre(8, task_set=TS), "task set").status, "fail") + Gw.state = {"task_set": VALID_SET} + c = self.row(self.pre(8, task_set="factory-v1"), "task set") # by name + self.assertEqual(c.status, "pass") + self.assertIn("could not be compared", c.detail) + Gw.state = {"task_set": VALID_SET, "limits": {**LIMITS, "host": {"id": "drums-rc1", "status": "active"}}} + self.assertEqual(self.row(self.pre(8, task_set=TS), "task set").status, "warn") + + def test_console_row(self): + rep = self.pre(8, check_console=True, console_url=self.url) + self.assertEqual(self.row(rep, "console").status, "pass") + Gw.state = {"console": 502} + self.assertEqual(self.row(self.pre(8, check_console=True, console_url=self.url), "console").status, "fail") + + def test_model_gpus(self): + self.assertEqual(pf.parse_model_gpus("2:6"), {"inference": 2, "trainer": 6, "total": 8}) + self.assertEqual(pf.parse_model_gpus("8")["total"], 8) + with self.assertRaises(ValueError): + pf.parse_model_gpus("lots") + rep = self.pre(128, 2.0, model_gpus="2:6", gpu_hour_usd=4.0) + c = self.row(rep, "model GPUs") + self.assertEqual(c.status, "info") + self.assertEqual(rep.need["projected_gpu_usd"], 64.0) + + def test_bad_arguments(self): + with self.assertRaises(ValueError): + drums.preflight(0, 1.0, url=self.url, token=TOKEN) + with self.assertRaises(ValueError): + drums.preflight(8, 0, url=self.url, token=TOKEN) + + +def cli_run(argv, env): + out, err = io.StringIO(), io.StringIO() + keys = ("DRUMS_TOKEN", "DRUMS_URL", "DRUMS_TOKEN_FILE", "DRUMS_CONSOLE_URL", "DRUMS_WORKSPACE") + saved = {k: os.environ.get(k) for k in keys} + for k in keys: + os.environ.pop(k, None) + os.environ.update(env) + try: + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + rc = cli.main(argv) + finally: + for k, v in saved.items(): + if v is None: + os.environ.pop(k, None) + else: + os.environ[k] = v + return rc, out.getvalue(), err.getvalue() + + +class PreflightCli(Preflight.__base__): + @classmethod + def setUpClass(cls): + Preflight.setUpClass.__func__(cls) + + @classmethod + def tearDownClass(cls): + cls.srv.shutdown() + + def setUp(self): + Gw.state = {} + + def test_table_and_exit_codes(self): + env = {"DRUMS_URL": self.url, "DRUMS_TOKEN": TOKEN} + rc, out, err = cli_run(["preflight", "--desktops", "16", "--hours", "2", "--no-console"], env) + self.assertEqual(rc, 0, out + err) + self.assertIn("CHECK", out) + self.assertIn("NOT CHECKED", out) + rc, _, _ = cli_run(["preflight", "--desktops", "16", "--hours", "2", "--no-console", "--strict"], env) + self.assertEqual(rc, 1) + Gw.state = {"live": 199} + rc, out, _ = cli_run(["preflight", "--desktops", "16", "--hours", "2", "--no-console"], env) + self.assertEqual(rc, 1) + self.assertIn("FAIL", out) + self.assertNotIn(TOKEN, out) + self.assertNotIn("Q" * 8, out) + + def test_json(self): + Gw.state = {"limits": LIMITS} + rc, out, _ = cli_run(["preflight", "--desktops", "128", "--hours", "3", "--no-console", "--json", "--model-gpus", "2:6"], + {"DRUMS_URL": self.url, "DRUMS_TOKEN": TOKEN}) + self.assertEqual(rc, 0) + d = json.loads(out) + self.assertTrue(d["ok"]) + self.assertEqual(d["need"]["requests_per_s"], 64.0) + self.assertEqual([c["name"] for c in d["checks"]][:2], ["gateway", "auth"]) + self.assertNotIn(TOKEN, out) + + def test_usage_errors_exit_2(self): + rc, _, err = cli_run(["preflight", "--desktops", "8", "--hours", "1"], {"DRUMS_TOKEN": TOKEN}) + self.assertEqual(rc, 2) + self.assertIn("DRUMS_URL", err) + rc, _, err = cli_run(["preflight", "--desktops", "8", "--hours", "1"], {"DRUMS_URL": self.url}) + self.assertEqual(rc, 2) + self.assertIn("DRUMS_TOKEN", err) + rc, _, err = cli_run(["preflight", "--desktops", "8", "--hours", "1", "--model-gpus", "x"], {"DRUMS_URL": self.url, "DRUMS_TOKEN": TOKEN}) + self.assertEqual(rc, 2) + rc, _, err = cli_run(["preflight", "--desktops", "8", "--hours", "1"], {"DRUMS_URL": "http://gw.example/gw", "DRUMS_TOKEN": TOKEN}) + self.assertEqual(rc, 2) + self.assertNotIn(TOKEN, err) + + +if __name__ == "__main__": + unittest.main() From 381ec676d96df3692b25212a87c326ee1eb43cc2 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:05:17 -0500 Subject: [PATCH 06/23] client: export RetryPolicy and CertificateError next to their definitions --- drums/__init__.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/drums/__init__.py b/drums/__init__.py index f559402..a90ce4c 100644 --- a/drums/__init__.py +++ b/drums/__init__.py @@ -67,7 +67,7 @@ __all__ = ["ActionFailed", "connect", "Client", "Env", "Reward", "Observation", "StepResult", "State", "ForkResult", "env", "__version__", "DrumsError", "AuthError", "BadRequest", "NotFound", "EnvGone", "Conflict", "DaemonUnavailable", "GuestError", "EnvFailed", "RestoreFailed", "GateFailed", "TaskSetupFailed", "ForkError", "BatchError", "InvalidEpisode", "CheckerError", "NotQuiescent", "Overloaded", - "CheckpointStale", "TaskUnsupported", "InsecureTransport", "RedirectRefused", "check_transport", "RetryPolicy", "CertificateError"] + "CheckpointStale", "TaskUnsupported", "InsecureTransport", "RedirectRefused", "check_transport"] _STATUS = {400: BadRequest, 401: AuthError, 404: NotFound, 409: Conflict, 410: EnvGone, 422: BadRequest, 429: Overloaded, 502: GuestError, 503: DaemonUnavailable} @@ -193,6 +193,9 @@ def __repr__(self): 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 From 3bc0cf2560c35fe4180ea4511daf6d349c0a4533 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:05:28 -0500 Subject: [PATCH 07/23] runs: export Run and RunNotSupported on their own line --- drums/__init__.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drums/__init__.py b/drums/__init__.py index 65715a5..ec0d964 100644 --- a/drums/__init__.py +++ b/drums/__init__.py @@ -57,7 +57,9 @@ __all__ = ["ActionFailed", "connect", "Client", "Env", "Reward", "Observation", "StepResult", "State", "ForkResult", "env", "__version__", "DrumsError", "AuthError", "BadRequest", "NotFound", "EnvGone", "Conflict", "DaemonUnavailable", "GuestError", "EnvFailed", "RestoreFailed", "GateFailed", "TaskSetupFailed", "ForkError", "BatchError", "InvalidEpisode", "CheckerError", "NotQuiescent", "Overloaded", - "CheckpointStale", "TaskUnsupported", "InsecureTransport", "RedirectRefused", "check_transport", "Run", "RunNotSupported"] + "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} From b84b047968802f5da628fb82b13ee997670bb458 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:05:34 -0500 Subject: [PATCH 08/23] preflight: export preflight and PreflightReport at the end of the module --- drums/__init__.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drums/__init__.py b/drums/__init__.py index ab8e9d0..0052d7d 100644 --- a/drums/__init__.py +++ b/drums/__init__.py @@ -55,7 +55,7 @@ __all__ = ["ActionFailed", "connect", "Client", "Env", "Reward", "Observation", "StepResult", "State", "ForkResult", "env", "__version__", "DrumsError", "AuthError", "BadRequest", "NotFound", "EnvGone", "Conflict", "DaemonUnavailable", "GuestError", "EnvFailed", "RestoreFailed", "GateFailed", "TaskSetupFailed", "ForkError", "BatchError", "InvalidEpisode", "CheckerError", "NotQuiescent", "Overloaded", - "CheckpointStale", "TaskUnsupported", "InsecureTransport", "RedirectRefused", "check_transport", "preflight", "PreflightReport"] + "CheckpointStale", "TaskUnsupported", "InsecureTransport", "RedirectRefused", "check_transport"] _STATUS = {400: BadRequest, 401: AuthError, 404: NotFound, 409: Conflict, 410: EnvGone, 422: BadRequest, 429: Overloaded, 502: GuestError, 503: DaemonUnavailable} @@ -881,3 +881,5 @@ def env(task: dict | None = None, *, from_state: str | None = None, checkpoint: from ._preflight import PreflightReport, preflight # noqa: E402 (needs Client defined above) + +__all__ += ["preflight", "PreflightReport"] From 0768f9421bda79becc800d908e86b83c8c4bef3a Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:05:56 -0500 Subject: [PATCH 09/23] runs: keep the runs import next to its use --- drums/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drums/__init__.py b/drums/__init__.py index ec0d964..bcb3e6f 100644 --- a/drums/__init__.py +++ b/drums/__init__.py @@ -44,10 +44,10 @@ import threading import warnings -from . import runs as _runs from .errors import (ActionFailed, AuthError, BadRequest, BatchError, 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" From d372421307ff60046c92bae7321eb19c2104472f Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:08:22 -0500 Subject: [PATCH 10/23] preflight: a platform task set without a validation record is a warning; README section --- README.md | 31 +++++++++++++++++++++++++++++++ drums/_preflight.py | 3 +++ tests/test_preflight.py | 2 ++ 3 files changed, 36 insertions(+) diff --git a/README.md b/README.md index 256a36b..2b393c6 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 | +| auth | the key is accepted, not revoked, and does not expire before the run ends | +| scopes | `computers:read` and `computers:write` (required); `runs:write` and `usage:read` (warned) | +| host capacity, admission | the bound host has N free desktops, drumsd is ok 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 need the gateway's `GET /v1/limits` summary; a +gateway without it 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 diff --git a/drums/_preflight.py b/drums/_preflight.py index eee6633..2a65210 100644 --- a/drums/_preflight.py +++ b/drums/_preflight.py @@ -419,6 +419,9 @@ def _task_set_check(client, task_set: str, lim, links, timeout) -> Check: 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) diff --git a/tests/test_preflight.py b/tests/test_preflight.py index b0a7e91..4577a32 100644 --- a/tests/test_preflight.py +++ b/tests/test_preflight.py @@ -199,6 +199,8 @@ def test_task_set(self): c = self.row(self.pre(8, task_set=TS), "task set") self.assertEqual(c.status, "fail") self.assertIn("never validated", c.detail) + Gw.state = {"task_set": {**VALID_SET, "validation": None, "platform": True}} + self.assertEqual(self.row(self.pre(8, task_set=TS), "task set").status, "warn") # e.g. the OSWorld set Gw.state = {"task_set": {**VALID_SET, "validation": {**VALID_SET["validation"], "rejected": 2}}} self.assertEqual(self.row(self.pre(8, task_set=TS), "task set").status, "fail") Gw.state = {"task_set": VALID_SET} From 559bf69f95632010169a2ad0b746da076d5ad652 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:21:40 -0500 Subject: [PATCH 11/23] Exchange an API key for a desktop token when the gateway advertises token mode; renew before expiry and after a 401; no secret in reprs or errors --- CHANGELOG.md | 13 +++ drums/__init__.py | 140 ++++++++++++++++++++++++- tests/test_tokens.py | 224 ++++++++++++++++++++++++++++++++++++++++ tests/test_transport.py | 14 +++ 4 files changed, 389 insertions(+), 2 deletions(-) create mode 100644 tests/test_tokens.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5466c87..8708468 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,19 @@ 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. +## Unreleased + +- Desktop tokens (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. In `both` mode an + unreachable console falls back to the API key (and tries the exchange again after a minute); in `token` mode it + raises `DaemonUnavailable`, and a refused key raises `AuthError`. 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. + ## 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/drums/__init__.py b/drums/__init__.py index 35ee461..6399a40 100644 --- a/drums/__init__.py +++ b/drums/__init__.py @@ -146,6 +146,130 @@ 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) +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.""" + + 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 + + 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 + + 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 + try: + self._exchange(client, now) + except (AuthError, InsecureTransport, RedirectRefused): + raise + except DrumsError: + # 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 + 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): + 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): + url = self._token_url + origin = _origin_text(url) + opener = urllib.request.build_opener(_RedirectPolicy(self._key, client.allow_insecure_http)) + 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") + except urllib.error.HTTPError as e: + status = e.code + e.close() + if status == 401: + raise AuthError(401, f"the console at {origin} refused the API key (missing, invalid, revoked or expired)") from None + raise DaemonUnavailable(status, f"could not exchange the API key for a desktop token at {origin} (HTTP {status})") from None + except (urllib.error.URLError, ConnectionError, TimeoutError, OSError) as e: + 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": """A client for one drumsd. `url`/`token` default to $DRUMS_URL / $DRUMS_TOKEN. With check=True the token is tried @@ -193,6 +317,7 @@ 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._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.close_on_exit = close_on_exit @@ -201,6 +326,9 @@ def __init__(self, url: str = DEFAULT_URL, token: str | None = None, timeout: fl 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: @@ -269,11 +397,13 @@ def call(self, method: str, path: str, body=None, raw: bool = False, timeout: fl (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 + 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) try: with self._opener.open(req, timeout=timeout or self.timeout) as r: @@ -286,6 +416,12 @@ 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 + if e.code == 401 and self._cred.using_token and not renewed: + # the token expired, was revoked or its signing key rotated: 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 else: diff --git a/tests/test_tokens.py b/tests/test_tokens.py new file mode 100644 index 0000000..b46848a --- /dev/null +++ b/tests/test_tokens.py @@ -0,0 +1,224 @@ +"""Desktop tokens: `drums.connect(url, key)` against a gateway that advertises token mode exchanges the API key once at +the console, sends only the token to the gateway, renews it before it expires and once after a 401, falls back to the +key in `both` mode when the console is away, and never shows the key or the token in a repr or an error. +A fake gateway and a fake console on loopback; no network.""" +import json +import os +import sys +import threading +import time +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) +import drums # noqa: E402 + +KEY = "drums_sk_abcdefghijkl_" + "K" * 43 + + +class State: + mode = "token" # what the gateway advertises + console_up = True + console_status = 200 + renew_after_s = 3300 + expires_in = 3600 + issued = [] # tokens the console handed out + exchanges = 0 + revoked = set() # tokens the gateway refuses from now on + gateway_auth = [] # Authorization headers the gateway saw on /v1 + console_auth = [] + console_url = "" + + @classmethod + def reset(cls): + cls.mode, cls.console_up, cls.console_status = "token", True, 200 + cls.renew_after_s, cls.expires_in = 3300, 3600 + cls.issued, cls.exchanges, cls.revoked = [], 0, set() + cls.gateway_auth, cls.console_auth = [], [] + + +def _send(h, code, obj): + b = json.dumps(obj).encode() + h.send_response(code) + h.send_header("Content-Type", "application/json") + h.send_header("Content-Length", str(len(b))) + h.end_headers() + h.wfile.write(b) + + +class Console(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + n = int(self.headers.get("Content-Length") or 0) + self.rfile.read(n) + State.console_auth.append(self.headers.get("Authorization")) + if self.path != "/api/v1/tokens": + return _send(self, 404, {"code": "not_found"}) + if not State.console_up: + return _send(self, 503, {"code": "retryable_infrastructure_failure"}) + if self.headers.get("Authorization") != f"Bearer {KEY}" or State.console_status == 401: + return _send(self, 401, {"error": "missing, invalid, revoked or expired API key", "code": "unauthenticated"}) + State.exchanges += 1 + tok = f"eyJhbGciOiJFZERTQSJ9.eyJuIjo{State.exchanges}fQ.{'s' * 86}" + State.issued.append(tok) + _send(self, 200, {"token": tok, "token_type": "Bearer", "expires_in": State.expires_in, "renew_after_s": State.renew_after_s, + "expires_at": "2026-11-17T20:00:00Z", "workspace_id": "w", "hosts": []}) + + +class Gateway(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def _auth_ok(self): + a = self.headers.get("Authorization") or "" + State.gateway_auth.append(a) + tok = a[len("Bearer "):] + if State.mode == "token": + return tok in State.issued and tok not in State.revoked + if State.mode == "both": + return tok == KEY or (tok in State.issued and tok not in State.revoked) + return tok == KEY + + def do_GET(self): + if self.path == "/gw/auth": + if State.mode == "drumsd": + return _send(self, 404, {"error": "no such route"}) + url = f"{State.console_url}/api/v1/tokens" if State.mode != "api_key" else None + return _send(self, 200, {"auth_mode": State.mode if State.mode != "drumsd" else "api_key", "token_url": url, "keys_url": None, "host_id": "h"}) + if not self._auth_ok(): + return _send(self, 401, {"error": "missing, invalid, revoked or expired desktop token", "code": "unauthenticated"}) + if self.path == "/gw/v1/health": + return _send(self, 200, {"ok": True, "version": "0.4.2"}) + return _send(self, 404, {"error": "no such route"}) + + def do_POST(self): + n = int(self.headers.get("Content-Length") or 0) + self.rfile.read(n) + if not self._auth_ok(): + return _send(self, 401, {"error": "missing, invalid, revoked or expired desktop token", "code": "unauthenticated"}) + return _send(self, 200, {"reset": True}) + + +def serve(handler): + httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + return httpd + + +class TokenExchange(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.console = serve(Console) + cls.gateway = serve(Gateway) + State.console_url = f"http://127.0.0.1:{cls.console.server_address[1]}" + cls.url = f"http://127.0.0.1:{cls.gateway.server_address[1]}/gw" + + @classmethod + def tearDownClass(cls): + for s in (cls.console, cls.gateway): + s.shutdown() + s.server_close() + + def setUp(self): + State.reset() + + def connect(self, **kw): + return drums.connect(self.url, KEY, close_on_exit=False, handle_signals=False, retry_s=0.0, **kw) + + def test_signature_unchanged_and_the_key_goes_to_the_console_only_once(self): + c = self.connect() + for _ in range(5): + self.assertTrue(c.health()["ok"]) + self.assertEqual(State.exchanges, 1) + self.assertEqual(State.console_auth, [f"Bearer {KEY}"]) + self.assertTrue(State.gateway_auth) + for a in State.gateway_auth: + self.assertNotIn(KEY, a) + self.assertEqual(a, f"Bearer {State.issued[0]}") + + def test_renews_before_expiry(self): + State.renew_after_s = 1 + c = self.connect() + c.health() + time.sleep(1.2) + c.health() + self.assertEqual(State.exchanges, 2) + self.assertEqual(State.gateway_auth[-1], f"Bearer {State.issued[1]}") + + def test_a_refused_token_is_renewed_once_and_the_call_retried(self): + c = self.connect() + c.health() + State.revoked.add(State.issued[0]) # e.g. the signing key rotated + self.assertEqual(c.call("POST", "/v1/slots/x/reset", {}), {"reset": True}) + self.assertEqual(State.exchanges, 2) + + def test_a_revoked_key_raises_auth_error_without_the_key_or_a_token(self): + c = self.connect() + c.health() + State.revoked.add(State.issued[0]) + State.console_status = 401 + with self.assertRaises(drums.AuthError) as cm: + c.health() + msg = str(cm.exception) + self.assertNotIn(KEY, msg) + self.assertNotIn("K" * 8, msg) + for t in State.issued: + self.assertNotIn(t, msg) + self.assertIn("refused the API key", msg) + + def test_token_mode_with_the_console_down_is_a_clear_error(self): + State.console_up = False + with self.assertRaises(drums.DaemonUnavailable) as cm: + self.connect() + self.assertIn("could not exchange the API key for a desktop token", str(cm.exception)) + self.assertNotIn(KEY, str(cm.exception)) + + def test_both_mode_falls_back_to_the_key_when_the_console_is_down(self): + State.mode, State.console_up = "both", False + c = self.connect() + self.assertTrue(c.health()["ok"]) + self.assertEqual(State.gateway_auth[-1], f"Bearer {KEY}") + tries = len(State.console_auth) + for _ in range(3): + c.health() + self.assertEqual(len(State.console_auth), tries, "no exchange attempt per call while the console is away") + + def test_api_key_mode_and_plain_drumsd_send_the_key_and_never_exchange(self): + for mode in ("api_key", "drumsd"): + State.reset() + State.mode = mode + c = self.connect() + c.health() + self.assertEqual(State.exchanges, 0, mode) + self.assertEqual(State.gateway_auth[-1], f"Bearer {KEY}") + + def test_a_drumsd_token_is_sent_as_is_with_no_discovery(self): + tok = "t" * 43 + c = drums.Client(self.url, tok) + self.assertEqual(c._cred.bearer(c), tok) + self.assertEqual(State.gateway_auth, []) + + def test_reprs_never_show_the_key_or_the_token(self): + c = self.connect() + c.health() + for text in (repr(c), str(c), repr(c._cred), str(c._cred)): + self.assertNotIn(KEY, text) + self.assertNotIn("K" * 8, text) + self.assertNotIn(State.issued[0], text) + self.assertIn("desktop token", repr(c)) + + def test_the_key_never_goes_to_a_plain_http_token_url_off_loopback(self): + State.console_url_saved = State.console_url + try: + State.console_url = "http://console.example.com" + with self.assertRaises(drums.InsecureTransport) as cm: + self.connect() + self.assertNotIn(KEY, str(cm.exception)) + finally: + State.console_url = State.console_url_saved + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_transport.py b/tests/test_transport.py index 5e1540d..4197838 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -184,6 +184,7 @@ class Redirecting(BaseHTTPRequestHandler): """A loopback server that redirects: every request is recorded as (path, headers). Location targets are built from the query-free path; `remote_port` is a second loopback listener that must never see a connection.""" requests = [] + probes = [] # GET /auth: the SDK's credential-free discovery of the gateway's auth mode (kept apart) remote_port = 0 def log_message(self, *a): @@ -203,6 +204,12 @@ def _json(self, obj): self.wfile.write(b) def do_GET(self): + if self.path == "/auth": + Redirecting.probes.append(dict(self.headers)) + self.send_response(404) + self.send_header("Content-Length", "0") + self.end_headers() + return Redirecting.requests.append((self.path, dict(self.headers))) host = f"127.0.0.1:{self.server.server_address[1]}" p = self.path @@ -284,6 +291,13 @@ def assert_refused(self, path, *expect_in_message): self.assertEqual(len(Redirecting.requests), 1, "only the first request was made") return cm.exception + def test_auth_discovery_probe_never_carries_the_key(self): + Redirecting.probes = [] + self.client.call("GET", "/landed") + self.client.call("GET", "/landed") + self.assertEqual(len(Redirecting.probes), 1, "discovered once per client") + self.assertNotIn("Authorization", Redirecting.probes[0]) + def test_cross_host_redirect_is_refused_unfollowed(self): self.assert_refused("/to-remote-host", "HTTP 302", "http://example.com:80", "127.0.0.1") self.assert_refused("/to-remote-https", "HTTP 301", "https://example.com:443") From 85f670142f534a1ffd4f9ce33a6a82bcdae24c33 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:35:04 -0500 Subject: [PATCH 12/23] mcp: custom tasks by task_set_id + task_id, list_task_sets and get_task_set, a task document sent as a JSON string, and verify with no task says so (same tool list and messages as the gateway) --- README.md | 8 ++++-- drums/mcp.py | 55 +++++++++++++++++++++++++++++++++++++--- drums/mcp_tools.json | 39 +++++++++++++++++++++++----- tests/test_mcp_server.py | 55 +++++++++++++++++++++++++++++++++++++--- tests/test_transport.py | 6 ++--- 5 files changed, 144 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 256a36b..430940b 100644 --- a/README.md +++ b/README.md @@ -212,8 +212,12 @@ methods raise `drums.NotFound`. Concepts: [runs and evaluations](https://docs.dr ## 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 | |---|---|---| diff --git a/drums/mcp.py b/drums/mcp.py index 7630b48..2cdf3a5 100644 --- a/drums/mcp.py +++ b/drums/mcp.py @@ -31,7 +31,7 @@ import urllib.parse from . import Client, Env, __version__, connect -from .errors import DrumsError, InsecureTransport, NotFound +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) 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/tests/test_mcp_server.py b/tests/test_mcp_server.py index 806ab8a..5b32894 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -15,6 +15,7 @@ from drums import mcp # noqa: E402 TOKEN = "k" * 43 +TS_ID = "0b5c2a52-77a0-4c0e-9a39-0a7a0f3c1d10" HERE = os.path.dirname(os.path.abspath(__file__)) TOOLS_JSON = mcp.TOOLS_PATH # the installed package's copy, so the test also proves the wheel ships it @@ -56,7 +57,7 @@ def _route(self, method, body): u = urllib.parse.urlsplit(self.path) path, q = u.path, dict(urllib.parse.parse_qsl(u.query)) parts = path.strip("/").split("/") - gateway_only = len(parts) >= 2 and parts[1] in ("runs", "api-keys", "audit") + gateway_only = len(parts) >= 2 and parts[1] in ("runs", "api-keys", "audit", "task-sets") if gateway_only and FakeGateway.no_runs: return self._send(404) # axum's default: no body at all # ---- slots @@ -69,6 +70,10 @@ def _route(self, method, body): return self._send(201, computer(7, checkpoint=body.get("checkpoint"), task=body.get("task"))) if path.startswith("/v1/slots/"): cid = parts[2] + if cid == "bare" and len(parts) == 3 and method == "GET": + return self._send(200, computer(1, task=None)) + if cid == "bare" and parts[3:] == ["verify"]: + return self._send(400, {"error": "drumsd rejected the request", "code": "invalid_request"}) if cid == "missing": return self._send(404, {"error": f"no env {cid} on this drumsd", "code": "not_found"}) if len(parts) == 3 and method == "GET": @@ -105,6 +110,18 @@ def _route(self, method, body): return self._send(200, rows) if path.startswith("/v1/tasks/"): return self._send(200, {"id": parts[2], "domain": "chrome", "instruction": "open a tab", "config": [], "evaluator": {"func": "x"}}) + # ---- task sets + if path == "/v1/task-sets" and method == "GET": + return self._send(200, {"items": [{"id": TS_ID, "name": "factory", "task_count": 2}], "next_cursor": None}) + if path == f"/v1/task-sets/{TS_ID}" and method == "GET": + return self._send(200, {"id": TS_ID, "name": "factory", "items": [{"task_id": "f-1"}, {"task_id": "f-2"}]}) + if path.startswith(f"/v1/task-sets/{TS_ID}/tasks/") and method == "GET": + tid = urllib.parse.unquote(parts[4]) + if tid not in ("f-1", "f-2"): + return self._send(404, {"error": "no such task in this set", "code": "not_found"}) + return self._send(200, {"id": tid, "instruction": "make a folder", "config": [], "evaluator": {"func": "drums_verifier"}}) + if path.startswith("/v1/task-sets/"): + return self._send(404, {"error": "no such task set", "code": "not_found"}) # ---- runs if path == "/v1/runs" and method == "GET": return self._send(200, {"items": [{"id": "r1", "kind": q.get("kind") or "scripted_test", "status": q.get("status") or "queued"}], "next_cursor": None}) @@ -183,7 +200,7 @@ def test_tools_list_equals_mcp_tools_json_in_order_with_annotations(self): with open(TOOLS_JSON) as f: want = json.load(f)["tools"] got = self.rpc(self.srv, "tools/list")["result"]["tools"] - self.assertEqual(len(got), 34) + self.assertEqual(len(got), 36) self.assertEqual([t["name"] for t in got], [t["name"] for t in want]) for g, w in zip(got, want): self.assertEqual(g["description"], w["description"]) @@ -207,7 +224,7 @@ def test_initialize_and_tools_list_send_nothing_and_the_transport_rule_holds_for # initialize and tools/list are answered from mcp_tools.json: no request reaches the gateway srv = mcp.Server(drums.Client("https://beta.drums.run/gw", TOKEN)) self.assertEqual(self.rpc(srv, "initialize")["result"]["serverInfo"]["name"], "drums") - self.assertEqual(len(self.rpc(srv, "tools/list")["result"]["tools"]), 34) + self.assertEqual(len(self.rpc(srv, "tools/list")["result"]["tools"]), 36) self.assertEqual(FakeGateway.calls, []) # the Server never gets a client that would send the token over plain http off loopback with self.assertRaises(drums.InsecureTransport) as cm: @@ -397,7 +414,37 @@ def test_desktop_tools_over_the_api(self): self.assertEqual(self.last()[2], {"task": {"id": "inline"}}) res, out = self.tool("load_task", {"computer_id": "c1"}) self.assertTrue(res["isError"]) - self.assertIn("task_id or task", out) + self.assertIn("one of task (a task document), task_set_id + task_id, or task_id", out) + + def test_custom_tasks_by_task_set_and_as_a_json_string(self): + res, out = self.tool("list_task_sets", {}) + self.assertEqual(out["task_sets"][0]["id"], TS_ID) + res, out = self.tool("get_task_set", {"task_set_id": TS_ID}) + self.assertEqual([i["task_id"] for i in out["items"]], ["f-1", "f-2"]) + res, out = self.tool("create_computer", {"template": "osworld-ubuntu", "task_set_id": TS_ID, "task_id": "f-2"}) + self.assertFalse(res["isError"], out) + self.assertEqual(FakeGateway.calls[-2][:2], ("GET", f"/v1/task-sets/{TS_ID}/tasks/f-2")) + self.assertEqual(self.last()[2]["task"]["id"], "f-2") + self.assertEqual(self.last()[2]["task"]["evaluator"], {"func": "drums_verifier"}) + res, out = self.tool("load_task", {"computer_id": "c1", "task_set_id": TS_ID, "task_id": "f-1"}) + self.assertEqual(self.last()[2]["task"]["id"], "f-1") + res, out = self.tool("create_computer", {"template": "osworld-ubuntu", "task_set_id": TS_ID, "task_id": "nope"}) + self.assertTrue(res["isError"]) + self.assertIn("no such task in this set", out) + res, out = self.tool("create_computer", {"template": "osworld-ubuntu", "task_set_id": TS_ID}) + self.assertIn("task_set_id needs task_id", out) + res, out = self.tool("create_computer", {"template": "osworld-ubuntu", "task": json.dumps({"id": "as-string", "instruction": "x"})}) + self.assertFalse(res["isError"], out) + self.assertEqual(self.last()[2]["task"], {"id": "as-string", "instruction": "x"}) + res, out = self.tool("create_computer", {"template": "osworld-ubuntu", "task": "not json"}) + self.assertTrue(res["isError"]) + + def test_verify_without_a_task_says_so(self): + res, out = self.tool("verify", {"computer_id": "bare"}) + self.assertTrue(res["isError"]) + self.assertEqual(out, mcp.NO_TASK) + res, out = self.tool("verify", {"computer_id": "c1"}) + self.assertFalse(res["isError"]) # safety ----------------------------------------------------------------------------------------------------------- def test_destructive_tools_refuse_without_confirm_before_any_request(self): diff --git a/tests/test_transport.py b/tests/test_transport.py index 5e1540d..13bec83 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -150,16 +150,16 @@ def test_loopback_http_and_https_start_the_server(self): self.assertEqual(rc, 0, (url, err)) self.assertEqual(err, "", url) reply = json.loads(out) - self.assertEqual(len(reply["result"]["tools"]), 34, url) # tools/list needs no gateway + self.assertEqual(len(reply["result"]["tools"]), 36, url) # tools/list needs no gateway self.assertNotIn(SECRET, out) def test_opt_in_flag_and_env_allow_plain_http(self): rc, out, err = run_cli(["mcp", "--url", "http://example.com", "--allow-insecure-http"], {"DRUMS_TOKEN": SECRET}, stdin=LIST_TOOLS) self.assertEqual(rc, 0, err) - self.assertEqual(len(json.loads(out)["result"]["tools"]), 34) + self.assertEqual(len(json.loads(out)["result"]["tools"]), 36) rc, out, err = run_cli(["mcp", "--url", "http://example.com"], {"DRUMS_TOKEN": SECRET, "DRUMS_ALLOW_INSECURE_HTTP": "1"}, stdin=LIST_TOOLS) self.assertEqual(rc, 0, err) - self.assertEqual(len(json.loads(out)["result"]["tools"]), 34) + self.assertEqual(len(json.loads(out)["result"]["tools"]), 36) self.assertNotIn(SECRET, out + err) def test_no_token_plain_http_is_not_refused(self): From 77784c6d96228ac9e2d96d4afd780d9c606e97c8 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:37:27 -0500 Subject: [PATCH 13/23] release: CHANGELOG entry for the post-D1 fixes and a proposed version 0.4.0 (not published) --- CHANGELOG.md | 34 ++++++++++++++++++++++++++++++++++ drums/__init__.py | 2 +- pyproject.toml | 2 +- 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5466c87..967fe76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,40 @@ 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. +## Unreleased (proposed: 0.4.0) + +Post-D1 fixes for training clients (audit 2026-11-16). Minor version: new API, one behaviour change (429 retries), +nothing removed. Each item is a pull request of its own. + +- **Retry-After 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`, with jittered exponential backoff, for at most 60 s of waiting per call. + `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. +- **macOS certificates** (A-07, #11). When the system store cannot verify the server and `certifi` is installed, the + client retries once with certifi's CA bundle and prints one line saying so; 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). `with client.run(name, kind="training", task_set=..., config=...) as run:` opens a run + (`POST /v1/runs`), `run.step(step, reward=, zero_advantage_share=, rollouts=, desktops_busy=)` 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). Desktops created inside carry `X-Drums-Run-Label` (and + `X-Drums-Run-Id`). On a gateway without these routes 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). Rows that + need the gateway's future `GET /v1/limits` say "not checked" until it exists. +- **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). + ## 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/drums/__init__.py b/drums/__init__.py index 35ee461..3ee0e08 100644 --- a/drums/__init__.py +++ b/drums/__init__.py @@ -48,7 +48,7 @@ EnvGone, ForkError, GateFailed, GuestError, InsecureTransport, InvalidEpisode, NotFound, NotQuiescent, Overloaded, RedirectRefused, RestoreFailed, TaskSetupFailed, TaskUnsupported) -__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" diff --git a/pyproject.toml b/pyproject.toml index 0c98b04..af59d95 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "drums-sdk" -version = "0.3.0" +version = "0.4.0" # Distribution name drums-sdk (PyPI rejects "drums" as too similar to an existing project); import name: drums. description = "Drums SDK: isolated desktop environments for computer-use RL. Create a desktop, act, screenshot, fork, verify." readme = "README.md" From e2b145b9662d17997c3071cbbaee7b472719f2a4 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:38:45 -0500 Subject: [PATCH 14/23] ci: run the test matrix on ubuntu-24.04 (ubuntu-latest has no Python 3.9; the same line as #10) --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 69b32d1..ef8ea0d 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: From 87d2788489d636984baa0ce99390bc4be3050a58 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:38:47 -0500 Subject: [PATCH 15/23] ci: run the test matrix on ubuntu-24.04 (ubuntu-latest has no Python 3.9; the same line as #10) --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 69b32d1..ef8ea0d 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: From 2eeea57b7d2c8ce5ce5676a74a703e5e979ca84e Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:38:48 -0500 Subject: [PATCH 16/23] ci: run the test matrix on ubuntu-24.04 (ubuntu-latest has no Python 3.9; the same line as #10) --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 69b32d1..ef8ea0d 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: From d69073568572c9b036c017f8bf8647d1bbe4855e Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:38:50 -0500 Subject: [PATCH 17/23] ci: run the test matrix on ubuntu-24.04 (ubuntu-latest has no Python 3.9; the same line as #10) --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 69b32d1..ef8ea0d 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: From befbf815de9bf5e26fe6e99c8c7498d47a8a5515 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 19:38:51 -0500 Subject: [PATCH 18/23] ci: run the test matrix on ubuntu-24.04 (ubuntu-latest has no Python 3.9; the same line as #10) --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 69b32d1..ef8ea0d 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: From 86b4f6796ada4a4e874e60ea13c9d6ce73faf066 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 22:07:39 -0500 Subject: [PATCH 19/23] tokens: the exchange and every renewal use the client's certifi fallback and RetryPolicy (429 with Retry-After; 5xx and dropped connections too in token mode); a key sent before the auth mode was known is retried once after a 401 --- drums/__init__.py | 125 ++++++++++++++++++++++++++++-------- tests/test_tokens.py | 148 ++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 244 insertions(+), 29 deletions(-) diff --git a/drums/__init__.py b/drums/__init__.py index 94c5c0d..8ae4318 100644 --- a/drums/__init__.py +++ b/drums/__init__.py @@ -246,7 +246,12 @@ class _Credentials: 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.""" + 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 @@ -257,6 +262,7 @@ def __init__(self, key: str | 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"" @@ -277,6 +283,20 @@ def kind(self) -> str: 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 @@ -297,11 +317,14 @@ def bearer(self, client) -> str | None: 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) + self._exchange(client, now, patient=not has_fallback) except (AuthError, InsecureTransport, RedirectRefused): raise - except DrumsError: + 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 @@ -309,6 +332,7 @@ def bearer(self, client) -> str | None: self._next_try = now + 60.0 return self._key raise + self.last_error = None return self._token def _discover(self, client): @@ -321,7 +345,9 @@ def _discover(self, client): e.close() self._mode = "api_key" # drumsd, or a gateway without token support return - except (RedirectRefused, urllib.error.URLError, ConnectionError, TimeoutError, OSError, ValueError): + 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 @@ -331,25 +357,57 @@ def _discover(self, client): else: self._mode = "api_key" - def _exchange(self, client, now: float): + 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) - opener = urllib.request.build_opener(_RedirectPolicy(self._key, client.allow_insecure_http)) - 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") - except urllib.error.HTTPError as e: - status = e.code - e.close() - if status == 401: - raise AuthError(401, f"the console at {origin} refused the API key (missing, invalid, revoked or expired)") from None - raise DaemonUnavailable(status, f"could not exchange the API key for a desktop token at {origin} (HTTP {status})") from None - except (urllib.error.URLError, ConnectionError, TimeoutError, OSError) as e: - 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 + 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") @@ -411,6 +469,7 @@ def __init__(self, url: str = DEFAULT_URL, token: str | None = None, timeout: fl # 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() @@ -485,19 +544,28 @@ def __exit__(self, *exc): self.close() # transport -------------------------------------------------------------------------------------------------------- - def _use_certifi(self) -> bool: - """Switch this client to certifi's CA bundle (once). False when certifi is missing or already in use.""" + 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._opener = urllib.request.build_opener(_RedirectPolicy(self.token, self.allow_insecure_http), urllib.request.HTTPSHandler(context=ctx)) + 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_text(self.url)}; using certifi's CA bundle " + 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 not retried after a dropped connection, since their outcome is unknown. @@ -539,9 +607,10 @@ def call(self, method: str, path: str, body=None, raw: bool = False, timeout: fl waited_429 += w time.sleep(w) continue - if e.code == 401 and self._cred.using_token and not renewed: - # the token expired, was revoked or its signing key rotated: exchange once more (a 401 is refused - # before anything ran, so even a POST is safe to send again) + 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 diff --git a/tests/test_tokens.py b/tests/test_tokens.py index b46848a..ed9e328 100644 --- a/tests/test_tokens.py +++ b/tests/test_tokens.py @@ -2,12 +2,16 @@ the console, sends only the token to the gateway, renews it before it expires and once after a 401, falls back to the key in `both` mode when the console is away, and never shows the key or the token in a repr or an error. A fake gateway and a fake console on loopback; no network.""" +import io import json import os +import ssl import sys import threading import time import unittest +import urllib.error +from contextlib import redirect_stderr from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) @@ -28,6 +32,7 @@ class State: gateway_auth = [] # Authorization headers the gateway saw on /v1 console_auth = [] console_url = "" + console_script = [] # (status, Retry-After or None) answered before the console issues a token @classmethod def reset(cls): @@ -35,6 +40,7 @@ def reset(cls): cls.renew_after_s, cls.expires_in = 3300, 3600 cls.issued, cls.exchanges, cls.revoked = [], 0, set() cls.gateway_auth, cls.console_auth = [], [] + cls.console_script = [] def _send(h, code, obj): @@ -58,6 +64,16 @@ def do_POST(self): return _send(self, 404, {"code": "not_found"}) if not State.console_up: return _send(self, 503, {"code": "retryable_infrastructure_failure"}) + if State.console_script: + status, ra = State.console_script.pop(0) + b = json.dumps({"code": "rate_limited" if status == 429 else "retryable_infrastructure_failure"}).encode() + self.send_response(status) + if ra is not None: + self.send_header("Retry-After", str(ra)) + self.send_header("Content-Length", str(len(b))) + self.end_headers() + self.wfile.write(b) + return if self.headers.get("Authorization") != f"Bearer {KEY}" or State.console_status == 401: return _send(self, 401, {"error": "missing, invalid, revoked or expired API key", "code": "unauthenticated"}) State.exchanges += 1 @@ -171,7 +187,7 @@ def test_a_revoked_key_raises_auth_error_without_the_key_or_a_token(self): def test_token_mode_with_the_console_down_is_a_clear_error(self): State.console_up = False with self.assertRaises(drums.DaemonUnavailable) as cm: - self.connect() + self.connect(retry=drums.RetryPolicy(max_wait_s=0)) self.assertIn("could not exchange the API key for a desktop token", str(cm.exception)) self.assertNotIn(KEY, str(cm.exception)) @@ -185,6 +201,64 @@ def test_both_mode_falls_back_to_the_key_when_the_console_is_down(self): c.health() self.assertEqual(len(State.console_auth), tries, "no exchange attempt per call while the console is away") + def test_the_exchange_waits_for_a_429_retry_after(self): + State.console_script = [(429, 1)] + t0 = time.monotonic() + c = self.connect() + self.assertTrue(c.health()["ok"]) + self.assertGreaterEqual(time.monotonic() - t0, 1.0) + self.assertEqual(State.exchanges, 1) + self.assertEqual(len(State.console_auth), 2) + self.assertEqual(State.gateway_auth[-1], f"Bearer {State.issued[0]}") + + def test_token_mode_retries_a_5xx_from_the_console_within_the_budget(self): + State.console_script = [(503, None), (502, None)] + c = self.connect(retry=drums.RetryPolicy(max_wait_s=5, base_s=0.05)) + self.assertTrue(c.health()["ok"]) + self.assertEqual(len(State.console_auth), 3) + + def test_the_exchange_honours_the_retry_off_switch(self): + State.console_script = [(429, 1)] + t0 = time.monotonic() + with self.assertRaises(drums.DaemonUnavailable) as cm: + self.connect(retry=drums.RetryPolicy(max_wait_s=0)) + self.assertLess(time.monotonic() - t0, 1.0) + self.assertIn("HTTP 429", str(cm.exception)) + self.assertEqual(cm.exception.retry_after, 1.0) + + def test_both_mode_does_not_wait_on_a_failing_console(self): + State.mode, State.console_script = "both", [(503, 5)] + t0 = time.monotonic() + c = self.connect() + self.assertTrue(c.health()["ok"]) + self.assertLess(time.monotonic() - t0, 2.0, "the key still works in both mode, so no 503 backoff") + self.assertEqual(State.gateway_auth[-1], f"Bearer {KEY}") + self.assertIn("HTTP 503", c._cred.last_error) + + def test_a_renewal_after_a_401_also_retries_a_429(self): + c = self.connect() + c.health() + State.revoked.add(State.issued[0]) + State.console_script = [(429, 0)] + self.assertTrue(c.health()["ok"]) + self.assertEqual(State.exchanges, 2) + self.assertEqual(State.gateway_auth[-1], f"Bearer {State.issued[1]}") + + def test_a_key_sent_before_discovery_answered_is_retried_after_the_401(self): + c = drums.Client(self.url, KEY, retry_s=0.0) + real = c._cred._discover + calls = [] + + def flaky(client): + calls.append(1) + if len(calls) == 1: + return None # no answer: the mode stays unknown and the key goes out as is + return real(client) + c._cred._discover = flaky + self.assertTrue(c.health()["ok"]) + self.assertEqual(len(calls), 2) + self.assertEqual(State.gateway_auth[-1], f"Bearer {State.issued[0]}") + def test_api_key_mode_and_plain_drumsd_send_the_key_and_never_exchange(self): for mode in ("api_key", "drumsd"): State.reset() @@ -220,5 +294,77 @@ def test_the_key_never_goes_to_a_plain_http_token_url_off_loopback(self): State.console_url = State.console_url_saved + +class _Resp(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *a): + self.close() + + +class _Opener: + def __init__(self, outcome): + self.outcome = outcome + + def open(self, req, timeout=None): + if isinstance(self.outcome, BaseException): + raise self.outcome + return _Resp(self.outcome) + + +def _cert_failure(): + return urllib.error.URLError(ssl.SSLCertVerificationError(1, "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed")) + + +class ExchangeCertificates(unittest.TestCase): + """The token exchange builds its own connection to the console: it gets the same certifi fallback as the gateway.""" + + def client(self, outcomes): + from unittest import mock + c = drums.Client("https://gw.example/gw", KEY) + c._cred._mode, c._cred._token_url = "token", "https://console.example/api/v1/tokens" + built = [] + + def build(token): + built.append((token is not None, c._certifi_ctx is not None)) + return _Opener(outcomes.pop(0)) + return c, built, mock.patch.object(c, "_build_opener", side_effect=build) + + def test_a_failed_system_store_on_the_console_switches_to_certifi(self): + from unittest import mock + tok = b'{"token": "tok-1", "expires_in": 3600}' + c, built, patch = self.client([_cert_failure(), b"gateway opener", tok]) # _use_certifi rebuilds the gateway's opener too + err = io.StringIO() + with patch, mock.patch.object(drums, "_certifi_context", return_value=ssl.create_default_context()), redirect_stderr(err): + self.assertEqual(c._cred.bearer(c), "tok-1") + self.assertTrue(c._certifi) + self.assertEqual(built, [(True, False), (True, True), (True, True)]) # the retry used certifi's bundle + line = err.getvalue().strip() + self.assertEqual(len(line.splitlines()), 1) + self.assertIn("https://console.example:443", line) + self.assertNotIn(KEY, line) + self.assertNotIn("tok-1", line) + + def test_without_certifi_the_console_error_names_the_fix(self): + from unittest import mock + c, _, patch = self.client([_cert_failure()]) + with patch, mock.patch.object(drums, "_certifi_context", return_value=None): + with self.assertRaises(drums.CertificateError) as cm: + c._cred.bearer(c) + msg = str(cm.exception) + self.assertIn("console.example", msg) + self.assertIn("pip install certifi", msg) + self.assertNotIn(KEY, msg) + + def test_a_client_already_on_certifi_uses_it_for_the_exchange(self): + from unittest import mock + c, built, patch = self.client([b'{"token": "tok-2", "expires_in": 3600}']) + c._certifi, c._certifi_ctx = True, ssl.create_default_context() + with patch: + self.assertEqual(c._cred.bearer(c), "tok-2") + self.assertEqual(built, [(True, True)]) + + if __name__ == "__main__": unittest.main() From 1a1765d3a78b6bb80484965ecdaca94940d36b63 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Tue, 17 Nov 2026 22:10:14 -0500 Subject: [PATCH 20/23] runs: follow the gateway's trainer runs (Drums-Labs/drums#41): no scripted_test kind (eval accepted), desktops_provisioned on open and steps, the label from the open reply, a 409 on heartbeat or close ends the run with one warning and no retries, a 403 says computers:write also suffices --- README.md | 17 ++++++++---- drums/__init__.py | 11 +++++--- drums/runs.py | 62 ++++++++++++++++++++++++++++++++----------- tests/test_runs.py | 65 +++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 130 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 83c9d07..cbb3a19 100644 --- a/README.md +++ b/README.md @@ -255,20 +255,27 @@ the run (task set, config hash, steps, reward, zero-advantage share, rollouts, d of anonymous computers: ```python -with client.run("qwen27b-d2", kind="training", task_set=task_set_id, config=cfg) as run: +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 name as their label (`X-Drums-Run-Label`; fork children inherit - it), so the Computers page can filter them by run. +- 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. +- 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 without `runs:write`, the run is a no-op with one warning and training - goes on; `strict=True` raises `drums.RunNotSupported` instead. The labels still apply. + `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). diff --git a/drums/__init__.py b/drums/__init__.py index 8ae4318..c6e4d30 100644 --- a/drums/__init__.py +++ b/drums/__init__.py @@ -718,13 +718,16 @@ def get_run(self, run_id: str) -> dict: 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) -> "Run": + 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. On a gateway without run routes it is a no-op - with one warning (strict=True raises instead).""" - return Run(self, name, kind, task_set=task_set, config=config, flush_s=flush_s, strict=strict, label=label) + 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 diff --git a/drums/runs.py b/drums/runs.py index bb3b9bf..9a339f1 100644 --- a/drums/runs.py +++ b/drums/runs.py @@ -9,11 +9,17 @@ 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} -> {run_id | id, ...} - (Idempotency-Key header: a retried open returns the same run) - PATCH /v1/runs/{id} {steps: [{step, reward, zero_advantage_share, rollouts, desktops_busy, at, extra?}]} + 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 `