diff --git a/CHANGELOG.md b/CHANGELOG.md index da12957..8c1581c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,16 @@ 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 + +### Added + +- **`Quarantined`**, a subclass of `Conflict`: the 409 `wrong_state` a quarantined env gives to reset, step, save and + fork. It carries why the env was quarantined (`reason`) and drumsd's advice (`next`), both sent by drumsd v0.2.1 and + later, and its message says the env stays quarantined until it is released and reset, or closed. Before, this was a + bare `Conflict`, so a loop that did not GET the record could not tell it from a passing refusal and kept resetting + ([drumsd#12](https://github.com/Drums-Labs/drumsd/issues/12)). `except Conflict` still catches it. + ## 0.4.0 - 2026-11-18 Fixes for training clients, from our first 128-desktop training run, integrated in one release. Minor version: new API and one diff --git a/README.md b/README.md index 8b64277..8258542 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,7 @@ reply), `message` and `body`. Errors about a computer carry its record and gate | `NotFound` | 404: no such computer, template, state or task | | `EnvGone` | 410: the computer was destroyed (closed, or reaped by its lease); a subclass of `NotFound` | | `Conflict` | 409: the computer's state does not allow this operation | +| `Quarantined` | 409: the computer is quarantined, so reset, step, save and fork are refused until you `release()` then `reset()` it, or close it (`reason`, `next`); a subclass of `Conflict` | | `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: rate limited, host full or near its memory limit; nothing was started. Raised after the retries ran out (`retry_after`, `retries`) | diff --git a/drums/__init__.py b/drums/__init__.py index a7bc08d..0b5b108 100644 --- a/drums/__init__.py +++ b/drums/__init__.py @@ -57,8 +57,8 @@ import warnings 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) + EnvGone, ForkError, GateFailed, GuestError, InsecureTransport, InvalidEpisode, NotFound, NotQuiescent, Overloaded, Quarantined, RedirectRefused, RestoreFailed, + TaskSetupFailed, TaskUnsupported) from . import runs as _runs from .runs import Run, RunNotSupported @@ -73,7 +73,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", "Quarantined", "TaskUnsupported", "InsecureTransport", "RedirectRefused", "check_transport"] __all__ += ["Run", "RunNotSupported"] @@ -632,6 +632,8 @@ def call(self, method: str, path: str, body=None, raw: bool = False, timeout: fl cls = NotQuiescent if e.code == 409 and isinstance(body_j, dict) and body_j.get("code") == "checkpoint_stale": cls = CheckpointStale + if e.code == 409 and isinstance(body_j, dict) and body_j.get("code") == "wrong_state" and body_j.get("state") == "quarantined": + cls = Quarantined if e.code == 422 and isinstance(body_j, dict) and body_j.get("code") == "task_unsupported": cls = TaskUnsupported if e.code == 409 and "slot is destroyed" in str(msg): # drumsd < 0.4.2 @@ -1006,7 +1008,8 @@ def _check_up(self): # episode ---------------------------------------------------------------------------------------------------------- def reset(self) -> "Env": """New episode from the image or saved state this env was made from (and the task's setup, for an env created - with a task).""" + with a task). Raises RestoreFailed / GateFailed / TaskSetupFailed if it did not come up ready, and Quarantined + if the env was quarantined already: release() it first, or close it and create a new env.""" self.record = self.client.call("POST", f"/v1/slots/{self.id}/reset") self.steps = 0 self._last_fork = None diff --git a/drums/errors.py b/drums/errors.py index 44e773b..ecdcfa4 100644 --- a/drums/errors.py +++ b/drums/errors.py @@ -78,8 +78,29 @@ def __init__(self, status: int, message: str, body=None): class Conflict(DrumsError): - """409: the env's state does not allow this operation (e.g. step on a quarantined env; code `wrong_state`). - A destroyed env raises EnvGone instead.""" + """409: the env's state does not allow this operation (code `wrong_state`, e.g. step on an env that is down). + A quarantined env raises Quarantined instead, a destroyed one EnvGone.""" + + +class Quarantined(Conflict): + """409 `wrong_state` from a quarantined env: its state is not trusted (a gate failed, a capture failed, or a client + or an operator quarantined it). drumsd never restores into it by itself, so every reset, step, save or fork on it + gets this same reply at once and retrying does not help. The ways out: `env.release()` then `env.reset()` (a new + episode in the same env), or `env.close()` and a new env. `reason` says why it was quarantined (e.g. "gate cgroup + failed: ...") and `next` is drumsd's own advice; a drumsd before v0.2.1 sends neither, so both are None then. A + subclass of Conflict, so `except Conflict` still catches it.""" + + def __init__(self, status: int, message: str, body=None): + super().__init__(status, message, body) + b = body if isinstance(body, dict) else {} + self.reason = b.get("reason") + self.next = b.get("next") + + def __str__(self) -> str: + # the way out before the reason: a reason can run to 4000 characters, and callers cut long messages + why = f" (reason: {self.reason})" if self.reason else "" + return (f"{super().__str__()}; it stays quarantined until it is released or closed: env.release() then " + f"env.reset(), or env.close() and a new env{why}") class Overloaded(DrumsError): @@ -177,7 +198,8 @@ class RestoreFailed(EnvFailed): class GateFailed(EnvFailed): - """A gate failed: the env is quarantined; its state is not trusted. Close it (or release + reset).""" + """A gate failed: the env is quarantined; its state is not trusted. Close it (or release + reset). Until then + every reset, step, save or fork on it raises Quarantined.""" class TaskSetupFailed(EnvFailed): diff --git a/tests/test_client.py b/tests/test_client.py index 5015d73..c65c457 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -14,6 +14,9 @@ TOKEN = "t" * 43 PNG = b"\x89PNG\r\n\x1a\n" + b"\x00\x00\x00\rIHDR" + (1920).to_bytes(4, "big") + (1080).to_bytes(4, "big") + b"\x08\x02\x00\x00\x00" +QUARANTINE_REASON = 'gate cgroup failed: {"failed":["outside_cgroup"],"strays":[{"comm":"sh"}]}' +QUARANTINE_NEXT = ("release (POST /v1/slots/{id}/release) then reset, or destroy it and create a new env; the env is not restored " + "into again by itself") def slot(i, state="ready", episode=1, verdict="pending", **kw): @@ -58,12 +61,27 @@ def _gone(self): return True return False + def _wrong_state(self): + """/v1/slots/quarantined/...: a quarantined env, refused as drumsd v0.2.1 and later do (with reason and next); + /v1/slots/quarantined-old/...: as v0.2.0 did (code and state only); /v1/slots/down/...: an env that is down.""" + parts = self.path.split("/") + if len(parts) != 5 or parts[3] not in ("quarantined", "quarantined-old", "down") or parts[4] not in ("reset", "step", "capture", "branch"): + return False + eid, op = parts[3], {"branch": "capture"}.get(parts[4], parts[4]) + state = "down" if eid == "down" else "quarantined" + body = {"error": f"slot is {state}: {op} is not allowed (allowed from: {'ready, down' if op == 'reset' else 'ready'})", + "code": "wrong_state", "state": state} + if eid == "quarantined": + body.update(reason=QUARANTINE_REASON, next=QUARANTINE_NEXT) + self._send(409, body) + return True + def do_POST(self): b = self._body() Fake.calls.append(("POST", self.path, b)) if not self._authed(): return - if self._gone(): + if self._gone() or self._wrong_state(): return if self.path == "/v1/slots": ck = b["checkpoint"] @@ -427,6 +445,33 @@ def test_a_destroyed_env_raises_env_gone_and_close_is_a_no_op(self): e.step("x") self.assertEqual((cm.exception.status, cm.exception.closed_reason), (410, "lease: idle 1800 s")) + def test_a_quarantined_env_is_typed_and_says_why_and_what_to_do(self): + # drumsd issue 12: an env quarantined by a gate got 10,325 resets in 50 s, each refused with the same bare 409 + e = drums.Env(self.c, {"id": "quarantined", "state": "ready"}) + Fake.calls.clear() + with self.assertRaises(drums.Quarantined) as cm: + e.reset() + q = cm.exception + self.assertIsInstance(q, drums.Conflict, "Quarantined is a Conflict (old except clauses still catch it)") + self.assertEqual((q.status, q.reason, q.next, q.body["state"]), (409, QUARANTINE_REASON, QUARANTINE_NEXT, "quarantined")) + self.assertEqual(q.message, "slot is quarantined: reset is not allowed (allowed from: ready, down)") + self.assertEqual(len(Fake.calls), 1, "sent once: a 409 is not retried") + self.assertIn("it stays quarantined until it is released or closed: env.release() then env.reset(), or env.close() and a new env", + str(q)) + self.assertTrue(str(q).endswith(f"(reason: {QUARANTINE_REASON})"), str(q)) + for op in (lambda: e.step("pyautogui.press('shift')"), e.save, lambda: e.fork(2)): + with self.assertRaises(drums.Quarantined): + op() + # a drumsd before v0.2.1 sent code and state only: the same error, without a reason + with self.assertRaises(drums.Quarantined) as cm: + drums.Env(self.c, {"id": "quarantined-old", "state": "ready"}).reset() + self.assertEqual((cm.exception.reason, cm.exception.next), (None, None)) + self.assertNotIn("(reason:", str(cm.exception)) + # an env refused for another state (here: down) is still a plain Conflict + with self.assertRaises(drums.Conflict) as cm: + drums.Env(self.c, {"id": "down", "state": "down"}).step("pyautogui.press('shift')") + self.assertNotIsInstance(cm.exception, drums.Quarantined) + def test_fork_returns_its_saved_state_and_the_old_shape(self): e = self.c.create() Fake.calls.clear() diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 5b32894..373a928 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -76,6 +76,10 @@ def _route(self, method, body): 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 cid == "quarantined" and parts[3:] == ["reset"]: # drumsd keeps up to 4000 characters of gate detail + return self._send(409, {"error": "slot is quarantined: reset is not allowed (allowed from: ready, down)", "code": "wrong_state", + "state": "quarantined", "reason": "gate cgroup failed: " + "x" * 4000, + "next": "release (POST /v1/slots/{id}/release) then reset, or destroy it and create a new env"}) if len(parts) == 3 and method == "GET": return self._send(200, computer(1)) if len(parts) == 3 and method == "DELETE": @@ -446,6 +450,14 @@ def test_verify_without_a_task_says_so(self): res, out = self.tool("verify", {"computer_id": "c1"}) self.assertFalse(res["isError"]) + def test_reset_on_a_quarantined_computer_says_it_will_not_come_back_by_itself(self): + res, out = self.tool("reset", {"computer_id": "quarantined"}) + self.assertTrue(res["isError"]) + self.assertEqual(len(out), 1000, "a tool error keeps 1000 characters of a 4000-character reason") + self.assertTrue(out.startswith("server HTTP 409: slot is quarantined: reset is not allowed"), out[:200]) + self.assertIn("it stays quarantined until it is released or closed", out) # the way out comes before the reason + self.assertIn("(reason: gate cgroup failed: xxx", out) + # safety ----------------------------------------------------------------------------------------------------------- def test_destructive_tools_refuse_without_confirm_before_any_request(self): for name, args in (("destroy_computer", {"computer_id": "c1"}), ("destroy_computer", {"computer_id": "c1", "confirm": False}),