Repository navigation
[core][sandbox] Support per-exec user and appending writes in the gVisor backend - #65942
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces support for executing commands as a specific user inside the gVisor sandbox by resolving usernames and group names against the image's /etc/passwd and /etc/group files. It also adds an append option to the write_file API to allow appending content to files instead of truncating them. The review feedback suggests several robustness and performance improvements: caching the database lookups using @lru_cache to avoid repeated disk I/O, safely handling potential IndexError exceptions when parsing malformed /etc/passwd entries, and using -- in shell commands to prevent option injection for paths starting with a hyphen.
…ns via pasta (#65820) ## Description `network="public"` sandboxes currently run with runsc `--network=host` in the Ray worker's own network namespace: every sandbox on a node shares one port space, so concurrent workloads that bind a fixed port collide and can reach each other's listeners. The concrete failure is terminal-bench's QEMU tasks (`qemu-startup`, `qemu-alpine-ssh`), which start QEMU with `hostfwd=tcp::2222-:22` and then SSH to `localhost:2222` from inside the same sandbox. Under co-tenancy the second bind gets `EADDRINUSE`, and a verifier can connect to a *different* sandbox's guest. This PR gives each `public` sandbox a private user+network namespace pair bridged by pasta (passt) user-mode networking, the rootless-Podman topology: - a tiny holder process (`unshare --user --map-root-user --net`) pins the namespaces for the sandbox's lifetime; - `pasta` attaches from the pod side (`--netns/--userns /proc/$PID/ns/*`) and runs in the **foreground** inside the sandbox's process group, so teardown's `killpg` takes it with the rest of the tree. `-t/-u/-T/-U none --no-map-gw` make it egress-only: in-sandbox binds are never republished on the pod, pod-local services are unreachable from the sandbox loopback, and there is no inbound path; - `runsc run` executes inside via `nsenter` as mapped root. `--rootless` is dropped because nesting a second userns breaks the gofer's `/proc` magic-link derefs; since rootless mode is also what tolerated cgroup permission failures, the wrapper forces `--ignore-cgroups` for rootless configs. runsc still gets `--network=host`, but "host" is now private to the sandbox. Mount and pid namespaces stay shared, so the bundle and control sockets under `--root` keep working for pod-side `state`/`exec`/`kill`/`delete`. ### What `public` does and does not isolate `public` isolates sandboxes from each other and from the node's own services. It does **not** isolate them from the network the node sits on: pasta relays every outbound connection through the pod's own sockets and has no destination filter, so a `public` sandbox can reach other Ray nodes (including the head node's GCS and dashboard ports), other pods, and any internal service the node can reach. The docs now say this explicitly and keep `none` as the recommendation for untrusted code. Closing that gap needs egress policy outside pasta: a node-level netfilter rule set (which needs `CAP_NET_ADMIN` in the pod netns), or a second, intermediate user+network namespace we own and can firewall with nftables before handing traffic to the pod-side pasta. That is a follow-up, not part of this PR. ### Why not `pasta [flags] runsc ...` pasta can spawn a command in namespaces it creates itself, which would collapse the holder, pidfile, and nsenter into one wrapper. Prototyped in a privileged container (non-root, pasta from source, `pasta <flags> --foreground -- runsc ... run ...`): the command runs as uid 0 with a fixed `0 <uid> 1` map inside new user, net, **pid, mount, ipc, and uts** namespaces. runsc boots fine, but the pod side loses control of it: `runsc exec` fails with `waiting on pid 2: sandbox is not running` because the state file records the inner pid, and `runsc state` silently reports `running` whenever some unrelated pod process happens to have that pid. Every control call would have to be wrapped in `nsenter -U -n -p -m -t <child>` (that does work), and the single-uid map rules out the multi-uid mapping #65823 needs. The holder + attach shape keeps pid and mount namespaces shared for exactly that reason; with pasta in the foreground it costs one extra `sleep` process. Requires `pasta` and `nsenter` on nodes for `public` sandboxes. Docs updated (requirements, mode table with a warning admonition, install snippets, troubleshooting). Per-exec `user` and `write_file(append=)` moved to #65942 per review. ## Related issues Related to #65633. Per-exec user support split into #65942. ## Additional information Tested with `TEST_SANDBOX=1` in a privileged `rayproject/ray:nightly-py312` container on arm64 as the non-root `ray` user, with pasta built from source: two concurrent `public` sandboxes both bind `0.0.0.0:2222` and each reaches its own listener on `127.0.0.1:2222`; the worker namespace shows nothing on 2222; no address names one sandbox from another; egress and generated-resolv.conf DNS work; `delete_sandbox` and the create-failure path leave no pasta process behind (the tests diff the set of running pasta pids). The exact pasta flag list, the `--foreground`/pidfile gate, and the forced `--ignore-cgroups` are pinned by argv-level unit tests that run without runsc or pasta. ``` TEST_SANDBOX=1 pytest ray/experimental/sandbox/tests/test_gvisor_backend.py -k "netns or build_run_command or requires_pasta" 10 passed ``` --------- Signed-off-by: xyuzh <[email protected]>
|
Note: This approach won't work for the erofs, and even for for the rootfs stored in the filesystem, it might produce wrong results, since the |
f16942e to
8c46fc9
Compare
4d2430e to
a091004
Compare
|
@pcmoritz done in 89786c1: Tests: |
| raise SandboxExecError( | ||
| f"cannot read {path} inside the sandbox to resolve a user name " | ||
| f"(pass a numeric uid instead): {err}" | ||
| ) from err |
There was a problem hiding this comment.
Named-user exec ignores timeout
Low Severity
Named-user exec resolves the account by calling read_file on /etc/passwd and /etc/group before the timed runsc exec. Those reads have no timeout, so exec(..., user="alice", timeout=T) can hang indefinitely if the sandbox is unresponsive, while the same call with a numeric uid is killed after T seconds.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit a091004. Configure here.
a091004 to
5f12c13
Compare
|
Rebased onto #65992's head (e9973cd) per the merge order EROFS → per-exec user → HTTP API → gRPC facade, so this branch now carries that commit first; review the last commit. The per-exec user change already resolves names inside the running sandbox, so it needed no adaptation to the EROFS cache. Runtime suite of the stacked branch in the privileged |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
There are 2 total unresolved issues (including 1 from previous review).
Reviewed by Cursor Bugbot for commit 5f12c13. Configure here.
92aa019 to
89786c1
Compare
## Description Rootless gVisor serves each image's extracted directory through the gofer, so every file inside a sandbox reads as the worker's uid (root), image-baked ownership (postfix's `0700` uid-101 spool, mailman's uid-38 data) flattens away, and `chown` to another uid fails. Fixing that on the host needs subordinate id ranges and setuid helpers (#65823), which many environments can't provide. This caches each image as an **EROFS root filesystem** instead. gVisor mounts it inside the Sentry, so uids and gids live in the image and in the private overlay upper layer and never need a host representation: files keep their real owners and `chown` works for any uid, from an unprivileged worker, with no id mapping and no user namespace of ours. - **Build without root.** Extraction records each layer's non-root owners (whiteout-aware; a later root-owned layer drops the entry; hardlinks are recorded under their own name so the re-pack keeps the owner whichever name it emits first), the tree is re-packed as a tar whose headers carry them, and `mkfs.erofs --tar` (erofs-utils 1.7+) turns that into the image with `-E^inline_data` (gVisor's EROFS reader maps the image and only handles the flat-plain layout) and 4 KiB blocks. The extracted tree is deleted afterwards; the cache holds one file per image plus the image config. - **Mount via annotations.** The bundle gets `dev.gvisor.spec.rootfs.source/type/overlay`; the `self` overlay is anchored at a per-sandbox directory, and runsc no longer gets `--overlay2`. `readonly=True` keeps its semantics because the standard mount points (`/proc`, `/sys`, `/dev`, `/dev/pts`, `/dev/shm`, `/run`, `/tmp`, `/etc/{resolv.conf,hosts,hostname}`) are seeded into the image at build time; runsc applies no rootfs overlay to a read-only root and can't create mount points in an immutable image. - **Paths resolve inside the tree.** Extraction resolves each member's parent with the extracted tree as `/` (an absolute symlink target restarts at the root, `..` never climbs above it), so a member under a symlinked directory (UsrMerge's `bin -> usr/bin`, Debian's `/var/run -> /run`) lands where the image means it, its owner is recorded under that canonical path (where the re-pack finds it), and whiteouts delete through the same resolution. Before, a relative link left the owner keyed under the link path and the built image had the file as `0:0`; an absolute link dropped the member. The `/tmp` and mount-point seeding use the same resolver, so an image whose `etc`, `dev` or `tmp` links to a host directory gets its seeds inside the tree, never on the host; created files use `O_NOFOLLOW`, and a hardlink to a symlink links the symlink itself. - **EROFS is the only layout.** Per review, the extracted-directory layout (and its `RAY_SANDBOX_ROOTFS=dir` switch) is gone, so `mkfs.erofs` 1.7+ is a hard requirement on worker nodes next to `runsc`. A pull checks for it before downloading anything and fails with an error naming what to install. Ubuntu 24.04 and Debian 13 package a new enough erofs-utils; Ubuntu 22.04's is 1.4 and predates `--tar`, so nodes built on today's `rayproject/ray` images need it built from source (the docs carry the recipe). The `.extracted` marker moves to format 3, so a cache left by an earlier Ray re-pulls once; sandboxes still running on an old extracted tree keep it (the tree moves into the rebuilt entry, since a rename leaves the gofer's open root fd alone) and it is deleted on a later pull once no sandbox uses the image. - **CI.** The sandbox tests boot real sandboxes with `TEST_SANDBOX=1`, so the `corebuild` image now builds erofs-utils v1.9.4 from source (pinned to the tag's commit). Unit tests build images through a fake `mkfs.erofs` from `conftest.py` and inspect the resulting tar, so they run anywhere. **One known gap.** `readonly=True` with an explicit `workdir` runs on a private writable overlay (warned at spec time and documented): runsc drops the requested rootfs overlay for read-only roots, and an immutable image can't grow the workdir mount point. The clean fix is a small upstream change to runsc (`initGoferConfs`) to honor an explicitly requested rootfs overlay on a read-only root; `mountAll` already makes the root writable only while creating mount points. The test for the intended behavior is skipped with that reason and a new test pins today's behavior. Together with a Sentry-side network adapter that proxies to the host without `unshare --net`, this leaves no host requirements beyond `runsc` and `mkfs.erofs`. ## Related issues Supersedes #65823 (closed). Related to #65820 and #66004. **Merge order: this PR first.** #65942 (per-exec user), #65633 (HTTP API), and #65839 (gRPC facade) are stacked on this branch in that order; each carries the commits below it until those merge, so their diffs on GitHub include this commit until it lands. #65942 resolves `exec(user=<name>)` inside the running sandbox, so it works unchanged on this cache layout. ## Additional information Validated on x86_64 as well: an Anyscale staging cluster (`anyscale/ray:2.58.0-py312` + runsc release-20260817 + erofs-utils 1.9.4, three 8-CPU nodes) running Terminal-Bench 2.1 with the oracle agent through the `ray.experimental.sandbox` Python API. The `mailman` task, which depends on image-baked postfix/mailman file ownership surviving inside the sandbox, scores 0 on the directory layout and 1.0 with this change; the other 88 tasks are unchanged (89 trials, 0 errored). That is the exact ownership scenario this PR exists for, on a real cluster rather than a privileged dev container. Measured in a privileged `rayproject/ray:nightly-py312` container on arm64 (erofs-utils 1.9.4 built from source, runsc release-20260817): | image | pull + build | `rootfs.erofs` | extracted tree | | --- | --- | --- | --- | | python:3.10-slim | 7.1 s | 156.8 MB | 147 MB | | ubuntu:24.04 | 4.6 s | 108.0 MB | 104 MB | `mkfs.erofs` itself takes about 2 s for python:3.10-slim; `-E^inline_data` costs roughly 6% over the tree size, and the tree is gone afterwards, so the cache shrinks. A cache hit no longer walks an extracted tree for eviction accounting either (one file per image), which removes the ~60 ms per `pull_image` that @OneSizeFitsQuorum profiled on the directory layout. Runtime tests in that container as the unprivileged `ray` user with `TEST_SANDBOX=1` (`test_gvisor_backend.py`, `test_image_utils.py`, `test_image_manager.py`): 79 passed, 1 skipped (the readonly + workdir case above); the `ray.init` smoke test was run on its own. The run started from the cache the directory layout had left on that node, which the first pull rebuilt to the format-3 marker. They cover image-baked ownership from a local tar (`101:0:700`, `101:104:2710` setgid dir, a setuid tool), root traversing another user's `0700` directory, `chown` to arbitrary uids and `chown -R` with setgid inheritance, a readonly EROFS root with writable `/tmp`, `network="host"` egress, the `network="public"` netns suite, and the existing lifecycle, overlay isolation, and workdir suites. Unit tests cover ownership recording across layers including hardlinks, the owner-restoring tar filter, the build through a fake `mkfs.erofs`, the missing/too-old `mkfs.erofs` error, the format-3 re-pull with and without running sandboxes, and the EROFS OCI spec. Signed-off-by: xyuzh <[email protected]>
…5992) ## Description Rootless gVisor serves each image's extracted directory through the gofer, so every file inside a sandbox reads as the worker's uid (root), image-baked ownership (postfix's `0700` uid-101 spool, mailman's uid-38 data) flattens away, and `chown` to another uid fails. Fixing that on the host needs subordinate id ranges and setuid helpers (ray-project#65823), which many environments can't provide. This caches each image as an **EROFS root filesystem** instead. gVisor mounts it inside the Sentry, so uids and gids live in the image and in the private overlay upper layer and never need a host representation: files keep their real owners and `chown` works for any uid, from an unprivileged worker, with no id mapping and no user namespace of ours. - **Build without root.** Extraction records each layer's non-root owners (whiteout-aware; a later root-owned layer drops the entry; hardlinks are recorded under their own name so the re-pack keeps the owner whichever name it emits first), the tree is re-packed as a tar whose headers carry them, and `mkfs.erofs --tar` (erofs-utils 1.7+) turns that into the image with `-E^inline_data` (gVisor's EROFS reader maps the image and only handles the flat-plain layout) and 4 KiB blocks. The extracted tree is deleted afterwards; the cache holds one file per image plus the image config. - **Mount via annotations.** The bundle gets `dev.gvisor.spec.rootfs.source/type/overlay`; the `self` overlay is anchored at a per-sandbox directory, and runsc no longer gets `--overlay2`. `readonly=True` keeps its semantics because the standard mount points (`/proc`, `/sys`, `/dev`, `/dev/pts`, `/dev/shm`, `/run`, `/tmp`, `/etc/{resolv.conf,hosts,hostname}`) are seeded into the image at build time; runsc applies no rootfs overlay to a read-only root and can't create mount points in an immutable image. - **Paths resolve inside the tree.** Extraction resolves each member's parent with the extracted tree as `/` (an absolute symlink target restarts at the root, `..` never climbs above it), so a member under a symlinked directory (UsrMerge's `bin -> usr/bin`, Debian's `/var/run -> /run`) lands where the image means it, its owner is recorded under that canonical path (where the re-pack finds it), and whiteouts delete through the same resolution. Before, a relative link left the owner keyed under the link path and the built image had the file as `0:0`; an absolute link dropped the member. The `/tmp` and mount-point seeding use the same resolver, so an image whose `etc`, `dev` or `tmp` links to a host directory gets its seeds inside the tree, never on the host; created files use `O_NOFOLLOW`, and a hardlink to a symlink links the symlink itself. - **EROFS is the only layout.** Per review, the extracted-directory layout (and its `RAY_SANDBOX_ROOTFS=dir` switch) is gone, so `mkfs.erofs` 1.7+ is a hard requirement on worker nodes next to `runsc`. A pull checks for it before downloading anything and fails with an error naming what to install. Ubuntu 24.04 and Debian 13 package a new enough erofs-utils; Ubuntu 22.04's is 1.4 and predates `--tar`, so nodes built on today's `rayproject/ray` images need it built from source (the docs carry the recipe). The `.extracted` marker moves to format 3, so a cache left by an earlier Ray re-pulls once; sandboxes still running on an old extracted tree keep it (the tree moves into the rebuilt entry, since a rename leaves the gofer's open root fd alone) and it is deleted on a later pull once no sandbox uses the image. - **CI.** The sandbox tests boot real sandboxes with `TEST_SANDBOX=1`, so the `corebuild` image now builds erofs-utils v1.9.4 from source (pinned to the tag's commit). Unit tests build images through a fake `mkfs.erofs` from `conftest.py` and inspect the resulting tar, so they run anywhere. **One known gap.** `readonly=True` with an explicit `workdir` runs on a private writable overlay (warned at spec time and documented): runsc drops the requested rootfs overlay for read-only roots, and an immutable image can't grow the workdir mount point. The clean fix is a small upstream change to runsc (`initGoferConfs`) to honor an explicitly requested rootfs overlay on a read-only root; `mountAll` already makes the root writable only while creating mount points. The test for the intended behavior is skipped with that reason and a new test pins today's behavior. Together with a Sentry-side network adapter that proxies to the host without `unshare --net`, this leaves no host requirements beyond `runsc` and `mkfs.erofs`. ## Related issues Supersedes ray-project#65823 (closed). Related to ray-project#65820 and ray-project#66004. **Merge order: this PR first.** ray-project#65942 (per-exec user), ray-project#65633 (HTTP API), and ray-project#65839 (gRPC facade) are stacked on this branch in that order; each carries the commits below it until those merge, so their diffs on GitHub include this commit until it lands. ray-project#65942 resolves `exec(user=<name>)` inside the running sandbox, so it works unchanged on this cache layout. ## Additional information Validated on x86_64 as well: an Anyscale staging cluster (`anyscale/ray:2.58.0-py312` + runsc release-20260817 + erofs-utils 1.9.4, three 8-CPU nodes) running Terminal-Bench 2.1 with the oracle agent through the `ray.experimental.sandbox` Python API. The `mailman` task, which depends on image-baked postfix/mailman file ownership surviving inside the sandbox, scores 0 on the directory layout and 1.0 with this change; the other 88 tasks are unchanged (89 trials, 0 errored). That is the exact ownership scenario this PR exists for, on a real cluster rather than a privileged dev container. Measured in a privileged `rayproject/ray:nightly-py312` container on arm64 (erofs-utils 1.9.4 built from source, runsc release-20260817): | image | pull + build | `rootfs.erofs` | extracted tree | | --- | --- | --- | --- | | python:3.10-slim | 7.1 s | 156.8 MB | 147 MB | | ubuntu:24.04 | 4.6 s | 108.0 MB | 104 MB | `mkfs.erofs` itself takes about 2 s for python:3.10-slim; `-E^inline_data` costs roughly 6% over the tree size, and the tree is gone afterwards, so the cache shrinks. A cache hit no longer walks an extracted tree for eviction accounting either (one file per image), which removes the ~60 ms per `pull_image` that @OneSizeFitsQuorum profiled on the directory layout. Runtime tests in that container as the unprivileged `ray` user with `TEST_SANDBOX=1` (`test_gvisor_backend.py`, `test_image_utils.py`, `test_image_manager.py`): 79 passed, 1 skipped (the readonly + workdir case above); the `ray.init` smoke test was run on its own. The run started from the cache the directory layout had left on that node, which the first pull rebuilt to the format-3 marker. They cover image-baked ownership from a local tar (`101:0:700`, `101:104:2710` setgid dir, a setuid tool), root traversing another user's `0700` directory, `chown` to arbitrary uids and `chown -R` with setgid inheritance, a readonly EROFS root with writable `/tmp`, `network="host"` egress, the `network="public"` netns suite, and the existing lifecycle, overlay isolation, and workdir suites. Unit tests cover ownership recording across layers including hardlinks, the owner-restoring tar filter, the build through a fake `mkfs.erofs`, the missing/too-old `mkfs.erofs` error, the format-3 re-pull with and without running sandboxes, and the EROFS OCI spec. Signed-off-by: xyuzh <[email protected]>
…sor backend - `exec(..., user=)` runs a command as a numeric uid, `uid:gid`, or a user (and optionally group) name. runsc only accepts numeric ids, so names resolve against the /etc/passwd and /etc/group inside the running sandbox, read through a first exec before the real command: that covers users the image ships and users added since, and needs no host copy of the root filesystem, so it is independent of the image cache layout. A named user with no explicit group gets its login group; numeric ids never touch the sandbox. - `write_file(..., append=True)` extends a file instead of truncating it, so callers can upload large files in chunks. Both are plumbed through `SandboxRuntime`; the external sandbox APIs (HTTP service, gRPC facade) build on them. Signed-off-by: xyuzh <[email protected]>
89786c1 to
21d3640
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]>
## 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]>
…ns via pasta (ray-project#65820) ## Description `network="public"` sandboxes currently run with runsc `--network=host` in the Ray worker's own network namespace: every sandbox on a node shares one port space, so concurrent workloads that bind a fixed port collide and can reach each other's listeners. The concrete failure is terminal-bench's QEMU tasks (`qemu-startup`, `qemu-alpine-ssh`), which start QEMU with `hostfwd=tcp::2222-:22` and then SSH to `localhost:2222` from inside the same sandbox. Under co-tenancy the second bind gets `EADDRINUSE`, and a verifier can connect to a *different* sandbox's guest. This PR gives each `public` sandbox a private user+network namespace pair bridged by pasta (passt) user-mode networking, the rootless-Podman topology: - a tiny holder process (`unshare --user --map-root-user --net`) pins the namespaces for the sandbox's lifetime; - `pasta` attaches from the pod side (`--netns/--userns /proc/$PID/ns/*`) and runs in the **foreground** inside the sandbox's process group, so teardown's `killpg` takes it with the rest of the tree. `-t/-u/-T/-U none --no-map-gw` make it egress-only: in-sandbox binds are never republished on the pod, pod-local services are unreachable from the sandbox loopback, and there is no inbound path; - `runsc run` executes inside via `nsenter` as mapped root. `--rootless` is dropped because nesting a second userns breaks the gofer's `/proc` magic-link derefs; since rootless mode is also what tolerated cgroup permission failures, the wrapper forces `--ignore-cgroups` for rootless configs. runsc still gets `--network=host`, but "host" is now private to the sandbox. Mount and pid namespaces stay shared, so the bundle and control sockets under `--root` keep working for pod-side `state`/`exec`/`kill`/`delete`. ### What `public` does and does not isolate `public` isolates sandboxes from each other and from the node's own services. It does **not** isolate them from the network the node sits on: pasta relays every outbound connection through the pod's own sockets and has no destination filter, so a `public` sandbox can reach other Ray nodes (including the head node's GCS and dashboard ports), other pods, and any internal service the node can reach. The docs now say this explicitly and keep `none` as the recommendation for untrusted code. Closing that gap needs egress policy outside pasta: a node-level netfilter rule set (which needs `CAP_NET_ADMIN` in the pod netns), or a second, intermediate user+network namespace we own and can firewall with nftables before handing traffic to the pod-side pasta. That is a follow-up, not part of this PR. ### Why not `pasta [flags] runsc ...` pasta can spawn a command in namespaces it creates itself, which would collapse the holder, pidfile, and nsenter into one wrapper. Prototyped in a privileged container (non-root, pasta from source, `pasta <flags> --foreground -- runsc ... run ...`): the command runs as uid 0 with a fixed `0 <uid> 1` map inside new user, net, **pid, mount, ipc, and uts** namespaces. runsc boots fine, but the pod side loses control of it: `runsc exec` fails with `waiting on pid 2: sandbox is not running` because the state file records the inner pid, and `runsc state` silently reports `running` whenever some unrelated pod process happens to have that pid. Every control call would have to be wrapped in `nsenter -U -n -p -m -t <child>` (that does work), and the single-uid map rules out the multi-uid mapping ray-project#65823 needs. The holder + attach shape keeps pid and mount namespaces shared for exactly that reason; with pasta in the foreground it costs one extra `sleep` process. Requires `pasta` and `nsenter` on nodes for `public` sandboxes. Docs updated (requirements, mode table with a warning admonition, install snippets, troubleshooting). Per-exec `user` and `write_file(append=)` moved to ray-project#65942 per review. ## Related issues Related to ray-project#65633. Per-exec user support split into ray-project#65942. ## Additional information Tested with `TEST_SANDBOX=1` in a privileged `rayproject/ray:nightly-py312` container on arm64 as the non-root `ray` user, with pasta built from source: two concurrent `public` sandboxes both bind `0.0.0.0:2222` and each reaches its own listener on `127.0.0.1:2222`; the worker namespace shows nothing on 2222; no address names one sandbox from another; egress and generated-resolv.conf DNS work; `delete_sandbox` and the create-failure path leave no pasta process behind (the tests diff the set of running pasta pids). The exact pasta flag list, the `--foreground`/pidfile gate, and the forced `--ignore-cgroups` are pinned by argv-level unit tests that run without runsc or pasta. ``` TEST_SANDBOX=1 pytest ray/experimental/sandbox/tests/test_gvisor_backend.py -k "netns or build_run_command or requires_pasta" 10 passed ``` --------- Signed-off-by: xyuzh <[email protected]>
…5992) ## Description Rootless gVisor serves each image's extracted directory through the gofer, so every file inside a sandbox reads as the worker's uid (root), image-baked ownership (postfix's `0700` uid-101 spool, mailman's uid-38 data) flattens away, and `chown` to another uid fails. Fixing that on the host needs subordinate id ranges and setuid helpers (ray-project#65823), which many environments can't provide. This caches each image as an **EROFS root filesystem** instead. gVisor mounts it inside the Sentry, so uids and gids live in the image and in the private overlay upper layer and never need a host representation: files keep their real owners and `chown` works for any uid, from an unprivileged worker, with no id mapping and no user namespace of ours. - **Build without root.** Extraction records each layer's non-root owners (whiteout-aware; a later root-owned layer drops the entry; hardlinks are recorded under their own name so the re-pack keeps the owner whichever name it emits first), the tree is re-packed as a tar whose headers carry them, and `mkfs.erofs --tar` (erofs-utils 1.7+) turns that into the image with `-E^inline_data` (gVisor's EROFS reader maps the image and only handles the flat-plain layout) and 4 KiB blocks. The extracted tree is deleted afterwards; the cache holds one file per image plus the image config. - **Mount via annotations.** The bundle gets `dev.gvisor.spec.rootfs.source/type/overlay`; the `self` overlay is anchored at a per-sandbox directory, and runsc no longer gets `--overlay2`. `readonly=True` keeps its semantics because the standard mount points (`/proc`, `/sys`, `/dev`, `/dev/pts`, `/dev/shm`, `/run`, `/tmp`, `/etc/{resolv.conf,hosts,hostname}`) are seeded into the image at build time; runsc applies no rootfs overlay to a read-only root and can't create mount points in an immutable image. - **Paths resolve inside the tree.** Extraction resolves each member's parent with the extracted tree as `/` (an absolute symlink target restarts at the root, `..` never climbs above it), so a member under a symlinked directory (UsrMerge's `bin -> usr/bin`, Debian's `/var/run -> /run`) lands where the image means it, its owner is recorded under that canonical path (where the re-pack finds it), and whiteouts delete through the same resolution. Before, a relative link left the owner keyed under the link path and the built image had the file as `0:0`; an absolute link dropped the member. The `/tmp` and mount-point seeding use the same resolver, so an image whose `etc`, `dev` or `tmp` links to a host directory gets its seeds inside the tree, never on the host; created files use `O_NOFOLLOW`, and a hardlink to a symlink links the symlink itself. - **EROFS is the only layout.** Per review, the extracted-directory layout (and its `RAY_SANDBOX_ROOTFS=dir` switch) is gone, so `mkfs.erofs` 1.7+ is a hard requirement on worker nodes next to `runsc`. A pull checks for it before downloading anything and fails with an error naming what to install. Ubuntu 24.04 and Debian 13 package a new enough erofs-utils; Ubuntu 22.04's is 1.4 and predates `--tar`, so nodes built on today's `rayproject/ray` images need it built from source (the docs carry the recipe). The `.extracted` marker moves to format 3, so a cache left by an earlier Ray re-pulls once; sandboxes still running on an old extracted tree keep it (the tree moves into the rebuilt entry, since a rename leaves the gofer's open root fd alone) and it is deleted on a later pull once no sandbox uses the image. - **CI.** The sandbox tests boot real sandboxes with `TEST_SANDBOX=1`, so the `corebuild` image now builds erofs-utils v1.9.4 from source (pinned to the tag's commit). Unit tests build images through a fake `mkfs.erofs` from `conftest.py` and inspect the resulting tar, so they run anywhere. **One known gap.** `readonly=True` with an explicit `workdir` runs on a private writable overlay (warned at spec time and documented): runsc drops the requested rootfs overlay for read-only roots, and an immutable image can't grow the workdir mount point. The clean fix is a small upstream change to runsc (`initGoferConfs`) to honor an explicitly requested rootfs overlay on a read-only root; `mountAll` already makes the root writable only while creating mount points. The test for the intended behavior is skipped with that reason and a new test pins today's behavior. Together with a Sentry-side network adapter that proxies to the host without `unshare --net`, this leaves no host requirements beyond `runsc` and `mkfs.erofs`. ## Related issues Supersedes ray-project#65823 (closed). Related to ray-project#65820 and ray-project#66004. **Merge order: this PR first.** ray-project#65942 (per-exec user), ray-project#65633 (HTTP API), and ray-project#65839 (gRPC facade) are stacked on this branch in that order; each carries the commits below it until those merge, so their diffs on GitHub include this commit until it lands. ray-project#65942 resolves `exec(user=<name>)` inside the running sandbox, so it works unchanged on this cache layout. ## Additional information Validated on x86_64 as well: an Anyscale staging cluster (`anyscale/ray:2.58.0-py312` + runsc release-20260817 + erofs-utils 1.9.4, three 8-CPU nodes) running Terminal-Bench 2.1 with the oracle agent through the `ray.experimental.sandbox` Python API. The `mailman` task, which depends on image-baked postfix/mailman file ownership surviving inside the sandbox, scores 0 on the directory layout and 1.0 with this change; the other 88 tasks are unchanged (89 trials, 0 errored). That is the exact ownership scenario this PR exists for, on a real cluster rather than a privileged dev container. Measured in a privileged `rayproject/ray:nightly-py312` container on arm64 (erofs-utils 1.9.4 built from source, runsc release-20260817): | image | pull + build | `rootfs.erofs` | extracted tree | | --- | --- | --- | --- | | python:3.10-slim | 7.1 s | 156.8 MB | 147 MB | | ubuntu:24.04 | 4.6 s | 108.0 MB | 104 MB | `mkfs.erofs` itself takes about 2 s for python:3.10-slim; `-E^inline_data` costs roughly 6% over the tree size, and the tree is gone afterwards, so the cache shrinks. A cache hit no longer walks an extracted tree for eviction accounting either (one file per image), which removes the ~60 ms per `pull_image` that @OneSizeFitsQuorum profiled on the directory layout. Runtime tests in that container as the unprivileged `ray` user with `TEST_SANDBOX=1` (`test_gvisor_backend.py`, `test_image_utils.py`, `test_image_manager.py`): 79 passed, 1 skipped (the readonly + workdir case above); the `ray.init` smoke test was run on its own. The run started from the cache the directory layout had left on that node, which the first pull rebuilt to the format-3 marker. They cover image-baked ownership from a local tar (`101:0:700`, `101:104:2710` setgid dir, a setuid tool), root traversing another user's `0700` directory, `chown` to arbitrary uids and `chown -R` with setgid inheritance, a readonly EROFS root with writable `/tmp`, `network="host"` egress, the `network="public"` netns suite, and the existing lifecycle, overlay isolation, and workdir suites. Unit tests cover ownership recording across layers including hardlinks, the owner-restoring tar filter, the build through a fake `mkfs.erofs`, the missing/too-old `mkfs.erofs` error, the format-3 re-pull with and without running sandboxes, and the EROFS OCI spec. Signed-off-by: xyuzh <[email protected]>
…sor backend (ray-project#65942) ## Description Two small additions to the gVisor backend and `SandboxRuntime`, split out of ray-project#65820 at reviewer request so that PR stays about network namespaces: - **Per-exec user.** `exec(..., user=)` runs a command as a numeric uid, `uid:gid`, or a user (and optionally group) name. runsc only accepts numeric ids, so names resolve against the `/etc/passwd` and `/etc/group` **inside the running sandbox**, read through a first exec (`cat`) before the real command runs. That covers users the image ships and users added since (`adduser` in the sandbox), and it needs no host copy of the root filesystem, so it works the same on the EROFS cache of ray-project#65992. A named user with no explicit group gets its login group; numeric ids never touch the sandbox. - **Appending writes.** `write_file(..., append=True)` extends a file instead of truncating it, so callers can upload large files in chunks under proxy body-size limits. Both are plumbed through `SandboxRuntime`. The external sandbox APIs (ray-project#65633 and the gRPC facade in ray-project#65839) build on them; those PRs will rebase onto this one. ## Related issues Split from ray-project#65820 per review. **Next to review.** ray-project#65992 (EROFS) has merged and this branch is rebased onto master, so the diff is this PR's commit alone. Merge order for the rest of the stack is ray-project#65942 → ray-project#65633 → ray-project#65839; ray-project#65633 and ray-project#65839 are stacked on this PR. ## Additional information `test_resolve_exec_user` covers numeric pass-through, `name`, `name:gid`, `name:group`, `uid:group`, a truncated passwd line, the unknown user/group errors, an unreadable account file, and that the group file is only read for a group name; it stubs the in-sandbox read and runs without runsc. `test_exec_as_named_user_resolves_inside_the_sandbox` boots busybox and checks that `user="nobody"` and `user="65534"` agree, that a user added with `adduser` after boot resolves, and that an unknown name is a `SandboxExecError`. Container run (`rayproject/ray:nightly-py312`, runsc release-20260817, as the `ray` user): `TEST_SANDBOX=1 pytest test_gvisor_backend.py` 24 passed (netns suite included), with the `ray.init` smoke test run on its own. `ruff check`, `ruff check --select I`, `black`, and `pydoclint` pass with the pre-commit versions and flags. Signed-off-by: xyuzh <[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]>
…ns via pasta (ray-project#65820) ## Description `network="public"` sandboxes currently run with runsc `--network=host` in the Ray worker's own network namespace: every sandbox on a node shares one port space, so concurrent workloads that bind a fixed port collide and can reach each other's listeners. The concrete failure is terminal-bench's QEMU tasks (`qemu-startup`, `qemu-alpine-ssh`), which start QEMU with `hostfwd=tcp::2222-:22` and then SSH to `localhost:2222` from inside the same sandbox. Under co-tenancy the second bind gets `EADDRINUSE`, and a verifier can connect to a *different* sandbox's guest. This PR gives each `public` sandbox a private user+network namespace pair bridged by pasta (passt) user-mode networking, the rootless-Podman topology: - a tiny holder process (`unshare --user --map-root-user --net`) pins the namespaces for the sandbox's lifetime; - `pasta` attaches from the pod side (`--netns/--userns /proc/$PID/ns/*`) and runs in the **foreground** inside the sandbox's process group, so teardown's `killpg` takes it with the rest of the tree. `-t/-u/-T/-U none --no-map-gw` make it egress-only: in-sandbox binds are never republished on the pod, pod-local services are unreachable from the sandbox loopback, and there is no inbound path; - `runsc run` executes inside via `nsenter` as mapped root. `--rootless` is dropped because nesting a second userns breaks the gofer's `/proc` magic-link derefs; since rootless mode is also what tolerated cgroup permission failures, the wrapper forces `--ignore-cgroups` for rootless configs. runsc still gets `--network=host`, but "host" is now private to the sandbox. Mount and pid namespaces stay shared, so the bundle and control sockets under `--root` keep working for pod-side `state`/`exec`/`kill`/`delete`. ### What `public` does and does not isolate `public` isolates sandboxes from each other and from the node's own services. It does **not** isolate them from the network the node sits on: pasta relays every outbound connection through the pod's own sockets and has no destination filter, so a `public` sandbox can reach other Ray nodes (including the head node's GCS and dashboard ports), other pods, and any internal service the node can reach. The docs now say this explicitly and keep `none` as the recommendation for untrusted code. Closing that gap needs egress policy outside pasta: a node-level netfilter rule set (which needs `CAP_NET_ADMIN` in the pod netns), or a second, intermediate user+network namespace we own and can firewall with nftables before handing traffic to the pod-side pasta. That is a follow-up, not part of this PR. ### Why not `pasta [flags] runsc ...` pasta can spawn a command in namespaces it creates itself, which would collapse the holder, pidfile, and nsenter into one wrapper. Prototyped in a privileged container (non-root, pasta from source, `pasta <flags> --foreground -- runsc ... run ...`): the command runs as uid 0 with a fixed `0 <uid> 1` map inside new user, net, **pid, mount, ipc, and uts** namespaces. runsc boots fine, but the pod side loses control of it: `runsc exec` fails with `waiting on pid 2: sandbox is not running` because the state file records the inner pid, and `runsc state` silently reports `running` whenever some unrelated pod process happens to have that pid. Every control call would have to be wrapped in `nsenter -U -n -p -m -t <child>` (that does work), and the single-uid map rules out the multi-uid mapping ray-project#65823 needs. The holder + attach shape keeps pid and mount namespaces shared for exactly that reason; with pasta in the foreground it costs one extra `sleep` process. Requires `pasta` and `nsenter` on nodes for `public` sandboxes. Docs updated (requirements, mode table with a warning admonition, install snippets, troubleshooting). Per-exec `user` and `write_file(append=)` moved to ray-project#65942 per review. ## Related issues Related to ray-project#65633. Per-exec user support split into ray-project#65942. ## Additional information Tested with `TEST_SANDBOX=1` in a privileged `rayproject/ray:nightly-py312` container on arm64 as the non-root `ray` user, with pasta built from source: two concurrent `public` sandboxes both bind `0.0.0.0:2222` and each reaches its own listener on `127.0.0.1:2222`; the worker namespace shows nothing on 2222; no address names one sandbox from another; egress and generated-resolv.conf DNS work; `delete_sandbox` and the create-failure path leave no pasta process behind (the tests diff the set of running pasta pids). The exact pasta flag list, the `--foreground`/pidfile gate, and the forced `--ignore-cgroups` are pinned by argv-level unit tests that run without runsc or pasta. ``` TEST_SANDBOX=1 pytest ray/experimental/sandbox/tests/test_gvisor_backend.py -k "netns or build_run_command or requires_pasta" 10 passed ``` --------- Signed-off-by: xyuzh <[email protected]>
…5992) ## Description Rootless gVisor serves each image's extracted directory through the gofer, so every file inside a sandbox reads as the worker's uid (root), image-baked ownership (postfix's `0700` uid-101 spool, mailman's uid-38 data) flattens away, and `chown` to another uid fails. Fixing that on the host needs subordinate id ranges and setuid helpers (ray-project#65823), which many environments can't provide. This caches each image as an **EROFS root filesystem** instead. gVisor mounts it inside the Sentry, so uids and gids live in the image and in the private overlay upper layer and never need a host representation: files keep their real owners and `chown` works for any uid, from an unprivileged worker, with no id mapping and no user namespace of ours. - **Build without root.** Extraction records each layer's non-root owners (whiteout-aware; a later root-owned layer drops the entry; hardlinks are recorded under their own name so the re-pack keeps the owner whichever name it emits first), the tree is re-packed as a tar whose headers carry them, and `mkfs.erofs --tar` (erofs-utils 1.7+) turns that into the image with `-E^inline_data` (gVisor's EROFS reader maps the image and only handles the flat-plain layout) and 4 KiB blocks. The extracted tree is deleted afterwards; the cache holds one file per image plus the image config. - **Mount via annotations.** The bundle gets `dev.gvisor.spec.rootfs.source/type/overlay`; the `self` overlay is anchored at a per-sandbox directory, and runsc no longer gets `--overlay2`. `readonly=True` keeps its semantics because the standard mount points (`/proc`, `/sys`, `/dev`, `/dev/pts`, `/dev/shm`, `/run`, `/tmp`, `/etc/{resolv.conf,hosts,hostname}`) are seeded into the image at build time; runsc applies no rootfs overlay to a read-only root and can't create mount points in an immutable image. - **Paths resolve inside the tree.** Extraction resolves each member's parent with the extracted tree as `/` (an absolute symlink target restarts at the root, `..` never climbs above it), so a member under a symlinked directory (UsrMerge's `bin -> usr/bin`, Debian's `/var/run -> /run`) lands where the image means it, its owner is recorded under that canonical path (where the re-pack finds it), and whiteouts delete through the same resolution. Before, a relative link left the owner keyed under the link path and the built image had the file as `0:0`; an absolute link dropped the member. The `/tmp` and mount-point seeding use the same resolver, so an image whose `etc`, `dev` or `tmp` links to a host directory gets its seeds inside the tree, never on the host; created files use `O_NOFOLLOW`, and a hardlink to a symlink links the symlink itself. - **EROFS is the only layout.** Per review, the extracted-directory layout (and its `RAY_SANDBOX_ROOTFS=dir` switch) is gone, so `mkfs.erofs` 1.7+ is a hard requirement on worker nodes next to `runsc`. A pull checks for it before downloading anything and fails with an error naming what to install. Ubuntu 24.04 and Debian 13 package a new enough erofs-utils; Ubuntu 22.04's is 1.4 and predates `--tar`, so nodes built on today's `rayproject/ray` images need it built from source (the docs carry the recipe). The `.extracted` marker moves to format 3, so a cache left by an earlier Ray re-pulls once; sandboxes still running on an old extracted tree keep it (the tree moves into the rebuilt entry, since a rename leaves the gofer's open root fd alone) and it is deleted on a later pull once no sandbox uses the image. - **CI.** The sandbox tests boot real sandboxes with `TEST_SANDBOX=1`, so the `corebuild` image now builds erofs-utils v1.9.4 from source (pinned to the tag's commit). Unit tests build images through a fake `mkfs.erofs` from `conftest.py` and inspect the resulting tar, so they run anywhere. **One known gap.** `readonly=True` with an explicit `workdir` runs on a private writable overlay (warned at spec time and documented): runsc drops the requested rootfs overlay for read-only roots, and an immutable image can't grow the workdir mount point. The clean fix is a small upstream change to runsc (`initGoferConfs`) to honor an explicitly requested rootfs overlay on a read-only root; `mountAll` already makes the root writable only while creating mount points. The test for the intended behavior is skipped with that reason and a new test pins today's behavior. Together with a Sentry-side network adapter that proxies to the host without `unshare --net`, this leaves no host requirements beyond `runsc` and `mkfs.erofs`. ## Related issues Supersedes ray-project#65823 (closed). Related to ray-project#65820 and ray-project#66004. **Merge order: this PR first.** ray-project#65942 (per-exec user), ray-project#65633 (HTTP API), and ray-project#65839 (gRPC facade) are stacked on this branch in that order; each carries the commits below it until those merge, so their diffs on GitHub include this commit until it lands. ray-project#65942 resolves `exec(user=<name>)` inside the running sandbox, so it works unchanged on this cache layout. ## Additional information Validated on x86_64 as well: an Anyscale staging cluster (`anyscale/ray:2.58.0-py312` + runsc release-20260817 + erofs-utils 1.9.4, three 8-CPU nodes) running Terminal-Bench 2.1 with the oracle agent through the `ray.experimental.sandbox` Python API. The `mailman` task, which depends on image-baked postfix/mailman file ownership surviving inside the sandbox, scores 0 on the directory layout and 1.0 with this change; the other 88 tasks are unchanged (89 trials, 0 errored). That is the exact ownership scenario this PR exists for, on a real cluster rather than a privileged dev container. Measured in a privileged `rayproject/ray:nightly-py312` container on arm64 (erofs-utils 1.9.4 built from source, runsc release-20260817): | image | pull + build | `rootfs.erofs` | extracted tree | | --- | --- | --- | --- | | python:3.10-slim | 7.1 s | 156.8 MB | 147 MB | | ubuntu:24.04 | 4.6 s | 108.0 MB | 104 MB | `mkfs.erofs` itself takes about 2 s for python:3.10-slim; `-E^inline_data` costs roughly 6% over the tree size, and the tree is gone afterwards, so the cache shrinks. A cache hit no longer walks an extracted tree for eviction accounting either (one file per image), which removes the ~60 ms per `pull_image` that @OneSizeFitsQuorum profiled on the directory layout. Runtime tests in that container as the unprivileged `ray` user with `TEST_SANDBOX=1` (`test_gvisor_backend.py`, `test_image_utils.py`, `test_image_manager.py`): 79 passed, 1 skipped (the readonly + workdir case above); the `ray.init` smoke test was run on its own. The run started from the cache the directory layout had left on that node, which the first pull rebuilt to the format-3 marker. They cover image-baked ownership from a local tar (`101:0:700`, `101:104:2710` setgid dir, a setuid tool), root traversing another user's `0700` directory, `chown` to arbitrary uids and `chown -R` with setgid inheritance, a readonly EROFS root with writable `/tmp`, `network="host"` egress, the `network="public"` netns suite, and the existing lifecycle, overlay isolation, and workdir suites. Unit tests cover ownership recording across layers including hardlinks, the owner-restoring tar filter, the build through a fake `mkfs.erofs`, the missing/too-old `mkfs.erofs` error, the format-3 re-pull with and without running sandboxes, and the EROFS OCI spec. Signed-off-by: xyuzh <[email protected]>
…sor backend (ray-project#65942) ## Description Two small additions to the gVisor backend and `SandboxRuntime`, split out of ray-project#65820 at reviewer request so that PR stays about network namespaces: - **Per-exec user.** `exec(..., user=)` runs a command as a numeric uid, `uid:gid`, or a user (and optionally group) name. runsc only accepts numeric ids, so names resolve against the `/etc/passwd` and `/etc/group` **inside the running sandbox**, read through a first exec (`cat`) before the real command runs. That covers users the image ships and users added since (`adduser` in the sandbox), and it needs no host copy of the root filesystem, so it works the same on the EROFS cache of ray-project#65992. A named user with no explicit group gets its login group; numeric ids never touch the sandbox. - **Appending writes.** `write_file(..., append=True)` extends a file instead of truncating it, so callers can upload large files in chunks under proxy body-size limits. Both are plumbed through `SandboxRuntime`. The external sandbox APIs (ray-project#65633 and the gRPC facade in ray-project#65839) build on them; those PRs will rebase onto this one. ## Related issues Split from ray-project#65820 per review. **Next to review.** ray-project#65992 (EROFS) has merged and this branch is rebased onto master, so the diff is this PR's commit alone. Merge order for the rest of the stack is ray-project#65942 → ray-project#65633 → ray-project#65839; ray-project#65633 and ray-project#65839 are stacked on this PR. ## Additional information `test_resolve_exec_user` covers numeric pass-through, `name`, `name:gid`, `name:group`, `uid:group`, a truncated passwd line, the unknown user/group errors, an unreadable account file, and that the group file is only read for a group name; it stubs the in-sandbox read and runs without runsc. `test_exec_as_named_user_resolves_inside_the_sandbox` boots busybox and checks that `user="nobody"` and `user="65534"` agree, that a user added with `adduser` after boot resolves, and that an unknown name is a `SandboxExecError`. Container run (`rayproject/ray:nightly-py312`, runsc release-20260817, as the `ray` user): `TEST_SANDBOX=1 pytest test_gvisor_backend.py` 24 passed (netns suite included), with the `ray.init` smoke test run on its own. `ruff check`, `ruff check --select I`, `black`, and `pydoclint` pass with the pre-commit versions and flags. Signed-off-by: xyuzh <[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]>


Description
Two small additions to the gVisor backend and
SandboxRuntime, split out of #65820 at reviewer request so that PR stays about network namespaces:exec(..., user=)runs a command as a numeric uid,uid:gid, or a user (and optionally group) name. runsc only accepts numeric ids, so names resolve against the/etc/passwdand/etc/groupinside the running sandbox, read through a first exec (cat) before the real command runs. That covers users the image ships and users added since (adduserin the sandbox), and it needs no host copy of the root filesystem, so it works the same on the EROFS cache of [core][sandbox] Cache images as EROFS root filesystems #65992. A named user with no explicit group gets its login group; numeric ids never touch the sandbox.write_file(..., append=True)extends a file instead of truncating it, so callers can upload large files in chunks under proxy body-size limits.Both are plumbed through
SandboxRuntime. The external sandbox APIs (#65633 and the gRPC facade in #65839) build on them; those PRs will rebase onto this one.Related issues
Split from #65820 per review.
Next to review. #65992 (EROFS) has merged and this branch is rebased onto master, so the diff is this PR's commit alone. Merge order for the rest of the stack is #65942 → #65633 → #65839; #65633 and #65839 are stacked on this PR.
Additional information
test_resolve_exec_usercovers numeric pass-through,name,name:gid,name:group,uid:group, a truncated passwd line, the unknown user/group errors, an unreadable account file, and that the group file is only read for a group name; it stubs the in-sandbox read and runs without runsc.test_exec_as_named_user_resolves_inside_the_sandboxboots busybox and checks thatuser="nobody"anduser="65534"agree, that a user added withadduserafter boot resolves, and that an unknown name is aSandboxExecError. Container run (rayproject/ray:nightly-py312, runsc release-20260817, as therayuser):TEST_SANDBOX=1 pytest test_gvisor_backend.py24 passed (netns suite included), with theray.initsmoke test run on its own.ruff check,ruff check --select I,black, andpydoclintpass with the pre-commit versions and flags.