Repository navigation
[core][sandbox] Default network="public" egress to the public internet and enforce allowlists - #66359
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces an experimental REST API service and a gRPC facade for Ray Sandbox, allowing sandboxes to be managed externally via HTTP or gRPC. It updates the image manager to cache container images as EROFS filesystems using mkfs.erofs to preserve file ownership, and implements egress network filtering using nftables with a configurable cidr_allowlist. The review feedback highlights several opportunities to improve robustness and concurrency safety, including serializing network policy updates with an asyncio.Lock to prevent race conditions, adding type and bounds checks to prevent AttributeError and IndexError crashes in the gRPC facade, catching SandboxError in write_file to avoid 500 errors, and making the sandbox listing endpoint more resilient to individual actor failures.
| self._execs: "OrderedDict[str, _ExecJob]" = OrderedDict() | ||
| self._exec_tasks: Dict[str, asyncio.Task] = {} | ||
| self._ttl_task: Optional[asyncio.Task] = None | ||
| self._boot_started = False |
There was a problem hiding this comment.
Since SandboxHost is an async actor, multiple concurrent calls to set_network_access will run concurrently in different threads (via asyncio.to_thread). They will race on reading/writing egress.nft and running nsenter ... nft -f. We should initialize an asyncio.Lock to serialize these updates.
| self._boot_started = False | |
| self._boot_started = False | |
| self._network_lock = asyncio.Lock() |
There was a problem hiding this comment.
Done in 3edaa94: SandboxHost creates self._network_lock, an asyncio.Lock (see the next thread for how it's used).
| async def set_network_access(self, cidr_allowlist: List[str]) -> Dict[str, Any]: | ||
| """Replace the sandbox's egress allowlist. | ||
|
|
||
| Only a sandbox created with ``cidr_allowlist`` can be changed; the | ||
| runtime keeps its ruleset and swaps it atomically. Returns the | ||
| updated info, or an ``error_code`` dict like the other methods. | ||
| """ | ||
| if self._status != "running": | ||
| return { | ||
| "error_code": "conflict", | ||
| "message": ( | ||
| f"sandbox {self._sandbox_id} is {self._status}, not running" | ||
| ), | ||
| } | ||
| if self._spec.get("cidr_allowlist") is None: | ||
| return { | ||
| "error_code": "conflict", | ||
| "message": ( | ||
| f"sandbox {self._sandbox_id} was created without a " | ||
| "cidr_allowlist, so its egress policy is fixed; create it " | ||
| "with one (['0.0.0.0/0', '::/0'] for open egress) to " | ||
| "change it later" | ||
| ), | ||
| } | ||
| try: | ||
| cidrs = normalize_cidr_allowlist(cidr_allowlist) | ||
| except ValueError as exc: | ||
| return {"error_code": "invalid", "message": str(exc)} | ||
| try: | ||
| await asyncio.to_thread( | ||
| self._runtime.set_egress_allowlist, self._instance_id, cidrs | ||
| ) | ||
| except (SandboxError, NotImplementedError) as exc: | ||
| return {"error_code": "internal", "message": str(exc)} | ||
| self._spec["cidr_allowlist"] = cidrs | ||
| return self._info() |
There was a problem hiding this comment.
Use the initialized self._network_lock to serialize network policy updates and prevent concurrent threads from racing on the shared egress.nft file and nft command execution.
async def set_network_access(self, cidr_allowlist: List[str]) -> Dict[str, Any]:
"""Replace the sandbox's egress allowlist.
Only a sandbox created with ``cidr_allowlist`` can be changed; the
runtime keeps its ruleset and swaps it atomically. Returns the
updated info, or an ``error_code`` dict like the other methods.
"""
if self._status != "running":
return {
"error_code": "conflict",
"message": (
f"sandbox {self._sandbox_id} is {self._status}, not running"
),
}
if self._spec.get("cidr_allowlist") is None:
return {
"error_code": "conflict",
"message": (
f"sandbox {self._sandbox_id} was created without a "
"cidr_allowlist, so its egress policy is fixed; create it "
"with one (['0.0.0.0/0', '::/0'] for open egress) to "
"change it later"
),
}
try:
cidrs = normalize_cidr_allowlist(cidr_allowlist)
except ValueError as exc:
return {"error_code": "invalid", "message": str(exc)}
async with self._network_lock:
try:
await asyncio.to_thread(
self._runtime.set_egress_allowlist, self._instance_id, cidrs
)
except (SandboxError, NotImplementedError) as exc:
return {"error_code": "internal", "message": str(exc)}
self._spec["cidr_allowlist"] = cidrs
return self._info()There was a problem hiding this comment.
Done in 3edaa94: set_network_access holds the lock across the backend call and the spec update. The backend's set_egress_allowlist also takes a per-sandbox lock across the ruleset write, the nft -f load, and the recorded list, which covers callers of the Python API too. Tests run three overlapping updates at each layer and check they never overlap and that the recorded list is the one applied last.
| async def _start_fs_op(self, record: _ExecRecord, command: List[str]) -> None: | ||
| """Emulate one filesystem-tools invocation on ``record``.""" | ||
| try: | ||
| op = json.loads(command[1]) if len(command) > 1 else {} | ||
| except ValueError: | ||
| op = {} | ||
| if len(op) != 1: | ||
| raise GRPCError( | ||
| Status.INVALID_ARGUMENT, f"unrecognized fs-tools command: {command[1:]}" | ||
| ) | ||
| ((name, payload),) = op.items() | ||
| path = payload.get("path", "") | ||
| record.fs_path = path |
There was a problem hiding this comment.
If command[1] is a valid JSON but not a dictionary (e.g., a list or a string), op.items() will raise an unhandled AttributeError. Similarly, if payload is not a dictionary, payload.get will raise an AttributeError. We should add type checks to handle these cases gracefully.
async def _start_fs_op(self, record: _ExecRecord, command: List[str]) -> None:
"""Emulate one filesystem-tools invocation on ``record``."""
try:
op = json.loads(command[1]) if len(command) > 1 else {}
except ValueError:
op = {}
if not isinstance(op, dict) or len(op) != 1:
raise GRPCError(
Status.INVALID_ARGUMENT, f"unrecognized fs-tools command: {command[1:]}"
)
((name, payload),) = op.items()
if not isinstance(payload, dict):
raise GRPCError(
Status.INVALID_ARGUMENT, f"unrecognized fs-tools payload: {payload!r}"
)
path = payload.get("path", "")
record.fs_path = path| for line in image.dockerfile_commands: | ||
| stripped = line.strip() | ||
| if not stripped or stripped.startswith("#"): | ||
| continue | ||
| keyword = stripped.split(None, 1)[0].upper() | ||
| if keyword == "FROM": | ||
| if ref is not None: | ||
| raise GRPCError( | ||
| Status.INVALID_ARGUMENT, | ||
| "multi-stage image builds are not supported by the " | ||
| "Ray Sandbox gRPC facade", | ||
| ) | ||
| ref = stripped.split(None, 1)[1].strip() | ||
| elif keyword not in ("ENTRYPOINT", "CMD", "ENV", "WORKDIR", "LABEL"): | ||
| raise GRPCError( | ||
| Status.INVALID_ARGUMENT, | ||
| f"image build step {stripped!r} is not supported: the " | ||
| "Ray Sandbox gRPC facade only runs prebuilt registry images " | ||
| "(a single FROM line)", | ||
| ) |
There was a problem hiding this comment.
If image.dockerfile_commands contains a line that is exactly "FROM" (without any arguments), stripped.split(None, 1)[1] will raise an unhandled IndexError. We should check the length of the split parts before accessing the second element.
ref = None
for line in image.dockerfile_commands:
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
parts = stripped.split(None, 1)
keyword = parts[0].upper()
if keyword == "FROM":
if len(parts) < 2:
raise GRPCError(
Status.INVALID_ARGUMENT,
"FROM instruction requires an image reference",
)
if ref is not None:
raise GRPCError(
Status.INVALID_ARGUMENT,
"multi-stage image builds are not supported by the "
"Ray Sandbox gRPC facade",
)
ref = parts[1].strip()
elif keyword not in ("ENTRYPOINT", "CMD", "ENV", "WORKDIR", "LABEL"):
raise GRPCError(
Status.INVALID_ARGUMENT,
f"image build step {stripped!r} is not supported: the "
"Ray Sandbox gRPC facade only runs prebuilt registry images "
"(a single FROM line)",
)| async def write_file( | ||
| self, path: str, content: bytes, append: bool = False | ||
| ) -> Dict[str, Any]: | ||
| if self._status != "running": | ||
| return { | ||
| "error_code": "conflict", | ||
| "message": ( | ||
| f"sandbox {self._sandbox_id} is {self._status}, not running" | ||
| ), | ||
| } | ||
| await asyncio.to_thread( | ||
| self._runtime.write_file, | ||
| self._instance_id, | ||
| path, | ||
| content, | ||
| append, | ||
| ) | ||
| return {"ok": True} |
There was a problem hiding this comment.
If write_file fails (e.g., due to writing to a non-existent directory or a read-only path), it raises SandboxError (or SandboxExecError), which propagates all the way up to FastAPI's exception handlers and causes a 500 Internal Server Error. We should catch SandboxError and return a clean conflict error instead.
async def write_file(
self, path: str, content: bytes, append: bool = False
) -> Dict[str, Any]:
if self._status != "running":
return {
"error_code": "conflict",
"message": (
f"sandbox {self._sandbox_id} is {self._status}, not running"
),
}
try:
await asyncio.to_thread(
self._runtime.write_file,
self._instance_id,
path,
content,
append,
)
except SandboxError as exc:
return {"error_code": "conflict", "message": str(exc)}
return {"ok": True}| if isinstance(info, _ApiError) and info.code == "sandbox_not_found": | ||
| continue | ||
| if isinstance(info, BaseException): | ||
| raise info | ||
| if all(info.get("labels", {}).get(k) == v for k, v in filters.items()): | ||
| sandboxes.append(info) | ||
| return {"sandboxes": sandboxes} |
There was a problem hiding this comment.
If any sandbox actor raises an unexpected exception during listing, list_sandboxes will raise the exception and fail the entire request. We should log the exception and continue to make the endpoint more robust.
| if isinstance(info, _ApiError) and info.code == "sandbox_not_found": | |
| continue | |
| if isinstance(info, BaseException): | |
| raise info | |
| if all(info.get("labels", {}).get(k) == v for k, v in filters.items()): | |
| sandboxes.append(info) | |
| return {"sandboxes": sandboxes} | |
| for info in results: | |
| if isinstance(info, _ApiError) and info.code == "sandbox_not_found": | |
| continue | |
| if isinstance(info, BaseException): | |
| logger.exception("Failed to describe sandbox in listing") | |
| continue | |
| if all(info.get("labels", {}).get(k) == v for k, v in filters.items()): | |
| sandboxes.append(info) |
fc90b5f to
3edaa94
Compare
3edaa94 to
112572d
Compare
…65633) ## Why are these changes needed? Ray Sandbox (`ray.experimental.sandbox`) can currently only be driven from inside the cluster as Ray actors. This PR adds an **experimental HTTP API service** so sandboxes can be managed from outside the cluster with nothing but an HTTP client and a bearer token — for example as an Anyscale service, or from agent-evaluation frameworks (a Harbor `ray-sandbox` environment built on this API is submitted alongside: harbor-framework/harbor PR to follow). This is the second step of the plan from #65570 (first: make the Python API run Docker-built images out of the box; second: make Ray Sandbox consumable as a standalone service). ## Design ``` client ──HTTP/bearer──▶ FastAPI on Ray Serve (ray.experimental.sandbox.http, stateless replicas) │ ray.get_actor(name, namespace) ▼ SandboxHost — named, detached actor per sandbox │ composes SandboxRuntime ▼ gVisor (runsc) on the node ``` - **Named detached actors are the registry.** Any replica resolves any sandbox by name; list = `ray.util.list_named_actors`. The service keeps no state, so replicas scale/restart freely. - **Async submit + poll.** Image pulls and commands outlive HTTP requests and LB limits, so `POST /sandboxes` and `POST .../execs` return `202` immediately; clients poll, optionally long-polling with `wait_seconds` (≤ 30 s per request). Boot progress is observable: `pending → pulling → starting → running | error`. - **One TTL owner.** The API's TTL reclaims the sandbox **and** its hosting actor (the core runtime TTL is deliberately disabled here); an abandoned sandbox never strands an actor reservation. - **Everything sandbox-behavioral is the core `SandboxConfig`'s** (#65570): capabilities (default `DOCKER_DEFAULT_CAPABILITIES`, sets written exactly), network modes (validated against `VALID_NETWORK_MODES`, so a new mode needs no API change), `dns`, `shell` (sandbox-level and per-exec override), and the workdir/readonly writability contract. The API patches nothing. - **Auth**: `Authorization: Bearer <token>` enforced when `RAY_SANDBOX_API_TOKEN` is set; an Anyscale service can leave it unset because the platform edge already requires the service bearer token. `GET /health` is always open. - **Isolation from core**: importing `ray.experimental.sandbox.http` requires `ray[serve]`; the base sandbox package never imports it. Endpoints (`/api/v1`): create/list/get/delete sandboxes, start/poll execs, PUT/GET files, JSON error envelope (`401/404/409/400/413/422/503/500`). Full table in the new docs section. ## E2E validation Deployed as an Anyscale service (runsc-equipped cluster image) and as a local `serve run`; drove real gVisor sandboxes through create → exec → file transfer → delete, including a full Harbor evaluation run (oracle agent, reward 1.0) against the service URL + token. ## Update (2026-09-24) Rebased onto master and addressed the latest review: - **A DELETE or TTL during boot no longer orphans a container** (from the approval review). A terminate that arrives during the image pull stops the boot before anything starts. One that arrives while `runtime.create` runs waits for it and deletes the new instance before the host exits, and the boot no longer flips a terminated host back to `running`. Tests cover a terminate during start and during pull, a TTL during start, and a boot after terminate; the start-race tests fail on the previous `host.py`. - **Typing:** `spec` and `settings` are `SandboxSpec` / `HostSettings` TypedDicts, and the runtime is typed as `SandboxRuntime`. - **Named-actor cost, measured** (see the scalability thread). The resolver built a fresh `ray.remote(SandboxHost)` for every sandbox, which re-exported the class on each create: 9.15 ms per create on the event loop (Ray 2.58, local), versus 0.76 ms with one cached ActorClass. Resolver calls (create, lookups, kill, list) now run in worker threads, so a GCS round trip never stalls the replica's event loop. Handles of sandboxes created under fresh random ids are cached; deterministic names (client tokens) keep resolving through `ray.get_actor`, whose cache follows actor deaths and re-creations. - **Ids:** random and token-derived ids are `sb-` plus 22 hex chars (88 bits, the facade's shape) instead of 12, and a fresh create skips `get_if_exists`, so a random-id collision fails loudly instead of attaching a second client to someone else's sandbox. - **Errors:** a file write the sandbox can't perform (a directory, a read-only rootfs outside the workdir) returns `409 write_failed` instead of `500`, and one sandbox that fails to describe no longer fails the whole listing. The docs list `write_failed` and the existing `503 sandbox_unavailable`. - **Second pass** (Bugbot on the update): exec, file, and network calls are refused once `terminate()` has started, not only after the status flips. A `client_token` retry re-sends the idempotent `boot()`, so a first boot that never reached the actor can't leave a sandbox pending without its TTL. The `ResourceSpec` docs no longer claim a CPU quota is derived from the request: only `cpu_limit` caps. The resolver and actor-error helpers moved to `http/resolver.py`, and the package resolves its REST exports lazily, so importing it doesn't require FastAPI. ## Related issue number Follow-up to #65570. #65992 and #65942 have merged, so this PR is now a single commit on master. Merge order for the rest of the stack: #65633 → #65839 → #66359. ## Checks - [x] I've signed off every commit (DCO). - [x] I've run pre-commit hooks (`ruff`, `pydoclint`, docstyle, semgrep, import order) on the changed files. - [x] Unit tests run with **no cluster and no runsc** (fake runtime + fake resolver + FastAPI `TestClient`), including an OpenAPI **contract snapshot** that pins the v1 surface: `pytest --import-mode=importlib python/ray/experimental/sandbox/http/tests/{test_http_app,test_sandbox_host,test_http_schemas}.py` → 77 passed. `test_http_integration.py` is gated on the sandbox test env + `runsc` like the existing sandbox tests; in a privileged container with runsc release-20260817 and erofs-utils 1.9.4 (`TEST_SANDBOX=1 RAY_SANDBOX_IGNORE_CGROUPS=1`), it and `sandbox/tests/test_gvisor_backend.py` pass at the top of the stack (40 passed, 1 skipped). `BUILD.bazel` uses the same `sandbox_tests`/`team:core` tags so the existing CI job picks the package up. - [x] Release tests: N/A (experimental, off by default; nothing imports this package unless deployed). - This PR was prepared with AI assistance. It is not a duplicate: it is one step of the Ray Sandbox series (#65570 → #65992 → #65942 → #65633 → #65839 → #66359), and no other open PR covers it. Signed-off-by: xyuzh <[email protected]>
112572d to
61c6850
Compare
## Why are these changes needed? #65992, #65942, and #65633 have merged, and this PR is rebased onto master, so the diff is the facade commit alone. #66359 stacks on it. #65633 (merged) exposes the sandbox control plane as a REST service. This PR adds a gRPC facade in front of the same detached `SandboxHost` actors, so an unmodified third-party sandbox client SDK pointed at this server can create sandboxes, exec commands, and use its filesystem API against a Ray cluster. The facade implements the subset of the SDK's control-plane (`ModalClient`) and command-router (`TaskCommandRouter`) services that its Sandbox API uses. The wire contract is vendored under `http/_proto/` as a minimal protobuf/grpclib stub set generated from checked-in `.proto` sources, so nothing third-party is needed to build or test. gRPC routes on the fully qualified method path and protobuf frames fields by number, so the vendored service, method, and field identifiers reproduce the external service's on-the-wire names verbatim; only the surface the facade uses is declared. The proto packages carry a `ray_sandbox_facade.` prefix that never reaches the wire, so the stubs can share a process with the client SDK. Design: - **Stateless where possible.** Object ids carry their payload (`im-<b64 image ref>`, `st-<b64 env json>`) and the sandbox id doubles as the client task id. Named creates are scoped to the client app and idempotent; a dead actor under a live name is killed and recreated. The one in-process table is the exec table, which keeps finished records for 120 s (the SDK reads output lazily) under a 50,000-record cap, so run a single facade process per cluster. - **Filesystem API via exec emulation.** The SDK implements its filesystem API by exec-ing a helper binary that sandbox images don't contain. The router recognizes its argv and emulates WriteFile / ReadFile / ListFiles with `SandboxHost` file operations; large writes flush in bounded slices. - **Scheduling-aware.** Every actor call is bounded, so an unscheduled actor on a scaling cluster surfaces as `UNAVAILABLE` (retried by the SDK) instead of hanging, and a dead actor maps to `NOT_FOUND` (the SDK's "task shut down" signal). Run with `python -m ray.experimental.sandbox.http.grpc_facade` (requires `grpclib`). Documented in the sandboxes guide under the HTTP API service section. One commit: the vendored wire contract (`.proto` sources, generated stubs, lint excludes), the facade, its tests, and docs. Review fixes that touch code shared with the lower PRs (`name:group` exec-user resolution, a bounded runsc download, a bounded `DELETE`, docs wording) live on those branches and are included here through the stack. Review fixes from the 2026-09-15 pass: - A `cidr_allowlist` the facade cannot enforce now fails `SandboxCreate` with `INVALID_ARGUMENT` instead of granting open egress behind a server-side warning, and `TaskSetNetworkAccess` fails with `UNIMPLEMENTED` instead of being acknowledged and ignored, so a client never runs with fewer restrictions than it asked for. - `TaskExecStart` reserves the exec id before anything reaches the actor and carries the start in its own task. A retry (the SDK retries `UNAVAILABLE`, which the facade answers when the actor has not replied within the scheduling grace) joins that in-flight start instead of running the command again; a start that fails for good is forgotten so a retry may start afresh. A test holds the first start in flight past the grace, retries, and checks the command ran once. - The exec record kind is `sandbox` or `fs` (was `host`), since both run in the sandbox. Update (2026-09-24), rebased onto the new #65633: - **Tests with the Modal client** (review request): `test_modal_client.py` runs the unmodified `modal` SDK (1.5.5) against the facade: create, exec with exit codes and stdout/stderr, `filesystem.write_bytes` / `read_bytes` including the typed not-found error, terminate, and the network-policy mappings. - **The facade and the Modal SDK can share a process.** The vendored protos declared `package modal.client`, which registered the same full names as the SDK's own protos in protobuf's process-wide descriptor pool, so importing both failed with `duplicate symbol 'modal.client.ObjectCreationType'` (hit while load-testing on Anyscale). The packages now carry a `ray_sandbox_facade.` prefix, and the generated gRPC stubs are rewritten to the external method paths, so the wire is unchanged: the regenerated `_grpc.py` files are byte-identical, every served path exists in the SDK's stubs, and the SDK's serialized messages parse into the vendored classes. `_proto/README.md` documents the regeneration step. - **`SandboxTerminate` no longer kills a host whose `terminate()` outlasts the wait** (Bugbot). As in the REST `DELETE`, the queued terminate finishes (with #65633's boot fix it first deletes a container that was still starting) and the host exits on its own. - **Exec records outlive fast traffic.** The SDK reads a command's stdout and stderr lazily, often after `wait()` returned. With the 1,000-record cap, a finished record lasted about a second at 700 execs/s and a late read got `NOT_FOUND`. Finished records now stay 120 s (hard cap 50,000), evicted by a bounded O(1) scan instead of a full-table copy per exec. - **Event loop:** resolver calls (create, lookups, kill) run in worker threads, and creates reuse one ActorClass (#65633). With real `SandboxHost` actors on a local Ray cluster and the Modal SDK issuing 48 concurrent creates, throughput went from 56 to 353–550 creates/s, the create RPC's p50 from 387 ms to 78–104 ms, and the facade's worst event-loop stall during the burst from 838 ms to 36 ms. Exec throughput is unchanged (about 1.3k/s on that machine). - **Malformed input is `INVALID_ARGUMENT`, not `INTERNAL`:** a bare `FROM` line, and fs-tools commands whose JSON isn't an object with an object payload (gemini, on #66359). - The image-seeding symlink finding (Bugbot) was fixed in #65992 before it merged (`_resolve_in_root`); `image_utils.py` is no longer part of this diff. - **Second pass** (Bugbot on the update): importing the facade no longer needs FastAPI (it takes the resolver from #65633's `http/resolver.py`), so it needs only `grpclib` and `ray[default]`, as the docs now say. Buffered `WriteFile` content is capped at `max_file_bytes` (`RESOURCE_EXHAUSTED` past it), and named-create retries re-send the idempotent `boot()`. ## Related issue number Follows #65633 (merged). ## Checks - `test_grpc_facade.py` drives the facade end to end over gRPC with the vendored stubs, and `test_modal_client.py` with the unmodified Modal SDK, both backed by the same fake resolver and runtime seams the REST app tests use. They skip when `grpclib` (and, for the latter, `modal`) is absent, so the sandbox core CI job, which installs neither, adds no new dependency. Ran locally with grpclib 0.4.9 and modal 1.5.5: `pytest --import-mode=importlib python/ray/experimental/sandbox/http/tests/` → 101 passed (21 wire tests, 3 Modal-client tests, and the 77-test HTTP API suite). - The facade module is never imported from `sandbox/__init__.py` or the REST `app.py` import graph, so it stays inert unless explicitly run. - `ruff check`, `ruff check --select I`, `black`, and `pydoclint` (the pre-commit versions and flags) pass on the changed files. - This PR was prepared with AI assistance. It is not a duplicate: it is one step of the Ray Sandbox series (#65570 → #65992 → #65942 → #65633 → #65839 → #66359), and no other open PR covers it (#66089, a KubeRay + Modal SDK guide, builds on it). Signed-off-by: xyuzh <[email protected]>
## Description The Ray Sandbox gRPC facade (`ray.experimental.sandbox.http.grpc_facade`) served sandbox create, exec, and file read/write to any client that could reach its port. Unlike the REST app, it never read `RAY_SANDBOX_API_TOKEN`, so even an operator who wanted to lock it down couldn't, and the documented quickstart binds `--host 0.0.0.0`. With this PR: - **The token is required on every RPC.** When `RAY_SANDBOX_API_TOKEN` is set, a call that doesn't present it fails with `UNAUTHENTICATED` before its handler reads the request. - A client presents the token the way the client SDK already sends credentials: as its token secret (`x-modal-token-secret`, from `MODAL_TOKEN_SECRET`), or as `authorization: Bearer <token>`, the REST app's form, which `MODAL_OVERRIDE_HEADERS` can also send. - `TaskGetCommandRouterAccess` hands out the token as the command router's credential. The SDK then sends it as a bearer token on every exec and file call, so an unmodified client only needs `MODAL_TOKEN_SECRET` set. - A bearer-only check wouldn't work with the SDK: its control-plane calls carry the token secret, and its router calls carry only the credential that `TaskGetCommandRouterAccess` returned. - **The check is bound to the servicers, not to one server.** `_TokenGate` wraps the handler table (`__mapping__`) that `grpclib.server.Server` dispatches through. So every server built from `build_servicers` is gated, including RPCs added later, such as #66359's `TaskSetNetworkAccess`. Without a token the table is returned unchanged. - **The CLI fails closed.** Without a token, `python -m ray.experimental.sandbox.http.grpc_facade` refuses a non-loopback `--host` unless `--allow-unauthenticated` is passed. - Keeping the facade on a private network isn't enough on its own. The facade's sandboxes get open egress by default and can reach any address their node can, including the facade's. So a tokenless facade on a network address would also serve the code running inside them. - Loopback binds stay tokenless, since `--disable-host-loopback` keeps sandboxes off the node's loopback. - **Docs.** The gRPC section now covers: - the token; - the trust model: one token controls every sandbox in the namespace, as with the REST token, with no per-client isolation; - the TLS requirement; - a fix for the stale network bullet: allowlists are refused, not widened. - **REST.** `require_bearer_token` compares bytes, so a non-ASCII `Authorization` header gets a 401 instead of a `TypeError` and a 500. **Behavior change:** a tokenless facade started with a non-loopback `--host`, as the old quickstart did, now exits with an error that names `RAY_SANDBOX_API_TOKEN` and `--allow-unauthenticated`. **This PR also fixes the failing `:ray: core: sandbox tests` job** (for example premerge build 74278 and microcheck build 55110). - `test_image_utils.py::test_seeding_stays_inside_the_tree` linked the fake image's `/tmp` to an absolute path under pytest's `tmp_path`, which is itself under `/tmp` in CI. - From the image's point of view that's a symlink loop. `_resolve_in_root` correctly reports it as `ELOOP`, so nothing was seeded. - The test now gives `tmp` its own tree with a relative link. The product code is unchanged. - The test only passed on macOS because `tmp_path` lives under `/private/var/folders` there. ## Related issues Related to #65839 (the facade) and #65352 (sandboxing umbrella). Not a duplicate: no open PR or issue covers facade authentication. I searched open PRs and issues for `grpc_facade`, `RAY_SANDBOX_API_TOKEN`, and sandbox authentication. ## Additional information **Tests run.** Environment: macOS, Python 3.12, the ray 2.58 wheel with this branch's sandbox package overlaid, grpclib 0.4.9. | Command | Result | | --- | --- | | `pytest --import-mode=importlib python/ray/experimental/sandbox/http/tests` | 130 passed, 8 skipped (modal not installed, `TEST_SANDBOX` unset) | | The same, with `RAY_SANDBOX_API_TOKEN=ambient` exported | 130 passed, 8 skipped | | `uv run --with modal==1.5.5 pytest .../http/tests/test_modal_client.py` | 6 passed | | `uv run --with modal==1.5.1 pytest .../http/tests/test_modal_client.py` | 5 passed, 1 skipped (1.5.1 can't send custom headers) | | The new auth tests against `origin/master`'s `grpc_facade.py` | 29 failed, as expected | | `test_image_utils.py::test_seeding_stays_inside_the_tree`, with the default `tmp_path` and with `tmp_path` under `/tmp` | Passed both ways (the old test fails with `tmp_path` under `/tmp`) | | `python -m ray.experimental.sandbox.http.grpc_facade --host 0.0.0.0` without a token | Exit 2, before connecting to the cluster | | Unauthenticated create path replayed against a local Ray cluster | Anonymous and wrong-token `AppGetOrCreate`, `ImageGetOrCreate`, and `SandboxCreate` return `UNAUTHENTICATED` and create no actor. With the token, a `SandboxHost` actor is created and then terminated. | | `pre-commit` (ruff, pydoclint, docstyle, import order), black 22.10.0, API param coverage check | Pass | `test_grpc_facade.py` and `test_modal_client.py` skip in CI because grpclib and modal aren't in the CI image, so the auth tests above ran locally only. AI assistance was used to write this change. Signed-off-by: xyuzh <[email protected]> Co-authored-by: Philipp Moritz <[email protected]>
…ay-project#65633) ## Why are these changes needed? Ray Sandbox (`ray.experimental.sandbox`) can currently only be driven from inside the cluster as Ray actors. This PR adds an **experimental HTTP API service** so sandboxes can be managed from outside the cluster with nothing but an HTTP client and a bearer token — for example as an Anyscale service, or from agent-evaluation frameworks (a Harbor `ray-sandbox` environment built on this API is submitted alongside: harbor-framework/harbor PR to follow). This is the second step of the plan from ray-project#65570 (first: make the Python API run Docker-built images out of the box; second: make Ray Sandbox consumable as a standalone service). ## Design ``` client ──HTTP/bearer──▶ FastAPI on Ray Serve (ray.experimental.sandbox.http, stateless replicas) │ ray.get_actor(name, namespace) ▼ SandboxHost — named, detached actor per sandbox │ composes SandboxRuntime ▼ gVisor (runsc) on the node ``` - **Named detached actors are the registry.** Any replica resolves any sandbox by name; list = `ray.util.list_named_actors`. The service keeps no state, so replicas scale/restart freely. - **Async submit + poll.** Image pulls and commands outlive HTTP requests and LB limits, so `POST /sandboxes` and `POST .../execs` return `202` immediately; clients poll, optionally long-polling with `wait_seconds` (≤ 30 s per request). Boot progress is observable: `pending → pulling → starting → running | error`. - **One TTL owner.** The API's TTL reclaims the sandbox **and** its hosting actor (the core runtime TTL is deliberately disabled here); an abandoned sandbox never strands an actor reservation. - **Everything sandbox-behavioral is the core `SandboxConfig`'s** (ray-project#65570): capabilities (default `DOCKER_DEFAULT_CAPABILITIES`, sets written exactly), network modes (validated against `VALID_NETWORK_MODES`, so a new mode needs no API change), `dns`, `shell` (sandbox-level and per-exec override), and the workdir/readonly writability contract. The API patches nothing. - **Auth**: `Authorization: Bearer <token>` enforced when `RAY_SANDBOX_API_TOKEN` is set; an Anyscale service can leave it unset because the platform edge already requires the service bearer token. `GET /health` is always open. - **Isolation from core**: importing `ray.experimental.sandbox.http` requires `ray[serve]`; the base sandbox package never imports it. Endpoints (`/api/v1`): create/list/get/delete sandboxes, start/poll execs, PUT/GET files, JSON error envelope (`401/404/409/400/413/422/503/500`). Full table in the new docs section. ## E2E validation Deployed as an Anyscale service (runsc-equipped cluster image) and as a local `serve run`; drove real gVisor sandboxes through create → exec → file transfer → delete, including a full Harbor evaluation run (oracle agent, reward 1.0) against the service URL + token. ## Update (2026-09-24) Rebased onto master and addressed the latest review: - **A DELETE or TTL during boot no longer orphans a container** (from the approval review). A terminate that arrives during the image pull stops the boot before anything starts. One that arrives while `runtime.create` runs waits for it and deletes the new instance before the host exits, and the boot no longer flips a terminated host back to `running`. Tests cover a terminate during start and during pull, a TTL during start, and a boot after terminate; the start-race tests fail on the previous `host.py`. - **Typing:** `spec` and `settings` are `SandboxSpec` / `HostSettings` TypedDicts, and the runtime is typed as `SandboxRuntime`. - **Named-actor cost, measured** (see the scalability thread). The resolver built a fresh `ray.remote(SandboxHost)` for every sandbox, which re-exported the class on each create: 9.15 ms per create on the event loop (Ray 2.58, local), versus 0.76 ms with one cached ActorClass. Resolver calls (create, lookups, kill, list) now run in worker threads, so a GCS round trip never stalls the replica's event loop. Handles of sandboxes created under fresh random ids are cached; deterministic names (client tokens) keep resolving through `ray.get_actor`, whose cache follows actor deaths and re-creations. - **Ids:** random and token-derived ids are `sb-` plus 22 hex chars (88 bits, the facade's shape) instead of 12, and a fresh create skips `get_if_exists`, so a random-id collision fails loudly instead of attaching a second client to someone else's sandbox. - **Errors:** a file write the sandbox can't perform (a directory, a read-only rootfs outside the workdir) returns `409 write_failed` instead of `500`, and one sandbox that fails to describe no longer fails the whole listing. The docs list `write_failed` and the existing `503 sandbox_unavailable`. - **Second pass** (Bugbot on the update): exec, file, and network calls are refused once `terminate()` has started, not only after the status flips. A `client_token` retry re-sends the idempotent `boot()`, so a first boot that never reached the actor can't leave a sandbox pending without its TTL. The `ResourceSpec` docs no longer claim a CPU quota is derived from the request: only `cpu_limit` caps. The resolver and actor-error helpers moved to `http/resolver.py`, and the package resolves its REST exports lazily, so importing it doesn't require FastAPI. ## Related issue number Follow-up to ray-project#65570. ray-project#65992 and ray-project#65942 have merged, so this PR is now a single commit on master. Merge order for the rest of the stack: ray-project#65633 → ray-project#65839 → ray-project#66359. ## Checks - [x] I've signed off every commit (DCO). - [x] I've run pre-commit hooks (`ruff`, `pydoclint`, docstyle, semgrep, import order) on the changed files. - [x] Unit tests run with **no cluster and no runsc** (fake runtime + fake resolver + FastAPI `TestClient`), including an OpenAPI **contract snapshot** that pins the v1 surface: `pytest --import-mode=importlib python/ray/experimental/sandbox/http/tests/{test_http_app,test_sandbox_host,test_http_schemas}.py` → 77 passed. `test_http_integration.py` is gated on the sandbox test env + `runsc` like the existing sandbox tests; in a privileged container with runsc release-20260817 and erofs-utils 1.9.4 (`TEST_SANDBOX=1 RAY_SANDBOX_IGNORE_CGROUPS=1`), it and `sandbox/tests/test_gvisor_backend.py` pass at the top of the stack (40 passed, 1 skipped). `BUILD.bazel` uses the same `sandbox_tests`/`team:core` tags so the existing CI job picks the package up. - [x] Release tests: N/A (experimental, off by default; nothing imports this package unless deployed). - This PR was prepared with AI assistance. It is not a duplicate: it is one step of the Ray Sandbox series (ray-project#65570 → ray-project#65992 → ray-project#65942 → ray-project#65633 → ray-project#65839 → ray-project#66359), and no other open PR covers it. Signed-off-by: xyuzh <[email protected]>
…roject#65839) ## Why are these changes needed? ray-project#65992, ray-project#65942, and ray-project#65633 have merged, and this PR is rebased onto master, so the diff is the facade commit alone. ray-project#66359 stacks on it. ray-project#65633 (merged) exposes the sandbox control plane as a REST service. This PR adds a gRPC facade in front of the same detached `SandboxHost` actors, so an unmodified third-party sandbox client SDK pointed at this server can create sandboxes, exec commands, and use its filesystem API against a Ray cluster. The facade implements the subset of the SDK's control-plane (`ModalClient`) and command-router (`TaskCommandRouter`) services that its Sandbox API uses. The wire contract is vendored under `http/_proto/` as a minimal protobuf/grpclib stub set generated from checked-in `.proto` sources, so nothing third-party is needed to build or test. gRPC routes on the fully qualified method path and protobuf frames fields by number, so the vendored service, method, and field identifiers reproduce the external service's on-the-wire names verbatim; only the surface the facade uses is declared. The proto packages carry a `ray_sandbox_facade.` prefix that never reaches the wire, so the stubs can share a process with the client SDK. Design: - **Stateless where possible.** Object ids carry their payload (`im-<b64 image ref>`, `st-<b64 env json>`) and the sandbox id doubles as the client task id. Named creates are scoped to the client app and idempotent; a dead actor under a live name is killed and recreated. The one in-process table is the exec table, which keeps finished records for 120 s (the SDK reads output lazily) under a 50,000-record cap, so run a single facade process per cluster. - **Filesystem API via exec emulation.** The SDK implements its filesystem API by exec-ing a helper binary that sandbox images don't contain. The router recognizes its argv and emulates WriteFile / ReadFile / ListFiles with `SandboxHost` file operations; large writes flush in bounded slices. - **Scheduling-aware.** Every actor call is bounded, so an unscheduled actor on a scaling cluster surfaces as `UNAVAILABLE` (retried by the SDK) instead of hanging, and a dead actor maps to `NOT_FOUND` (the SDK's "task shut down" signal). Run with `python -m ray.experimental.sandbox.http.grpc_facade` (requires `grpclib`). Documented in the sandboxes guide under the HTTP API service section. One commit: the vendored wire contract (`.proto` sources, generated stubs, lint excludes), the facade, its tests, and docs. Review fixes that touch code shared with the lower PRs (`name:group` exec-user resolution, a bounded runsc download, a bounded `DELETE`, docs wording) live on those branches and are included here through the stack. Review fixes from the 2026-09-15 pass: - A `cidr_allowlist` the facade cannot enforce now fails `SandboxCreate` with `INVALID_ARGUMENT` instead of granting open egress behind a server-side warning, and `TaskSetNetworkAccess` fails with `UNIMPLEMENTED` instead of being acknowledged and ignored, so a client never runs with fewer restrictions than it asked for. - `TaskExecStart` reserves the exec id before anything reaches the actor and carries the start in its own task. A retry (the SDK retries `UNAVAILABLE`, which the facade answers when the actor has not replied within the scheduling grace) joins that in-flight start instead of running the command again; a start that fails for good is forgotten so a retry may start afresh. A test holds the first start in flight past the grace, retries, and checks the command ran once. - The exec record kind is `sandbox` or `fs` (was `host`), since both run in the sandbox. Update (2026-09-24), rebased onto the new ray-project#65633: - **Tests with the Modal client** (review request): `test_modal_client.py` runs the unmodified `modal` SDK (1.5.5) against the facade: create, exec with exit codes and stdout/stderr, `filesystem.write_bytes` / `read_bytes` including the typed not-found error, terminate, and the network-policy mappings. - **The facade and the Modal SDK can share a process.** The vendored protos declared `package modal.client`, which registered the same full names as the SDK's own protos in protobuf's process-wide descriptor pool, so importing both failed with `duplicate symbol 'modal.client.ObjectCreationType'` (hit while load-testing on Anyscale). The packages now carry a `ray_sandbox_facade.` prefix, and the generated gRPC stubs are rewritten to the external method paths, so the wire is unchanged: the regenerated `_grpc.py` files are byte-identical, every served path exists in the SDK's stubs, and the SDK's serialized messages parse into the vendored classes. `_proto/README.md` documents the regeneration step. - **`SandboxTerminate` no longer kills a host whose `terminate()` outlasts the wait** (Bugbot). As in the REST `DELETE`, the queued terminate finishes (with ray-project#65633's boot fix it first deletes a container that was still starting) and the host exits on its own. - **Exec records outlive fast traffic.** The SDK reads a command's stdout and stderr lazily, often after `wait()` returned. With the 1,000-record cap, a finished record lasted about a second at 700 execs/s and a late read got `NOT_FOUND`. Finished records now stay 120 s (hard cap 50,000), evicted by a bounded O(1) scan instead of a full-table copy per exec. - **Event loop:** resolver calls (create, lookups, kill) run in worker threads, and creates reuse one ActorClass (ray-project#65633). With real `SandboxHost` actors on a local Ray cluster and the Modal SDK issuing 48 concurrent creates, throughput went from 56 to 353–550 creates/s, the create RPC's p50 from 387 ms to 78–104 ms, and the facade's worst event-loop stall during the burst from 838 ms to 36 ms. Exec throughput is unchanged (about 1.3k/s on that machine). - **Malformed input is `INVALID_ARGUMENT`, not `INTERNAL`:** a bare `FROM` line, and fs-tools commands whose JSON isn't an object with an object payload (gemini, on ray-project#66359). - The image-seeding symlink finding (Bugbot) was fixed in ray-project#65992 before it merged (`_resolve_in_root`); `image_utils.py` is no longer part of this diff. - **Second pass** (Bugbot on the update): importing the facade no longer needs FastAPI (it takes the resolver from ray-project#65633's `http/resolver.py`), so it needs only `grpclib` and `ray[default]`, as the docs now say. Buffered `WriteFile` content is capped at `max_file_bytes` (`RESOURCE_EXHAUSTED` past it), and named-create retries re-send the idempotent `boot()`. ## Related issue number Follows ray-project#65633 (merged). ## Checks - `test_grpc_facade.py` drives the facade end to end over gRPC with the vendored stubs, and `test_modal_client.py` with the unmodified Modal SDK, both backed by the same fake resolver and runtime seams the REST app tests use. They skip when `grpclib` (and, for the latter, `modal`) is absent, so the sandbox core CI job, which installs neither, adds no new dependency. Ran locally with grpclib 0.4.9 and modal 1.5.5: `pytest --import-mode=importlib python/ray/experimental/sandbox/http/tests/` → 101 passed (21 wire tests, 3 Modal-client tests, and the 77-test HTTP API suite). - The facade module is never imported from `sandbox/__init__.py` or the REST `app.py` import graph, so it stays inert unless explicitly run. - `ruff check`, `ruff check --select I`, `black`, and `pydoclint` (the pre-commit versions and flags) pass on the changed files. - This PR was prepared with AI assistance. It is not a duplicate: it is one step of the Ray Sandbox series (ray-project#65570 → ray-project#65992 → ray-project#65942 → ray-project#65633 → ray-project#65839 → ray-project#66359), and no other open PR covers it (ray-project#66089, a KubeRay + Modal SDK guide, builds on it). Signed-off-by: xyuzh <[email protected]>
…#66675) ## Description The Ray Sandbox gRPC facade (`ray.experimental.sandbox.http.grpc_facade`) served sandbox create, exec, and file read/write to any client that could reach its port. Unlike the REST app, it never read `RAY_SANDBOX_API_TOKEN`, so even an operator who wanted to lock it down couldn't, and the documented quickstart binds `--host 0.0.0.0`. With this PR: - **The token is required on every RPC.** When `RAY_SANDBOX_API_TOKEN` is set, a call that doesn't present it fails with `UNAUTHENTICATED` before its handler reads the request. - A client presents the token the way the client SDK already sends credentials: as its token secret (`x-modal-token-secret`, from `MODAL_TOKEN_SECRET`), or as `authorization: Bearer <token>`, the REST app's form, which `MODAL_OVERRIDE_HEADERS` can also send. - `TaskGetCommandRouterAccess` hands out the token as the command router's credential. The SDK then sends it as a bearer token on every exec and file call, so an unmodified client only needs `MODAL_TOKEN_SECRET` set. - A bearer-only check wouldn't work with the SDK: its control-plane calls carry the token secret, and its router calls carry only the credential that `TaskGetCommandRouterAccess` returned. - **The check is bound to the servicers, not to one server.** `_TokenGate` wraps the handler table (`__mapping__`) that `grpclib.server.Server` dispatches through. So every server built from `build_servicers` is gated, including RPCs added later, such as ray-project#66359's `TaskSetNetworkAccess`. Without a token the table is returned unchanged. - **The CLI fails closed.** Without a token, `python -m ray.experimental.sandbox.http.grpc_facade` refuses a non-loopback `--host` unless `--allow-unauthenticated` is passed. - Keeping the facade on a private network isn't enough on its own. The facade's sandboxes get open egress by default and can reach any address their node can, including the facade's. So a tokenless facade on a network address would also serve the code running inside them. - Loopback binds stay tokenless, since `--disable-host-loopback` keeps sandboxes off the node's loopback. - **Docs.** The gRPC section now covers: - the token; - the trust model: one token controls every sandbox in the namespace, as with the REST token, with no per-client isolation; - the TLS requirement; - a fix for the stale network bullet: allowlists are refused, not widened. - **REST.** `require_bearer_token` compares bytes, so a non-ASCII `Authorization` header gets a 401 instead of a `TypeError` and a 500. **Behavior change:** a tokenless facade started with a non-loopback `--host`, as the old quickstart did, now exits with an error that names `RAY_SANDBOX_API_TOKEN` and `--allow-unauthenticated`. **This PR also fixes the failing `:ray: core: sandbox tests` job** (for example premerge build 74278 and microcheck build 55110). - `test_image_utils.py::test_seeding_stays_inside_the_tree` linked the fake image's `/tmp` to an absolute path under pytest's `tmp_path`, which is itself under `/tmp` in CI. - From the image's point of view that's a symlink loop. `_resolve_in_root` correctly reports it as `ELOOP`, so nothing was seeded. - The test now gives `tmp` its own tree with a relative link. The product code is unchanged. - The test only passed on macOS because `tmp_path` lives under `/private/var/folders` there. ## Related issues Related to ray-project#65839 (the facade) and ray-project#65352 (sandboxing umbrella). Not a duplicate: no open PR or issue covers facade authentication. I searched open PRs and issues for `grpc_facade`, `RAY_SANDBOX_API_TOKEN`, and sandbox authentication. ## Additional information **Tests run.** Environment: macOS, Python 3.12, the ray 2.58 wheel with this branch's sandbox package overlaid, grpclib 0.4.9. | Command | Result | | --- | --- | | `pytest --import-mode=importlib python/ray/experimental/sandbox/http/tests` | 130 passed, 8 skipped (modal not installed, `TEST_SANDBOX` unset) | | The same, with `RAY_SANDBOX_API_TOKEN=ambient` exported | 130 passed, 8 skipped | | `uv run --with modal==1.5.5 pytest .../http/tests/test_modal_client.py` | 6 passed | | `uv run --with modal==1.5.1 pytest .../http/tests/test_modal_client.py` | 5 passed, 1 skipped (1.5.1 can't send custom headers) | | The new auth tests against `origin/master`'s `grpc_facade.py` | 29 failed, as expected | | `test_image_utils.py::test_seeding_stays_inside_the_tree`, with the default `tmp_path` and with `tmp_path` under `/tmp` | Passed both ways (the old test fails with `tmp_path` under `/tmp`) | | `python -m ray.experimental.sandbox.http.grpc_facade --host 0.0.0.0` without a token | Exit 2, before connecting to the cluster | | Unauthenticated create path replayed against a local Ray cluster | Anonymous and wrong-token `AppGetOrCreate`, `ImageGetOrCreate`, and `SandboxCreate` return `UNAUTHENTICATED` and create no actor. With the token, a `SandboxHost` actor is created and then terminated. | | `pre-commit` (ruff, pydoclint, docstyle, import order), black 22.10.0, API param coverage check | Pass | `test_grpc_facade.py` and `test_modal_client.py` skip in CI because grpclib and modal aren't in the CI image, so the auth tests above ran locally only. AI assistance was used to write this change. Signed-off-by: xyuzh <[email protected]> Co-authored-by: Philipp Moritz <[email protected]>
## Why are these changes needed? Style and grammar pass over the top-level Ray Core pages under `doc/source/core/`, meaning the pages directly in that directory and not its subdirectories, against `doc/source/ray-contribute/writing-style.md` and its "Writing Ray Core docs" terms. This is the first prose layer stacked on #66640 (Core Vale term library), which is stacked on #66605 (the `ray-core/` to `core/` move). Later layers cover `tasks/`, `actors/`, `objects/`, `patterns/`, `fault-tolerance/`, `scheduling/`, and the remaining subdirectories. The edits are wording, voice, tense, list structure, and admonitions. No code block, `{ref}` or `{doc}` target, or existing `(label)=` anchor changed. Where a heading's words changed, a `(old-slug)=` label keeps the old URL fragment working. ### Corrections verified against source These change what a sentence says, so they're called out for review: - `starting-ray.md`: the `ray.init()` address lookup order listed `RAY_ADDRESS` before an explicit `address` argument. `ray.init()` in `python/ray/_private/worker.py` uses `RAY_ADDRESS` only when `address` is unset or `"auto"`, so the list now puts the explicit address first. - `tips-for-first-time.md`: `np.zeros((5000, 5000))` has 25 million entries, not 2.5 million. The speedup from the page's own output (1.08 s to 0.133 s) is about 8x, not 7x. - `handling-dependencies.md`: the `pip` and `uv` dict forms take four fields, not three (`python/ray/_private/runtime_env/validation.py`). - `ray-generator.md`: a sentence that repeated the previous paragraph's argument list and didn't parse now describes what the mixed-input example does. - `configure.md`: split malformed code spans that wrapped prose and file names, and removed a stray `\#` that rendered as a literal `#`. ### Pre-existing claims, tracked separately These claims were already on the pages, and this pass kept them as written. They don't block this PR. #66790 fixes the mechanical ones and #66791 corrects the ones that the source settles, both stacked on #66677. The rest need a Core engineering decision and are tracked separately: - `head-node-memory-management.md`: Best practices says to match memory and GPU requests to limits, while the `important` note and the example say memory and CPU. Which is right? - `configure.md`: "a maximum of 10,000 workers" per node, while the default worker port range 10002-19999 is 9,998 ports. - `handling-dependencies.md`: "A local path must be a directory path" and "A remote URI must link directly to a zip file" contradict the API reference, which accepts local files and `.whl` for `py_modules` and `.tar.gz`, `.tgz`, and `.tar.xz` remote archives. - `type-hint.md`: the Pattern 2 code sample calls `func.remote()` on an undecorated function and is missing imports. `ray-dag.md` leaves the Compiled Graph note untouched, because #66464 rewrites it for the deprecation. `sandboxes.md` is held out of this PR so it doesn't conflict with the open sandbox feature PRs #66359, #66470, and #66471. It gets its own pass after those land. ## Related issue number None. Not a duplicate: open PRs touching these pages are #66605 and #66640 (this stack), #66464 (Compiled Graph deprecation) and the sandbox feature PRs #66359, #66470, and #66471. This PR stays out of the text those PRs change, as described above. ## Checks - `vale doc/source/core/*.md` from the repo root: no `Core.Terms` alerts. This PR adds the terms the pass surfaced to the `General` and `Core` accept lists, which removes 35 alerts across `doc/source`, all on those tokens, and adds none. Remaining alerts are passives or "currently" kept on purpose, the Azure term "account name" (`Google.WordList`), and a `Vale.Terms` false positive on "the rest". Sandbox-only terms wait for the `sandboxes.md` pass. - `codespell doc/source/core/*.md`: only the `org.testng` Java import false positive. - Per-file invariant check against the pre-edit files: fenced-code count, role-target multiset, and URLs unchanged. Added labels are the only anchor changes. - `doc/.claude/skills/ray-soft-wrap/scripts/softwrap.py --check doc/source/core/*.md`: clean, with one pre-existing hard wrap joined and confirmed whitespace-only by `verify.py`. - Colon-fence directives parse and nest as before (markdown-it with the MyST colon-fence plugin). - Full `-W` doc build: relying on the Read the Docs preview. AI assistance (Claude Code) was used to draft these edits. I reviewed every changed line. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
## Why are these changes needed? Style and grammar pass over the remaining Ray Core prose pages, against `doc/source/ray-contribute/writing-style.md` and its "Writing Ray Core docs" terms. This is the fifth and last prose layer of the Ray Core stack: `compiled-graph/`, `direct-transport/`, `internals/`, `accelerator-types.md`, `api/index.md`, `examples/index.md`, and `examples/monte-carlo-pi.md`. It's stacked on #66672 (fault tolerance and scheduling), which is stacked on #66667 (design patterns), #66666 (tasks, actors, and objects), #66642 (top-level pages), #66640 (Core Vale term library), and #66605 (the `ray-core/` to `core/` move). Three things are out of scope. `sandboxes.md` and `api/sandboxes.md` are left for a follow-up, because five open PRs (#66675, #66471, #66470, #66359, #65898) make large edits to them. The autodoc `.rst` API pages and the example notebooks aren't prose pages. The edits are voice, person, tense, word choice, and list structure. First-person plural is now "you" or an imperative. Per the Core terms table, "Raylet" mid-sentence is now "raylet", "plasma store" is now "Plasma store", and "via" is now "through". Parenthetical asides and em dashes are now separate sentences or lists, and ordered lists use `1.` throughout. `internals/object-spilling.md` had 24 em dashes and now has none. Two MyST conversion artifacts were inline pseudo-lists (`\*` and `\-` bullets in one paragraph) in `compiled-graph/quickstart.md` and `internals/ray-event-exporter.md`. A third was a numbered list collapsed into one paragraph in `direct-transport/index.md`. All three are now real lists. Compiled Graph got a light pass, because #66464 deprecates it. The lines where #66464 inserts its deprecation banners are byte-identical, including each page's front matter, H1, and the paragraph after it, plus the landing page's beta warning. #66464's doc changes still apply cleanly on top of this branch. Headings changed only in case, except two whose slugs changed. On `compiled-graph/troubleshooting.md`, "Explicitly teardown before reusing the same actors" is now "Explicitly tear down...". On `internals/object-spilling.md`, "Primary vs. Secondary Copies" is now "Primary versus secondary copies". Both keep their old URL fragments through MyST labels named after the old slugs. No link in `doc/source` targets either old slug. No code block, role target, or URL changed beyond the fixes below. ### Fixes Each of these is checked against the page itself: - `compiled-graph/troubleshooting.md`: two `{ref}` links pointed at each other's sections. The item about tearing down a Compiled Graph before running another on the same actor linked to "Return NumPy arrays". The item about zero-copy values blocking later executions linked to the teardown section. Each now links to the section it describes. - `compiled-graph/quickstart.md`: "a ActorDiedError" is now "an". - `internals/metric-exporter.md`: the cardinality level labels were written as `` **\`legacy\`** ``, which rendered literal backticks. They're now bold code. - `examples/monte-carlo-pi.md`: the `{image}` directive had no alt text. ### Pre-existing claims, tracked separately These claims were already on the pages, and this pass kept them as written. They don't block this PR. #66790 fixes the mechanical ones and #66791 corrects the ones that the source settles, both stacked on #66677. The rest need a Core engineering decision and are tracked separately: - `compiled-graph/quickstart.md` and `troubleshooting.md`: several roadmap sentences, such as "Ray might detect such errors in the future", "The Ray team also plans to support custom communicators", and "Collective communication operations are coming soon". With #66464 deprecating Compiled Graph, should these go? - `compiled-graph/overlap.md`: "enabling `_overlap_gpu_communication` improves latency by about 14%". Latency goes down; the sample output shows about 13.7% less. Should this say "reduces latency"? - `compiled-graph/profiling.md`: the heading "Nsight system profiler" and the prose "Nsight system profiling". NVIDIA's product is Nsight Systems. - `direct-transport/index.md`: the NCCL section lists using `create_collective_group` as a "main difference" from the Gloo example, but the Gloo example also uses it. - `direct-transport/custom-tensor-transport.md`: the "Out-of-order actors" limitation looks like a special case of the "Actor creation and task submission from different processes" limitation that follows it. Is being out of order a separate trigger? - `internals/task-lifecycle.md`: the execution steps say the executor pulls arguments from a remote Plasma store if needed before it runs the function. A later step says the data was already pulled during scheduling. Which is right? - `internals/object-spilling.md`: - The architecture section says the raylet decides what to spill by least recently used (LRU) order and pinning status. The batch construction section says `TryToSpillObjects` walks `pinned_objects_` in order. Is spill selection LRU? - The prose says spilling starts when usage "exceeds" `object_spilling_threshold`, but the trigger table uses `>=`. - The configuration list calls `object_spilling_threshold` a fraction of available object store memory, while the trigger table defines it as primary object bytes divided by capacity. - Is `max_io_workers` a total, or per worker type, as the worker pool section says? - "GCS" in the cloud storage passages means Google Cloud Storage. On a Ray Core page, it reads as Ray's GCS. Should it be spelled out? - `internals/ray-event-exporter.md`: - The page says it describes Ray 2.52.1, but `RAY_DASHBOARD_AGGREGATOR_AGENT_EXPOSABLE_EVENT_TYPES` says `ALL` is supported in Ray 2.54.0 and later. - The Step 5 link text names `RayEventRecorder::AddEvent()`, but it points at the line the page elsewhere calls `AddEvents()`. - The Step 6 aggregator link uses the same anchor as Step 4. - `internals/metric-exporter.md`: the `DoubleGaugeCallback` link is pinned to commit `52ed7e3`, while every other link on the page uses `05e7efd5`. The `OpenTelemetryMetricRecorder::SetMetricValue()` link points into `src/ray/stats/metric.cc`. - `internals/token-authentication.md`: two notes both say that new HTTP services must add the middleware and header injection themselves. Should one go? - `compiled-graph/troubleshooting.md`: the page says Compiled Graph supports only peer-to-peer GPU transfers and that collective operations are planned, but `ray.experimental.collective` exports `allreduce`, `allgather`, and `reducescatter` with DAG wrappers. Is the limitation stale? - `internals/metric-exporter.md`: the page says C++ metrics register lazily on first use. With OpenTelemetry enabled, registration seems to happen when the `ray::stats` metric object is constructed (`src/ray/stats/metric.h`), and `SetMetricValue` fails on an unregistered name. - `internals/object-spilling.md`: the page names `ReleaseFreedObject()`; the function is `LocalObjectManager::ReleaseFreedLocalObject`. The two `PopDeleteWorker` links point at different lines of `worker_pool.cc`. - `internals/ray-event-exporter.md`: `_can_expose_event` and the event filtering now live in `publisher/async_publisher_client.py`, not `aggregator_agent.py`, and `ALL` bypasses the exposable-types list. - `internals/port-service-discovery.md`: the page calls core workers C++ processes. The core worker is a C++ library inside Python, Java, or C++ worker processes. - `examples/monte-carlo-pi.md`: the sampling task is described as sampling "up to" `num_samples`, but the code samples exactly `num_samples`. - `examples/index.md`: several list-table link texts don't match the titles of the notebooks they link to, such as "Build Batch Prediction Using Ray" for "Batch Prediction with Ray Core". ## Related issue number None. Not a duplicate. #66464 edits the Compiled Graph pages; see above. ## Checks - `vale` on the 21 pages from the repo root: 1,228 alerts before the pass, 372 after all three commits. The remaining alerts are intentional passives where the page names no actor, "currently" and "for now" where they mark an alpha feature or a temporary limitation, acronym alerts that fire after the acronym is spelled out, code identifiers used as link text, alerts on the lines protected for #66464, and Mermaid diagram source in `object-spilling.md`. - The third commit adds Perfetto, GDRCopy, `inlines` and `inlined`, `unlink`, `temporality`, `misconfiguration`, and `microbenchmark` to the `General` accept list, and `evictable` and `exposable` to the `Core` accept list. Across `doc/source` that removes 16 alerts and adds none. - `codespell` on the 21 pages: clean apart from `asend`, the Python async generator method. - Per-file invariant check against the pre-edit files: fenced-code count, role-target multiset, and URLs unchanged. The only anchor changes are the two legacy-slug labels. Line-count changes come from the new lists, the repaired pseudo-lists, and blank-line cleanup. - `doc/.claude/skills/ray-soft-wrap/scripts/softwrap.py --check`: clean. - `git apply --check` of #66464's doc hunks onto this branch, with paths remapped to `doc/source/core/`: clean. - Meaning review of the first commit: of 691 changed blocks, 140 were cosmetic. The other 551 were checked against source, and 545 preserved their meaning. The second commit restores the six that didn't: three `request_resources` mentions on `autoscaler-v2.md` that had made the caller "you" (Ray Data also calls it), the users-set-it framing of an environment variable on `ray-event-exporter.md`, "currently spillable" on `object-spilling.md`, and the attribution of a NIXL limitation on `direct-transport/index.md`. It also restores a few smaller shifts that the review noted. - A later commit restores one more shift, on `internals/port-service-discovery.md`. The pass had turned "Raylet (C++) spawns Core Workers (C++)" into "both are C++ processes", which is wrong for Python and Java worker processes. The restored sentence says both are written in C++. - Full `-W` doc build: relying on the Read the Docs preview. AI assistance (Claude Code) was used to draft these edits. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
61c6850 to
dea9f54
Compare
Only SandboxRuntime and the gRPC facade could change a running sandbox's allowlist. The Sandbox actor that sandbox.create() returns now has set_egress_allowlist too. Signed-off-by: xyuzh <[email protected]>
… KubeRay at the full Dockerfile Describe how the guard picks up new Ray nodes, the dns check at create, and set_egress_allowlist on the actor. The KubeRay example's Dockerfile installed runsc, slirp4netns and nftables but not erofs-utils, which every sandbox needs, so the example now uses the Dockerfiles in the Ray Sandboxes requirements instead of a copy. Signed-off-by: xyuzh <[email protected]>
…s ruleset ray-project#67022 made every create that fails before its sandbox starts delete its bundle and close its owner file. The egress ruleset's failure path, which ray-project#67022 didn't know about, only released the image, so the bundle stayed on the node, locked by the worker, until the worker exited. Signed-off-by: xyuzh <[email protected]>
f5c39fb to
30dbdb0
Compare
| | `host` | Full host network identity | Host's own file, mounted read-only (`dns=` overrides it) | Strictly more permissive than `public`. The sandbox can reach anything the node can reach, including internal networks and node-local services. | | ||
| | `sandbox` | gVisor netstack | untouched | Requires `rootless=False`. runsc doesn't support the sandbox netstack in rootless mode. | | ||
| | `none` *(default)* | Nothing | Untouched | Untrusted code that doesn't need the network. This is the recommended setting. | | ||
| | `public` | The public internet, or the destinations in its allowlist. Never the cluster's control plane. | Generated from `dns`, which defaults to `8.8.8.8` and `1.1.1.1`, and mounted read-only | Code that needs the internet. See [What can a public sandbox reach?](#what-can-a-public-sandbox-reach) | |
There was a problem hiding this comment.
Instead of Never the cluster's control plane, we should say something along the lines that some internal IP addresses are excluded via a denylist but we highly recommend to enforce an allowlist so agent's don't access things they shouldn't.
There was a problem hiding this comment.
Done in dddd170: the table now says the public internet with internal addresses left out as a best effort, and recommends an allowlist for untrusted code. The warning and the "What can a public sandbox reach?" section use the same wording, and "control plane" is gone from the docs and docstrings.
|
|
||
| :::{warning} | ||
| `public` isolates sandboxes from each other and from the node's own services, not from the network the node sits on. slirp4netns relays every outbound connection through the node, so a `public` sandbox can reach other Ray nodes, including the head node's GCS and dashboard ports, other Kubernetes Pods, and any internal service the node can reach. Use `network="none"` for untrusted code. | ||
| By default, a `public` sandbox can't reach your cluster's private networks, and it never reaches the cluster's control plane. It can reach the whole internet, so code inside it can send data anywhere. For untrusted code that doesn't need the network, use `network="none"`. Otherwise, limit the sandbox to the destinations it needs. See [Restrict egress to an allowlist](#restrict-egress-to-an-allowlist). |
There was a problem hiding this comment.
about "never reaches the cluster's control plane", I have the same comment as above.
There was a problem hiding this comment.
Done in dddd170: the warning now says Ray leaves out internal addresses as a best effort, not a guarantee for every service the cluster runs, and that untrusted code that needs the network should get an allowlist naming only the services it needs.
| Ray filters all traffic that leaves the sandbox. Before the sandbox starts, Ray installs an nftables ruleset in the sandbox's namespace that drops all outbound traffic except the following: | ||
|
|
||
| * DNS over UDP and TCP port 53 to the resolvers in `dns`. | ||
| * The destinations in the sandbox's allowlist. Unless you pass `cidr_allowlist`, the allowlist is `["internet"]`, every public address, which leaves out the private and special-purpose networks that hold your cluster's nodes and services. |
There was a problem hiding this comment.
Maybe we add a note here that his is our best effort to leave out private addresses, but for untrusted sandboxes that need network access, it is recommended to come up with a custom allowlist that only targets specific services that need to be accessed.
There was a problem hiding this comment.
Added in dddd170 as an important note right after the defaults: leaving out internal addresses is a best effort, and untrusted sandboxes that need network access should get an allowlist that names only the services they need.
| return _ray_addresses_cache[1] | ||
| hosts = { | ||
| node["NodeManagerAddress"] | ||
| for node in ray.nodes() |
There was a problem hiding this comment.
This is problematic since the nodes will change when the cluster autoscales and there will likely be a window where the addresses are open if new nodes get added. I wonder if we can just replace it with the "all internal IP addresses" filter and call out in the docs that people should make sure their Ray IP addresses are covered by those if they rely on this mechanism?
There was a problem hiding this comment.
Agreed, done in dddd170: the node list, its refresh thread, and the address:port exception are gone, so Ray nodes are covered only by the internal-address filter that internet applies. The docs tell anyone relying on it to keep their nodes on internal addresses or list the nodes' network in RAY_SANDBOX_EGRESS_DENY, which also covers nodes the autoscaler adds. Creating a public sandbox no longer calls GCS either.
…eny two more metadata endpoints The denylist held the Ray nodes that ray.nodes() listed when a ruleset was written, so on a cluster that autoscales, a node added later stayed reachable until the next refresh. Drop the node list, its refresh thread, and the address:port exception that only it needed. The default allowlist, internet, already leaves out internal addresses, where clusters run their nodes. The docs now call that a best effort: if you rely on it, keep your Ray nodes on internal addresses or list their network in RAY_SANDBOX_EGRESS_DENY, which also covers nodes added later, and give untrusted sandboxes an allowlist that names only the services they need. Creating a public sandbox no longer calls GCS. The static denylist missed two metadata endpoints outside link-local: Alibaba Cloud's 100.100.100.200, and Azure's platform endpoint 168.63.129.16, a public address that internet opened. Both are now always denied. DNS to 168.63.129.16 still works when it's a dns resolver. Signed-off-by: xyuzh <[email protected]>
|
Went through |
|
Thanks a lot of the updates, I'll have another pass and then hopefully we can get it merged :) |
|
Kicking off CI again since it was stuck previously |
…ay-project#65633) ## Why are these changes needed? Ray Sandbox (`ray.experimental.sandbox`) can currently only be driven from inside the cluster as Ray actors. This PR adds an **experimental HTTP API service** so sandboxes can be managed from outside the cluster with nothing but an HTTP client and a bearer token — for example as an Anyscale service, or from agent-evaluation frameworks (a Harbor `ray-sandbox` environment built on this API is submitted alongside: harbor-framework/harbor PR to follow). This is the second step of the plan from ray-project#65570 (first: make the Python API run Docker-built images out of the box; second: make Ray Sandbox consumable as a standalone service). ## Design ``` client ──HTTP/bearer──▶ FastAPI on Ray Serve (ray.experimental.sandbox.http, stateless replicas) │ ray.get_actor(name, namespace) ▼ SandboxHost — named, detached actor per sandbox │ composes SandboxRuntime ▼ gVisor (runsc) on the node ``` - **Named detached actors are the registry.** Any replica resolves any sandbox by name; list = `ray.util.list_named_actors`. The service keeps no state, so replicas scale/restart freely. - **Async submit + poll.** Image pulls and commands outlive HTTP requests and LB limits, so `POST /sandboxes` and `POST .../execs` return `202` immediately; clients poll, optionally long-polling with `wait_seconds` (≤ 30 s per request). Boot progress is observable: `pending → pulling → starting → running | error`. - **One TTL owner.** The API's TTL reclaims the sandbox **and** its hosting actor (the core runtime TTL is deliberately disabled here); an abandoned sandbox never strands an actor reservation. - **Everything sandbox-behavioral is the core `SandboxConfig`'s** (ray-project#65570): capabilities (default `DOCKER_DEFAULT_CAPABILITIES`, sets written exactly), network modes (validated against `VALID_NETWORK_MODES`, so a new mode needs no API change), `dns`, `shell` (sandbox-level and per-exec override), and the workdir/readonly writability contract. The API patches nothing. - **Auth**: `Authorization: Bearer <token>` enforced when `RAY_SANDBOX_API_TOKEN` is set; an Anyscale service can leave it unset because the platform edge already requires the service bearer token. `GET /health` is always open. - **Isolation from core**: importing `ray.experimental.sandbox.http` requires `ray[serve]`; the base sandbox package never imports it. Endpoints (`/api/v1`): create/list/get/delete sandboxes, start/poll execs, PUT/GET files, JSON error envelope (`401/404/409/400/413/422/503/500`). Full table in the new docs section. ## E2E validation Deployed as an Anyscale service (runsc-equipped cluster image) and as a local `serve run`; drove real gVisor sandboxes through create → exec → file transfer → delete, including a full Harbor evaluation run (oracle agent, reward 1.0) against the service URL + token. ## Update (2026-09-24) Rebased onto master and addressed the latest review: - **A DELETE or TTL during boot no longer orphans a container** (from the approval review). A terminate that arrives during the image pull stops the boot before anything starts. One that arrives while `runtime.create` runs waits for it and deletes the new instance before the host exits, and the boot no longer flips a terminated host back to `running`. Tests cover a terminate during start and during pull, a TTL during start, and a boot after terminate; the start-race tests fail on the previous `host.py`. - **Typing:** `spec` and `settings` are `SandboxSpec` / `HostSettings` TypedDicts, and the runtime is typed as `SandboxRuntime`. - **Named-actor cost, measured** (see the scalability thread). The resolver built a fresh `ray.remote(SandboxHost)` for every sandbox, which re-exported the class on each create: 9.15 ms per create on the event loop (Ray 2.58, local), versus 0.76 ms with one cached ActorClass. Resolver calls (create, lookups, kill, list) now run in worker threads, so a GCS round trip never stalls the replica's event loop. Handles of sandboxes created under fresh random ids are cached; deterministic names (client tokens) keep resolving through `ray.get_actor`, whose cache follows actor deaths and re-creations. - **Ids:** random and token-derived ids are `sb-` plus 22 hex chars (88 bits, the facade's shape) instead of 12, and a fresh create skips `get_if_exists`, so a random-id collision fails loudly instead of attaching a second client to someone else's sandbox. - **Errors:** a file write the sandbox can't perform (a directory, a read-only rootfs outside the workdir) returns `409 write_failed` instead of `500`, and one sandbox that fails to describe no longer fails the whole listing. The docs list `write_failed` and the existing `503 sandbox_unavailable`. - **Second pass** (Bugbot on the update): exec, file, and network calls are refused once `terminate()` has started, not only after the status flips. A `client_token` retry re-sends the idempotent `boot()`, so a first boot that never reached the actor can't leave a sandbox pending without its TTL. The `ResourceSpec` docs no longer claim a CPU quota is derived from the request: only `cpu_limit` caps. The resolver and actor-error helpers moved to `http/resolver.py`, and the package resolves its REST exports lazily, so importing it doesn't require FastAPI. ## Related issue number Follow-up to ray-project#65570. ray-project#65992 and ray-project#65942 have merged, so this PR is now a single commit on master. Merge order for the rest of the stack: ray-project#65633 → ray-project#65839 → ray-project#66359. ## Checks - [x] I've signed off every commit (DCO). - [x] I've run pre-commit hooks (`ruff`, `pydoclint`, docstyle, semgrep, import order) on the changed files. - [x] Unit tests run with **no cluster and no runsc** (fake runtime + fake resolver + FastAPI `TestClient`), including an OpenAPI **contract snapshot** that pins the v1 surface: `pytest --import-mode=importlib python/ray/experimental/sandbox/http/tests/{test_http_app,test_sandbox_host,test_http_schemas}.py` → 77 passed. `test_http_integration.py` is gated on the sandbox test env + `runsc` like the existing sandbox tests; in a privileged container with runsc release-20260817 and erofs-utils 1.9.4 (`TEST_SANDBOX=1 RAY_SANDBOX_IGNORE_CGROUPS=1`), it and `sandbox/tests/test_gvisor_backend.py` pass at the top of the stack (40 passed, 1 skipped). `BUILD.bazel` uses the same `sandbox_tests`/`team:core` tags so the existing CI job picks the package up. - [x] Release tests: N/A (experimental, off by default; nothing imports this package unless deployed). - This PR was prepared with AI assistance. It is not a duplicate: it is one step of the Ray Sandbox series (ray-project#65570 → ray-project#65992 → ray-project#65942 → ray-project#65633 → ray-project#65839 → ray-project#66359), and no other open PR covers it. Signed-off-by: xyuzh <[email protected]>
…roject#65839) ## Why are these changes needed? ray-project#65992, ray-project#65942, and ray-project#65633 have merged, and this PR is rebased onto master, so the diff is the facade commit alone. ray-project#66359 stacks on it. ray-project#65633 (merged) exposes the sandbox control plane as a REST service. This PR adds a gRPC facade in front of the same detached `SandboxHost` actors, so an unmodified third-party sandbox client SDK pointed at this server can create sandboxes, exec commands, and use its filesystem API against a Ray cluster. The facade implements the subset of the SDK's control-plane (`ModalClient`) and command-router (`TaskCommandRouter`) services that its Sandbox API uses. The wire contract is vendored under `http/_proto/` as a minimal protobuf/grpclib stub set generated from checked-in `.proto` sources, so nothing third-party is needed to build or test. gRPC routes on the fully qualified method path and protobuf frames fields by number, so the vendored service, method, and field identifiers reproduce the external service's on-the-wire names verbatim; only the surface the facade uses is declared. The proto packages carry a `ray_sandbox_facade.` prefix that never reaches the wire, so the stubs can share a process with the client SDK. Design: - **Stateless where possible.** Object ids carry their payload (`im-<b64 image ref>`, `st-<b64 env json>`) and the sandbox id doubles as the client task id. Named creates are scoped to the client app and idempotent; a dead actor under a live name is killed and recreated. The one in-process table is the exec table, which keeps finished records for 120 s (the SDK reads output lazily) under a 50,000-record cap, so run a single facade process per cluster. - **Filesystem API via exec emulation.** The SDK implements its filesystem API by exec-ing a helper binary that sandbox images don't contain. The router recognizes its argv and emulates WriteFile / ReadFile / ListFiles with `SandboxHost` file operations; large writes flush in bounded slices. - **Scheduling-aware.** Every actor call is bounded, so an unscheduled actor on a scaling cluster surfaces as `UNAVAILABLE` (retried by the SDK) instead of hanging, and a dead actor maps to `NOT_FOUND` (the SDK's "task shut down" signal). Run with `python -m ray.experimental.sandbox.http.grpc_facade` (requires `grpclib`). Documented in the sandboxes guide under the HTTP API service section. One commit: the vendored wire contract (`.proto` sources, generated stubs, lint excludes), the facade, its tests, and docs. Review fixes that touch code shared with the lower PRs (`name:group` exec-user resolution, a bounded runsc download, a bounded `DELETE`, docs wording) live on those branches and are included here through the stack. Review fixes from the 2026-09-15 pass: - A `cidr_allowlist` the facade cannot enforce now fails `SandboxCreate` with `INVALID_ARGUMENT` instead of granting open egress behind a server-side warning, and `TaskSetNetworkAccess` fails with `UNIMPLEMENTED` instead of being acknowledged and ignored, so a client never runs with fewer restrictions than it asked for. - `TaskExecStart` reserves the exec id before anything reaches the actor and carries the start in its own task. A retry (the SDK retries `UNAVAILABLE`, which the facade answers when the actor has not replied within the scheduling grace) joins that in-flight start instead of running the command again; a start that fails for good is forgotten so a retry may start afresh. A test holds the first start in flight past the grace, retries, and checks the command ran once. - The exec record kind is `sandbox` or `fs` (was `host`), since both run in the sandbox. Update (2026-09-24), rebased onto the new ray-project#65633: - **Tests with the Modal client** (review request): `test_modal_client.py` runs the unmodified `modal` SDK (1.5.5) against the facade: create, exec with exit codes and stdout/stderr, `filesystem.write_bytes` / `read_bytes` including the typed not-found error, terminate, and the network-policy mappings. - **The facade and the Modal SDK can share a process.** The vendored protos declared `package modal.client`, which registered the same full names as the SDK's own protos in protobuf's process-wide descriptor pool, so importing both failed with `duplicate symbol 'modal.client.ObjectCreationType'` (hit while load-testing on Anyscale). The packages now carry a `ray_sandbox_facade.` prefix, and the generated gRPC stubs are rewritten to the external method paths, so the wire is unchanged: the regenerated `_grpc.py` files are byte-identical, every served path exists in the SDK's stubs, and the SDK's serialized messages parse into the vendored classes. `_proto/README.md` documents the regeneration step. - **`SandboxTerminate` no longer kills a host whose `terminate()` outlasts the wait** (Bugbot). As in the REST `DELETE`, the queued terminate finishes (with ray-project#65633's boot fix it first deletes a container that was still starting) and the host exits on its own. - **Exec records outlive fast traffic.** The SDK reads a command's stdout and stderr lazily, often after `wait()` returned. With the 1,000-record cap, a finished record lasted about a second at 700 execs/s and a late read got `NOT_FOUND`. Finished records now stay 120 s (hard cap 50,000), evicted by a bounded O(1) scan instead of a full-table copy per exec. - **Event loop:** resolver calls (create, lookups, kill) run in worker threads, and creates reuse one ActorClass (ray-project#65633). With real `SandboxHost` actors on a local Ray cluster and the Modal SDK issuing 48 concurrent creates, throughput went from 56 to 353–550 creates/s, the create RPC's p50 from 387 ms to 78–104 ms, and the facade's worst event-loop stall during the burst from 838 ms to 36 ms. Exec throughput is unchanged (about 1.3k/s on that machine). - **Malformed input is `INVALID_ARGUMENT`, not `INTERNAL`:** a bare `FROM` line, and fs-tools commands whose JSON isn't an object with an object payload (gemini, on ray-project#66359). - The image-seeding symlink finding (Bugbot) was fixed in ray-project#65992 before it merged (`_resolve_in_root`); `image_utils.py` is no longer part of this diff. - **Second pass** (Bugbot on the update): importing the facade no longer needs FastAPI (it takes the resolver from ray-project#65633's `http/resolver.py`), so it needs only `grpclib` and `ray[default]`, as the docs now say. Buffered `WriteFile` content is capped at `max_file_bytes` (`RESOURCE_EXHAUSTED` past it), and named-create retries re-send the idempotent `boot()`. ## Related issue number Follows ray-project#65633 (merged). ## Checks - `test_grpc_facade.py` drives the facade end to end over gRPC with the vendored stubs, and `test_modal_client.py` with the unmodified Modal SDK, both backed by the same fake resolver and runtime seams the REST app tests use. They skip when `grpclib` (and, for the latter, `modal`) is absent, so the sandbox core CI job, which installs neither, adds no new dependency. Ran locally with grpclib 0.4.9 and modal 1.5.5: `pytest --import-mode=importlib python/ray/experimental/sandbox/http/tests/` → 101 passed (21 wire tests, 3 Modal-client tests, and the 77-test HTTP API suite). - The facade module is never imported from `sandbox/__init__.py` or the REST `app.py` import graph, so it stays inert unless explicitly run. - `ruff check`, `ruff check --select I`, `black`, and `pydoclint` (the pre-commit versions and flags) pass on the changed files. - This PR was prepared with AI assistance. It is not a duplicate: it is one step of the Ray Sandbox series (ray-project#65570 → ray-project#65992 → ray-project#65942 → ray-project#65633 → ray-project#65839 → ray-project#66359), and no other open PR covers it (ray-project#66089, a KubeRay + Modal SDK guide, builds on it). Signed-off-by: xyuzh <[email protected]>
…#66675) ## Description The Ray Sandbox gRPC facade (`ray.experimental.sandbox.http.grpc_facade`) served sandbox create, exec, and file read/write to any client that could reach its port. Unlike the REST app, it never read `RAY_SANDBOX_API_TOKEN`, so even an operator who wanted to lock it down couldn't, and the documented quickstart binds `--host 0.0.0.0`. With this PR: - **The token is required on every RPC.** When `RAY_SANDBOX_API_TOKEN` is set, a call that doesn't present it fails with `UNAUTHENTICATED` before its handler reads the request. - A client presents the token the way the client SDK already sends credentials: as its token secret (`x-modal-token-secret`, from `MODAL_TOKEN_SECRET`), or as `authorization: Bearer <token>`, the REST app's form, which `MODAL_OVERRIDE_HEADERS` can also send. - `TaskGetCommandRouterAccess` hands out the token as the command router's credential. The SDK then sends it as a bearer token on every exec and file call, so an unmodified client only needs `MODAL_TOKEN_SECRET` set. - A bearer-only check wouldn't work with the SDK: its control-plane calls carry the token secret, and its router calls carry only the credential that `TaskGetCommandRouterAccess` returned. - **The check is bound to the servicers, not to one server.** `_TokenGate` wraps the handler table (`__mapping__`) that `grpclib.server.Server` dispatches through. So every server built from `build_servicers` is gated, including RPCs added later, such as ray-project#66359's `TaskSetNetworkAccess`. Without a token the table is returned unchanged. - **The CLI fails closed.** Without a token, `python -m ray.experimental.sandbox.http.grpc_facade` refuses a non-loopback `--host` unless `--allow-unauthenticated` is passed. - Keeping the facade on a private network isn't enough on its own. The facade's sandboxes get open egress by default and can reach any address their node can, including the facade's. So a tokenless facade on a network address would also serve the code running inside them. - Loopback binds stay tokenless, since `--disable-host-loopback` keeps sandboxes off the node's loopback. - **Docs.** The gRPC section now covers: - the token; - the trust model: one token controls every sandbox in the namespace, as with the REST token, with no per-client isolation; - the TLS requirement; - a fix for the stale network bullet: allowlists are refused, not widened. - **REST.** `require_bearer_token` compares bytes, so a non-ASCII `Authorization` header gets a 401 instead of a `TypeError` and a 500. **Behavior change:** a tokenless facade started with a non-loopback `--host`, as the old quickstart did, now exits with an error that names `RAY_SANDBOX_API_TOKEN` and `--allow-unauthenticated`. **This PR also fixes the failing `:ray: core: sandbox tests` job** (for example premerge build 74278 and microcheck build 55110). - `test_image_utils.py::test_seeding_stays_inside_the_tree` linked the fake image's `/tmp` to an absolute path under pytest's `tmp_path`, which is itself under `/tmp` in CI. - From the image's point of view that's a symlink loop. `_resolve_in_root` correctly reports it as `ELOOP`, so nothing was seeded. - The test now gives `tmp` its own tree with a relative link. The product code is unchanged. - The test only passed on macOS because `tmp_path` lives under `/private/var/folders` there. ## Related issues Related to ray-project#65839 (the facade) and ray-project#65352 (sandboxing umbrella). Not a duplicate: no open PR or issue covers facade authentication. I searched open PRs and issues for `grpc_facade`, `RAY_SANDBOX_API_TOKEN`, and sandbox authentication. ## Additional information **Tests run.** Environment: macOS, Python 3.12, the ray 2.58 wheel with this branch's sandbox package overlaid, grpclib 0.4.9. | Command | Result | | --- | --- | | `pytest --import-mode=importlib python/ray/experimental/sandbox/http/tests` | 130 passed, 8 skipped (modal not installed, `TEST_SANDBOX` unset) | | The same, with `RAY_SANDBOX_API_TOKEN=ambient` exported | 130 passed, 8 skipped | | `uv run --with modal==1.5.5 pytest .../http/tests/test_modal_client.py` | 6 passed | | `uv run --with modal==1.5.1 pytest .../http/tests/test_modal_client.py` | 5 passed, 1 skipped (1.5.1 can't send custom headers) | | The new auth tests against `origin/master`'s `grpc_facade.py` | 29 failed, as expected | | `test_image_utils.py::test_seeding_stays_inside_the_tree`, with the default `tmp_path` and with `tmp_path` under `/tmp` | Passed both ways (the old test fails with `tmp_path` under `/tmp`) | | `python -m ray.experimental.sandbox.http.grpc_facade --host 0.0.0.0` without a token | Exit 2, before connecting to the cluster | | Unauthenticated create path replayed against a local Ray cluster | Anonymous and wrong-token `AppGetOrCreate`, `ImageGetOrCreate`, and `SandboxCreate` return `UNAUTHENTICATED` and create no actor. With the token, a `SandboxHost` actor is created and then terminated. | | `pre-commit` (ruff, pydoclint, docstyle, import order), black 22.10.0, API param coverage check | Pass | `test_grpc_facade.py` and `test_modal_client.py` skip in CI because grpclib and modal aren't in the CI image, so the auth tests above ran locally only. AI assistance was used to write this change. Signed-off-by: xyuzh <[email protected]> Co-authored-by: Philipp Moritz <[email protected]>
…disk caps, egress allowlist Moves the pin to Ray master @ 78e4b1f713, which has every merged sandbox fix and ray-project/ray#67444, so vLLM's Ray metrics no longer need ray[serve] in SkyRL's env. Validated there with 64 SWE-bench Verified tasks (Harbor's oracle and SkyRL's generator). - Pin Ray to master @ 78e4b1f713 in pyproject.toml, uv.lock and the image. - dockerfile-parse in the harbor extra: the environment reads the task Dockerfile's WORKDIR with Harbor's parse_dockerfile_workdir, which imports it, and harbor[daytona,modal] doesn't install it, so every task with a Dockerfile failed in the environment's constructor. - The image installs nftables and util-linux: Ray sets up network="public" sandboxes with nft, nsenter and setpriv since ray-project/ray#66359. gVisor goes to release-20261019.0. - The task's storage_mb caps the writable rootfs (ray-project/ray#66988). - New cidr_allowlist kwarg, passed to Ray, for public sandboxes that must reach a host inside the cluster. The comment on "public" said it could reach the Ray GCS; since ray-project/ray#66359 it reaches the internet only. - black reformats lines the file already had to the repo's 120 columns. Signed-off-by: xyuzh <[email protected]>
…t and enforce allowlists (ray-project#66359) ## Description A `network="public"` sandbox could reach everything its pod reaches. From a sandbox in a CoreWeave pod running a Ray head, GCS, the Ray client server, the raylet, the object manager, the dashboard agent, the Kubernetes API, the kubelet, and 169.254.169.254 all accepted connections. Ray's ports take no token unless the cluster runs with `RAY_AUTH_MODE=token`, and slirp4netns relays sandbox flows through the pod's own sockets, so a pod NetworkPolicy can't single them out. This PR filters every `public` sandbox's egress with an nftables ruleset in its private network namespace, loaded after slirp4netns brings the tap up and before runsc starts. A failed load fails the create. - `cidr_allowlist` defaults to `["internet"]`, public addresses only. Entries are addresses or networks with optional ports (`10.0.0.5:8000`, `internet:443`). - A denylist runs before any list: link-local (instance metadata), loopback, Alibaba Cloud's and Azure's metadata endpoints, the Kubernetes API Service, and `RAY_SANDBOX_EGRESS_DENY`. Ray doesn't track its nodes, as pcmoritz suggested: `internet` leaves them out while their addresses are internal, which the docs call a best effort, and an operator who allows internal networks lists the nodes' network in `RAY_SANDBOX_EGRESS_DENY`, which also covers nodes the autoscaler adds. - `set_egress_allowlist`, on `SandboxRuntime` and on the actor that `sandbox.create()` returns, replaces any public sandbox's ruleset in one `nft -f`, entering its namespaces through fds checked against the ones recorded at creation. - With `dns` set, the create sends each resolver one UDP byte from inside the sandbox and fails, naming the resolver, if the send fails. On Cilium, which translates the cluster DNS Service IP before the filter sees it, every lookup failed instead. - The gRPC facade maps `block_network`, `outbound_cidr_allowlist`, and `TaskSetNetworkAccess`; open access means `internet`. - The REST API answers 403 to `network="host"`, `"sandbox"`, or `rootless=false` unless `allowed_network_modes` / `allow_rootful` allow them, and `build_app` requires `RAY_SANDBOX_API_TOKEN` unless `allow_unauthenticated` is set. Behavior changes: `public` needs `nft` on the node, no longer reaches private networks without a list, and fails to create when a `dns` resolver is unreachable. REST deployments need a token. ### Why nftables inside the sandbox netns is the right enforcement point Inside the sandbox's private user + net namespace, the host-side launch script has CAP_NET_ADMIN over that child network namespace (without needing CAP_NET_ADMIN on the Kubernetes worker pod itself). runsc runs inside that child netns with --network=host. That means gVisor's hostinet creates real Linux kernel AF_INET/AF_INET6 sockets inside the child netns, so every packet from the sandbox passes through the Linux kernel's nf_tables output chain before reaching slirp4netns's tap0. **Why sandbox code cannot tamper with the rules (even with CAP_NET_ADMIN):** gVisor's Sentry intercepts all syscalls inside the sandbox. Even if the container process has CAP_NET_ADMIN or CAP_NET_RAW, gVisor's hostinet (without --net-raw) never forwards AF_NETLINK (NETLINK_NETFILTER / NETLINK_ROUTE) or AF_PACKET sockets to the host kernel. Running nft flush ruleset or iptables -F inside the sandbox talks only to gVisor's internal Sentry stub, never touching the host kernel netns where the rules live. ### Results TCP connects from a sandbox in a CoreWeave (Cilium) pod running a Ray head, 5 s timeout, measured on dddd170: | Destination | Default | `ALLOW_ALL_CIDRS` | + `RAY_SANDBOX_EGRESS_DENY=<node>,<API server>` | | --- | --- | --- | --- | | GCS, Ray client server, raylet, object manager, dashboard | timeout | open | timeout | | 169.254.169.254:80 | timeout | timeout | timeout | | Kubernetes API (Service and endpoint) | timeout | open | timeout | | 1.1.1.1:443, DNS | open | open | open | Allow-all reaches the Ray head's ports because Ray doesn't track its nodes, and it reaches the API Service because Cilium rewrites it to the API server's address at connect time; `RAY_SANDBOX_EGRESS_DENY` closes both, and the docs say so. Root in a sandbox with `CAP_NET_ADMIN` and `CAP_NET_RAW` ran `nft flush ruleset` and `iptables -F`: both failed with "Protocol not supported", and GCS stayed closed. How to review: `config.py`, `_internal/egress_guard.py`, `backend/gvisor.py` (`_render_egress_ruleset`, the run command, `set_egress_allowlist`, `_unreachable_resolver`), `http/host.py` and `http/grpc_facade.py`, `http/schemas.py` and `http/app.py`, then the docs. Skip the `_pb2.py` files. ## Related issues Follows ray-project#65839. Found through SkyRL's SWE-bench Multimodal runs on Ray Sandbox (skyrl-project/SkyRL#2467). ray-project#66782 and ray-project#67010 inherit the default. ray-project#66471's restore path needs the same nft install. ## Additional information - Not a duplicate: none of the 20 open sandbox PRs adds egress filtering or a default deny. - Tests on a CoreWeave pod (Cilium, runsc release-20261012.0, root), rebased on master 7073066: `TEST_SANDBOX=1 pytest tests/test_gvisor_backend.py tests/test_image_manager.py tests/test_image_utils.py tests/test_sandbox_config.py tests/test_sandbox_runtime.py tests/test_egress_guard.py -k "not netns and not test_create_sandbox_helper"`: 167 passed, 1 skipped. `-k netns`: 22 passed. `test_create_sandbox_helper`: 1 passed. `tests/test_sandbox.py`: 7 passed. `http/tests`: 167 passed, 10 skipped. With the Modal SDK 1.5.5 installed on macOS, which CI doesn't have, `http/tests`: 175 passed, 2 skipped (the gVisor integration tests). On the pod, `dns=["10.16.0.10"]`, the cluster DNS Service, now fails the create with "Operation not permitted" and still resolves with `ALLOW_ALL_CIDRS`; the check adds about 14 ms to a create. pre-commit passes. This round wasn't rerun as uid 1000. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Co-authored-by: Philipp Moritz <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
Description
A
network="public"sandbox could reach everything its pod reaches. From a sandbox in a CoreWeave pod running a Ray head, GCS, the Ray client server, the raylet, the object manager, the dashboard agent, the Kubernetes API, the kubelet, and 169.254.169.254 all accepted connections. Ray's ports take no token unless the cluster runs withRAY_AUTH_MODE=token, and slirp4netns relays sandbox flows through the pod's own sockets, so a pod NetworkPolicy can't single them out.This PR filters every
publicsandbox's egress with an nftables ruleset in its private network namespace, loaded after slirp4netns brings the tap up and before runsc starts. A failed load fails the create.cidr_allowlistdefaults to["internet"], public addresses only. Entries are addresses or networks with optional ports (10.0.0.5:8000,internet:443).RAY_SANDBOX_EGRESS_DENY. Ray doesn't track its nodes, as pcmoritz suggested:internetleaves them out while their addresses are internal, which the docs call a best effort, and an operator who allows internal networks lists the nodes' network inRAY_SANDBOX_EGRESS_DENY, which also covers nodes the autoscaler adds.set_egress_allowlist, onSandboxRuntimeand on the actor thatsandbox.create()returns, replaces any public sandbox's ruleset in onenft -f, entering its namespaces through fds checked against the ones recorded at creation.dnsset, the create sends each resolver one UDP byte from inside the sandbox and fails, naming the resolver, if the send fails. On Cilium, which translates the cluster DNS Service IP before the filter sees it, every lookup failed instead.block_network,outbound_cidr_allowlist, andTaskSetNetworkAccess; open access meansinternet.network="host","sandbox", orrootless=falseunlessallowed_network_modes/allow_rootfulallow them, andbuild_apprequiresRAY_SANDBOX_API_TOKENunlessallow_unauthenticatedis set.Behavior changes:
publicneedsnfton the node, no longer reaches private networks without a list, and fails to create when adnsresolver is unreachable. REST deployments need a token.Why nftables inside the sandbox netns is the right enforcement point
Inside the sandbox's private user + net namespace, the host-side launch script has CAP_NET_ADMIN over that child network namespace (without needing CAP_NET_ADMIN on the Kubernetes worker pod itself).
runsc runs inside that child netns with --network=host. That means gVisor's hostinet creates real Linux kernel AF_INET/AF_INET6 sockets inside the child netns, so every packet from the sandbox passes through the Linux kernel's nf_tables output chain before reaching slirp4netns's tap0.
Why sandbox code cannot tamper with the rules (even with CAP_NET_ADMIN): gVisor's Sentry intercepts all syscalls inside the sandbox. Even if the container process has CAP_NET_ADMIN or CAP_NET_RAW, gVisor's hostinet (without --net-raw) never forwards AF_NETLINK (NETLINK_NETFILTER / NETLINK_ROUTE) or AF_PACKET sockets to the host kernel. Running nft flush ruleset or iptables -F inside the sandbox talks only to gVisor's internal Sentry stub, never touching the host kernel netns where the rules live.
Results
TCP connects from a sandbox in a CoreWeave (Cilium) pod running a Ray head, 5 s timeout, measured on dddd170:
ALLOW_ALL_CIDRSRAY_SANDBOX_EGRESS_DENY=<node>,<API server>Allow-all reaches the Ray head's ports because Ray doesn't track its nodes, and it reaches the API Service because Cilium rewrites it to the API server's address at connect time;
RAY_SANDBOX_EGRESS_DENYcloses both, and the docs say so. Root in a sandbox withCAP_NET_ADMINandCAP_NET_RAWrannft flush rulesetandiptables -F: both failed with "Protocol not supported", and GCS stayed closed.How to review:
config.py,_internal/egress_guard.py,backend/gvisor.py(_render_egress_ruleset, the run command,set_egress_allowlist,_unreachable_resolver),http/host.pyandhttp/grpc_facade.py,http/schemas.pyandhttp/app.py, then the docs. Skip the_pb2.pyfiles.Related issues
Follows #65839. Found through SkyRL's SWE-bench Multimodal runs on Ray Sandbox (skyrl-project/SkyRL#2467). #66782 and #67010 inherit the default. #66471's restore path needs the same nft install.
Additional information
TEST_SANDBOX=1 pytest tests/test_gvisor_backend.py tests/test_image_manager.py tests/test_image_utils.py tests/test_sandbox_config.py tests/test_sandbox_runtime.py tests/test_egress_guard.py -k "not netns and not test_create_sandbox_helper": 167 passed, 1 skipped.-k netns: 22 passed.test_create_sandbox_helper: 1 passed.tests/test_sandbox.py: 7 passed.http/tests: 167 passed, 10 skipped. With the Modal SDK 1.5.5 installed on macOS, which CI doesn't have,http/tests: 175 passed, 2 skipped (the gVisor integration tests). On the pod,dns=["10.16.0.10"], the cluster DNS Service, now fails the create with "Operation not permitted" and still resolves withALLOW_ALL_CIDRS; the check adds about 14 ms to a create. pre-commit passes. This round wasn't rerun as uid 1000.