Repository navigation
[core][sandbox] Isolate network="public" sandboxes in per-sandbox netns via pasta - #65820
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces an experimental REST API service for Ray Sandbox, implemented as a FastAPI application on Ray Serve, allowing sandboxes to be managed externally. It also adds support for private network namespaces via pasta for the network="public" mode, enabling port isolation. Feedback focuses on improving robustness: failing fast during namespace holder startup, correctly parsing username:gid during user resolution, preventing a single broken sandbox from failing the list API, and adding timeouts to network downloads of runsc and pasta binaries.
Exposes ray.experimental.sandbox over a versioned REST API (/api/v1) served by Ray Serve, so sandboxes can be managed from outside the Ray cluster with nothing but an HTTP client and a bearer token — e.g. as an Anyscale service, or by agent-evaluation frameworks like Harbor. Design: - Each sandbox is a named, detached SandboxHost actor; the actors are the registry, so the Serve app is stateless and replicas can scale or restart without losing sandboxes. - Creation and execution are async submit + poll (with optional long-poll wait_seconds <= 30s) because image pulls and agent commands outlive HTTP requests and load-balancer limits. - The TTL reclaims both the sandbox and its hosting actor (the core runtime's TTL is deliberately disabled here so there is one owner). - Capabilities, network modes, DNS, shell, and workdir semantics are the core SandboxConfig's (ray-project#65570); the API validates network against VALID_NETWORK_MODES and defaults capabilities to DOCKER_DEFAULT_CAPABILITIES, patching nothing. - fastapi is only needed by this subpackage (ray[serve]); the base sandbox package never imports it. Testing: 54 unit tests run with no cluster and no runsc (fake runtime + fake actor resolver + FastAPI TestClient), including an OpenAPI contract snapshot; a runsc-gated integration test covers the real path. Validated end to end as a local 'serve run' and as an Anyscale service, driving real gVisor sandboxes. Signed-off-by: xyuzh <[email protected]>
POST /sandboxes now synthesizes its 202 response from the request instead of awaiting describe() on the new actor: on a saturated cluster the actor may be queued behind capacity for longer than a client (or load balancer) read timeout, and the endpoint has everything it needs to answer without touching the actor. Surfaced by a Harbor concurrency test that oversubscribed a single node. Signed-off-by: xyuzh <[email protected]>
A 16-way Terminal-Bench run against a cold cluster surfaced two capacity bugs: - The Serve deployment used the default max_ongoing_requests, but this API is long-poll based (requests deliberately hold a slot for up to ~30s), so a handful of concurrent clients saturated the replica and the platform load balancer answered 503 for everyone else. Raise it to 1000; the app is entirely async I/O. - Calls to a SandboxHost whose detached actor exists but has not been *scheduled* yet (cluster autoscaling) block indefinitely. Bound every actor call by the request's own long-poll budget plus a configurable scheduling grace: describe paths report a synthesized 'pending' instead of hanging, and exec/file paths return 409 with a retry hint. Signed-off-by: xyuzh <[email protected]>
An actor whose cpu/memory shape can never fit the cluster raises ActorUnschedulableError from any call; the app let it escape as an opaque 500. Terminal-Bench tasks declaring cpus=4/memory_mb=8192 on a cluster of 4CPU-16GB workers hit this for every large task. Map it to 409 'unschedulable' carrying Ray's own message, so clients see exactly which resource shape cannot be satisfied. Signed-off-by: xyuzh <[email protected]>
Proxies in front of a deployed service cap request bodies (an Anyscale ingress rejected a 4.8MB upload with 413 and killed an 11MB one mid-body), so single-request file uploads have a hidden size ceiling. PUT /files gains an append flag, plumbed through host, runtime, and backend (cat >> instead of cat >), so clients can chunk arbitrarily large uploads into proxy-sized pieces. Signed-off-by: xyuzh <[email protected]>
Match the style established in ray-project#65627 for the networking section: soft-wrapped prose, em-dash and semicolon clauses split into separate sentences, and bold list leads. Also document the new append flag on PUT /files and the 409 unschedulable error code. Signed-off-by: xyuzh <[email protected]>
… shared runsc cache, concurrent listing Three review findings: - A dead detached actor made its client_token permanently return 404; the idempotent-create path now clears the dead actor and creates a fresh sandbox under the same name. - The opt-in runsc download leaked a ~40MB temp dir per boot and raced concurrent boots; it now uses one shared cached path per node with an atomic rename. - GET /sandboxes described actors sequentially; it now gathers concurrently. Signed-off-by: xyuzh <[email protected]>
runsc exec takes numeric -user uid[:gid]; names are resolved against the image's own /etc/passwd host-side. Plumbed through runtime, the HTTP API (StartExecRequest.user), and the backend, with tests. Brings exec to parity with container engines' exec --user and the Harbor environment contract's user= parameter. Signed-off-by: xyuzh <[email protected]>
… via pasta Each public-mode sandbox now runs inside its own network namespace bridged by pasta (passt) user-mode networking: internet egress works, but ports and loopback are private — a bind on 0.0.0.0 cannot collide with the worker pod or other sandboxes, and nothing in the sandbox is reachable from outside it. This fulfills public's documented contract (egress without the host's network identity) and unblocks workloads that bind fixed ports, e.g. QEMU hostfwd tasks in Terminal-Bench. runsc still runs with --network=host; host is simply the private namespace. The mount namespace stays shared so runsc control sockets keep working. RAY_SANDBOX_PUBLIC_HOST_NETNS=1 on workers restores the previous shared-namespace behavior without a deploy; the auto_install_pasta server setting (default off) downloads a static pasta build on nodes that lack the passt package. Signed-off-by: xyuzh <[email protected]>
…ns via pasta Each public-mode sandbox gets a private user+network namespace pair, bridged by pasta (passt) user-mode networking in the rootless-Podman topology: a holder process pins the namespaces, pasta attaches from the pod side (so its uplink is the pod's real interface) and daemonizes, and runsc enters via nsenter as mapped root. Internet egress works, but ports and loopback are private — a bind on 0.0.0.0 cannot collide with the worker pod or other sandboxes, and nothing in the sandbox is reachable from outside it. This fulfills public's documented contract (egress without the host's network identity) and unblocks workloads that bind fixed ports, e.g. QEMU hostfwd tasks in Terminal-Bench. runsc still runs with --network=host — "host" is simply the private namespace — and without --rootless: it is already root in the holder's user namespace, and a nested user namespace would put the gofer's /proc/<pid>/root magic links out of reach. Mount and pid namespaces stay shared, so the bundle and the runsc control sockets keep working for pod-side state/exec/kill/delete. The host boot path creates /dev/net/tun (absent in fresh Kubernetes pods) via passwordless sudo. RAY_SANDBOX_PUBLIC_HOST_NETNS=1 on workers restores the previous shared-namespace behavior without a deploy; the auto_install_pasta server setting (default off) downloads a static pasta build on nodes without the passt package. Signed-off-by: xyuzh <[email protected]>
Cut the duplication and the over-long prose the netns tests picked up: - conftest: fold the runsc and pasta downloads into one _install_on_path helper; the two fixtures were the same twenty lines twice. - Share _public_config() and a _run_argv() argv builder instead of rebuilding a backend and config in every test. - Add a no_host_netns fixture for the repeated kill-switch delenv, and parametrize the non-public network modes so a failure names the mode. - Drop the real_which passthrough in the missing-pasta test: patch gvisor.shutil.which by path and return a stub for everything else. - Lift _pasta_pids and _host_ip to module scope, and trim the docstrings and comments to the claim each test actually makes. No coverage changes: same eight tests, same assertions. Signed-off-by: xyuzh <[email protected]>
8e48d3c to
1238fd1
Compare
…t the sandbox The pasta path parks each sandbox in an `unshare --user --net` holder and has pasta and a non-rootless runsc re-enter it via `nsenter -U -n`. Some sandboxed CI environments allow a single unprivileged user namespace (enough for the rootless sandbox tests) and even entering another process's, yet still deny the nested user namespace runsc opens when it drops the sandbox process to `nobody` -- surfacing only once the sandbox boots as `Started as root, will change to nobody. Couldn't open user namespace ...: Permission denied`. A namespace-entry probe passes in those environments and the tests then fail, so `ensure_pasta` instead brings a throwaway busybox `network="public"` sandbox all the way up and tears it down: only the real path exercises that nested open. runsc and pasta are installed before the probe runs. Signed-off-by: xyuzh <[email protected]>
1238fd1 to
04e7ef8
Compare
The sandbox HTTP API library (//python/ray/experimental/sandbox/http:sandbox_http_lib) depends on //python/ray/serve:serve_lib for the FastAPI/@serve.ingress app, but serve_lib's visibility did not include the sandbox http package. Bazel failed analysis with 'target //python/ray/serve:serve_lib is not visible', so the sandbox test job aborted the build even though the analyzed sandbox tests passed. Add the http package to serve_lib's visibility list. Signed-off-by: xyuzh <[email protected]>
The core sandbox test job builds with --install-mask all-ray-libraries, which removes python/ray/serve from the tree, so the //python/ray/serve:serve_lib bazel dep resolves to "no such package" and the runsc-gated integration test has no serve to import. app.py already imports serve lazily inside build_app, so the py_library needs no serve dep: drop it (and the now-moot visibility grant on serve/BUILD.bazel) and importorskip serve in the end-to-end test, which only runs in a full dev container where serve is installed. Signed-off-by: xyuzh <[email protected]>
Two failures surfaced once the core sandbox job started running these
tests (it installs with --install-mask all-ray-libraries):
- test_http_app: three tests drove TestClient with a bare client instead
of `with _client(...) as client:`, so each request ran on a fresh event
loop while the SandboxHost's asyncio.Events stayed bound to the first
one ("bound to a different event loop"). Wrap them like the others.
- test_http_integration: the mask leaves `ray.serve` importable but
without `serve.run`, so importorskip did not skip. Add a hasattr guard.
Signed-off-by: xyuzh <[email protected]>
|
@xyuzh Are you working on making this PR not depend on the http stuff and merging the backend first? |
| def _uses_pasta_netns(self, config: SandboxConfig) -> bool: | ||
| """Whether this sandbox gets a private network namespace via pasta.""" | ||
| return ( | ||
| config.network == "public" and os.environ.get(_PUBLIC_HOST_NETNS_ENV) != "1" |
There was a problem hiding this comment.
We should probably either remove the _PUBLIC_HOST_NETNS_ENV fallback, or at the very least log a big warning if that fallback is taken stating that this means the whole cluster network is accessible from within the sandbox.
There was a problem hiding this comment.
Removed in 81f4445. network="host" is the explicit shared-namespace mode, so the env kill switch was a second way to get the same thing without saying so; the missing-pasta error now just says to install passt.
|
|
||
| shutil.rmtree(root_dir, ignore_errors=True) | ||
|
|
||
| def _resolve_exec_user(self, user: str, image: str) -> str: |
There was a problem hiding this comment.
All the code related to the user handling like this function, the extra parameters and tests should be done in a separate PR.
…rootless cgroup behavior - Run pasta with --foreground in the shell's background instead of letting it daemonize. It stays in the process group that _terminate_tree kills, so the pidfile-based _kill_pasta and its PID-reuse hazard go away. The --pid file, written once pasta has initialised, now only gates the runsc start; a pasta that dies before then fails the create. - Force --ignore-cgroups when the pasta path drops --rootless, so a rootless config keeps tolerating cgroup permission failures instead of having runsc configure cgroups as mapped root. - Drop the RAY_SANDBOX_PUBLIC_HOST_NETNS kill switch; network="host" is the explicit shared-namespace mode. - Move per-exec `user` and `write_file(append=)` out of this PR. - Docs: keep `none` as the recommendation for untrusted code and call out that `public` sandboxes can still reach every address the node can reach, including other Ray nodes and internal services.
…nstead of pasta (#66004) ## Description pasta has a design flaw for our topology. It preserves the UDP source port on the host side of every flow (`fwd_nat_from_tap`: "for UDP we preserve the source port") and sets `SO_REUSEADDR` on every socket (`sock_l4_`). With one pasta per sandbox sharing the worker's network namespace, two sandboxes sending UDP from the same source port to the same server end up with two connected host sockets on an identical 4-tuple, and the kernel hands one sandbox's replies to the other. Reproduced against the merged #65820 wrapper with two `public` sandboxes and an echo server outside the pod: | Case | Sandbox A received | Sandbox B received | | --- | --- | --- | | Same source port 5000 | 1 own, 0 foreign | 21 own, **23 of A's replies** | | Distinct source ports | 24 own, 0 foreign | 24 own, 0 foreign | Fixed-port UDP clients talking to a shared service (a DNS resolver, NTP on 123, STUN, game or QEMU forwarders) hit this; TCP is unaffected because pasta lets the kernel pick TCP source ports. A two-line pasta patch (kernel-picked UDP source ports) fixes it, verified locally, and will be sent upstream, but we can't rely on nodes carrying it. This PR switches the bridge to **slirp4netns**, which NATs every flow through a fresh, kernel-assigned host port, so flows from different sandboxes can never share a host socket. The topology is unchanged: the `unshare --user --net` holder pins the namespaces, slirp4netns attaches from the pod side and runs in the foreground inside the sandbox's process group, runsc enters via `nsenter` as mapped root. - `--ready-fd` gives a real readiness signal and replaces the pidfile polling. - `--disable-host-loopback` and `--disable-dns` keep the pod's loopback and resolver out of reach; the sandbox sees only the generated `resolv.conf`. - `--enable-seccomp` filters the relay's syscalls. `--enable-sandbox` is not used: its `setegid(0)` fails inside a `--map-root-user` namespace. - Sandboxes get `198.18.0.100` behind NAT instead of a copy of the pod's address. The tap uses `--cidr=198.18.0.0/24` (RFC 2544 benchmarking space) rather than slirp4netns's default `10.0.2.0/24`, which would be on-link in the sandbox and shadow pod or service ranges that use it. - Static builds exist for x86_64 and aarch64, so the arm64 caveat in the docs goes away. Unchanged: `public` still reaches whatever the pod can reach on the network; the egress filter remains a follow-up. The docs, the KubeRay example, and the config docstring are updated. ## Related issues Follow-up to #65820. ## Additional information Runtime tests in a privileged `rayproject/ray:nightly-py312` container on arm64 (slirp4netns 1.3.5 static, runsc release-20260817), `TEST_SANDBOX=1`: the existing netns suite (concurrent same-port binds and isolation, egress and DNS, teardown reaps slirp4netns, failed create leaves nothing behind) plus the new `test_netns_udp_flows_do_not_cross`, which drives two sandboxes from UDP source port 5000 against one resolver with distinct query names and asserts neither receives the other's answers. All pass; the same test fails against pasta. Argv-level unit tests pin the slirp4netns flag list and the readiness gate. --------- Signed-off-by: xyuzh <[email protected]>
…nstead of pasta (ray-project#66004) ## Description pasta has a design flaw for our topology. It preserves the UDP source port on the host side of every flow (`fwd_nat_from_tap`: "for UDP we preserve the source port") and sets `SO_REUSEADDR` on every socket (`sock_l4_`). With one pasta per sandbox sharing the worker's network namespace, two sandboxes sending UDP from the same source port to the same server end up with two connected host sockets on an identical 4-tuple, and the kernel hands one sandbox's replies to the other. Reproduced against the merged ray-project#65820 wrapper with two `public` sandboxes and an echo server outside the pod: | Case | Sandbox A received | Sandbox B received | | --- | --- | --- | | Same source port 5000 | 1 own, 0 foreign | 21 own, **23 of A's replies** | | Distinct source ports | 24 own, 0 foreign | 24 own, 0 foreign | Fixed-port UDP clients talking to a shared service (a DNS resolver, NTP on 123, STUN, game or QEMU forwarders) hit this; TCP is unaffected because pasta lets the kernel pick TCP source ports. A two-line pasta patch (kernel-picked UDP source ports) fixes it, verified locally, and will be sent upstream, but we can't rely on nodes carrying it. This PR switches the bridge to **slirp4netns**, which NATs every flow through a fresh, kernel-assigned host port, so flows from different sandboxes can never share a host socket. The topology is unchanged: the `unshare --user --net` holder pins the namespaces, slirp4netns attaches from the pod side and runs in the foreground inside the sandbox's process group, runsc enters via `nsenter` as mapped root. - `--ready-fd` gives a real readiness signal and replaces the pidfile polling. - `--disable-host-loopback` and `--disable-dns` keep the pod's loopback and resolver out of reach; the sandbox sees only the generated `resolv.conf`. - `--enable-seccomp` filters the relay's syscalls. `--enable-sandbox` is not used: its `setegid(0)` fails inside a `--map-root-user` namespace. - Sandboxes get `198.18.0.100` behind NAT instead of a copy of the pod's address. The tap uses `--cidr=198.18.0.0/24` (RFC 2544 benchmarking space) rather than slirp4netns's default `10.0.2.0/24`, which would be on-link in the sandbox and shadow pod or service ranges that use it. - Static builds exist for x86_64 and aarch64, so the arm64 caveat in the docs goes away. Unchanged: `public` still reaches whatever the pod can reach on the network; the egress filter remains a follow-up. The docs, the KubeRay example, and the config docstring are updated. ## Related issues Follow-up to ray-project#65820. ## Additional information Runtime tests in a privileged `rayproject/ray:nightly-py312` container on arm64 (slirp4netns 1.3.5 static, runsc release-20260817), `TEST_SANDBOX=1`: the existing netns suite (concurrent same-port binds and isolation, egress and DNS, teardown reaps slirp4netns, failed create leaves nothing behind) plus the new `test_netns_udp_flows_do_not_cross`, which drives two sandboxes from UDP source port 5000 against one resolver with distinct query names and asserts neither receives the other's answers. All pass; the same test fails against pasta. Argv-level unit tests pin the slirp4netns flag list and the readiness gate. --------- Signed-off-by: xyuzh <[email protected]>
## 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 (#65942) ## Description Two small additions to the gVisor backend and `SandboxRuntime`, split out of #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 #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 (#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_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]>
…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]>
…nstead of pasta (ray-project#66004) ## Description pasta has a design flaw for our topology. It preserves the UDP source port on the host side of every flow (`fwd_nat_from_tap`: "for UDP we preserve the source port") and sets `SO_REUSEADDR` on every socket (`sock_l4_`). With one pasta per sandbox sharing the worker's network namespace, two sandboxes sending UDP from the same source port to the same server end up with two connected host sockets on an identical 4-tuple, and the kernel hands one sandbox's replies to the other. Reproduced against the merged ray-project#65820 wrapper with two `public` sandboxes and an echo server outside the pod: | Case | Sandbox A received | Sandbox B received | | --- | --- | --- | | Same source port 5000 | 1 own, 0 foreign | 21 own, **23 of A's replies** | | Distinct source ports | 24 own, 0 foreign | 24 own, 0 foreign | Fixed-port UDP clients talking to a shared service (a DNS resolver, NTP on 123, STUN, game or QEMU forwarders) hit this; TCP is unaffected because pasta lets the kernel pick TCP source ports. A two-line pasta patch (kernel-picked UDP source ports) fixes it, verified locally, and will be sent upstream, but we can't rely on nodes carrying it. This PR switches the bridge to **slirp4netns**, which NATs every flow through a fresh, kernel-assigned host port, so flows from different sandboxes can never share a host socket. The topology is unchanged: the `unshare --user --net` holder pins the namespaces, slirp4netns attaches from the pod side and runs in the foreground inside the sandbox's process group, runsc enters via `nsenter` as mapped root. - `--ready-fd` gives a real readiness signal and replaces the pidfile polling. - `--disable-host-loopback` and `--disable-dns` keep the pod's loopback and resolver out of reach; the sandbox sees only the generated `resolv.conf`. - `--enable-seccomp` filters the relay's syscalls. `--enable-sandbox` is not used: its `setegid(0)` fails inside a `--map-root-user` namespace. - Sandboxes get `198.18.0.100` behind NAT instead of a copy of the pod's address. The tap uses `--cidr=198.18.0.0/24` (RFC 2544 benchmarking space) rather than slirp4netns's default `10.0.2.0/24`, which would be on-link in the sandbox and shadow pod or service ranges that use it. - Static builds exist for x86_64 and aarch64, so the arm64 caveat in the docs goes away. Unchanged: `public` still reaches whatever the pod can reach on the network; the egress filter remains a follow-up. The docs, the KubeRay example, and the config docstring are updated. ## Related issues Follow-up to ray-project#65820. ## Additional information Runtime tests in a privileged `rayproject/ray:nightly-py312` container on arm64 (slirp4netns 1.3.5 static, runsc release-20260817), `TEST_SANDBOX=1`: the existing netns suite (concurrent same-port binds and isolation, egress and DNS, teardown reaps slirp4netns, failed create leaves nothing behind) plus the new `test_netns_udp_flows_do_not_cross`, which drives two sandboxes from UDP source port 5000 against one resolver with distinct query names and asserts neither receives the other's answers. All pass; the same test fails against pasta. Argv-level unit tests pin the slirp4netns flag list and the readiness gate. --------- 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]>
…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]>
…nstead of pasta (ray-project#66004) ## Description pasta has a design flaw for our topology. It preserves the UDP source port on the host side of every flow (`fwd_nat_from_tap`: "for UDP we preserve the source port") and sets `SO_REUSEADDR` on every socket (`sock_l4_`). With one pasta per sandbox sharing the worker's network namespace, two sandboxes sending UDP from the same source port to the same server end up with two connected host sockets on an identical 4-tuple, and the kernel hands one sandbox's replies to the other. Reproduced against the merged ray-project#65820 wrapper with two `public` sandboxes and an echo server outside the pod: | Case | Sandbox A received | Sandbox B received | | --- | --- | --- | | Same source port 5000 | 1 own, 0 foreign | 21 own, **23 of A's replies** | | Distinct source ports | 24 own, 0 foreign | 24 own, 0 foreign | Fixed-port UDP clients talking to a shared service (a DNS resolver, NTP on 123, STUN, game or QEMU forwarders) hit this; TCP is unaffected because pasta lets the kernel pick TCP source ports. A two-line pasta patch (kernel-picked UDP source ports) fixes it, verified locally, and will be sent upstream, but we can't rely on nodes carrying it. This PR switches the bridge to **slirp4netns**, which NATs every flow through a fresh, kernel-assigned host port, so flows from different sandboxes can never share a host socket. The topology is unchanged: the `unshare --user --net` holder pins the namespaces, slirp4netns attaches from the pod side and runs in the foreground inside the sandbox's process group, runsc enters via `nsenter` as mapped root. - `--ready-fd` gives a real readiness signal and replaces the pidfile polling. - `--disable-host-loopback` and `--disable-dns` keep the pod's loopback and resolver out of reach; the sandbox sees only the generated `resolv.conf`. - `--enable-seccomp` filters the relay's syscalls. `--enable-sandbox` is not used: its `setegid(0)` fails inside a `--map-root-user` namespace. - Sandboxes get `198.18.0.100` behind NAT instead of a copy of the pod's address. The tap uses `--cidr=198.18.0.0/24` (RFC 2544 benchmarking space) rather than slirp4netns's default `10.0.2.0/24`, which would be on-link in the sandbox and shadow pod or service ranges that use it. - Static builds exist for x86_64 and aarch64, so the arm64 caveat in the docs goes away. Unchanged: `public` still reaches whatever the pod can reach on the network; the egress filter remains a follow-up. The docs, the KubeRay example, and the config docstring are updated. ## Related issues Follow-up to ray-project#65820. ## Additional information Runtime tests in a privileged `rayproject/ray:nightly-py312` container on arm64 (slirp4netns 1.3.5 static, runsc release-20260817), `TEST_SANDBOX=1`: the existing netns suite (concurrent same-port binds and isolation, egress and DNS, teardown reaps slirp4netns, failed create leaves nothing behind) plus the new `test_netns_udp_flows_do_not_cross`, which drives two sandboxes from UDP source port 5000 against one resolver with distinct query names and asserts neither receives the other's answers. All pass; the same test fails against pasta. Argv-level unit tests pin the slirp4netns flag list and the readiness gate. --------- 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]>
## Description This PR adds GPU support to Ray Sandboxes by leveraging [CDI](https://github.com/cncf-tags/container-device-interface) (Container Device Interface) to inject GPU device nodes and their supported user-mode driver files into a gVisor sandbox at runtime. This PR builds on #66470, which adds the overlayfs rootfs that GPU sandboxes boot from, and on #66469 and #66528 underneath it. Only the last five commits are new here. The change is implemented as follows. - **Generic CDI framework**: We added a vendor-agnostic CDI module that can be used to parse CDI specs and merge devices from them with a standard OCI image spec. The implementation of this module is kept free of any Ray imports so it stays a candidate for extraction into a standalone library at some point in the future. As part of this, the`AcceleratorManager` class gains two new optional methods, `get_cdi_kind()`/`generate_cdi_spec()`. These methods are implemented by an `AcceleratorManager` to both generate a spec with the full set of CDI devices associated with the accelerator, as well as advertise what kind of CDI devices are associated with it (e.g. `nvidia.com/gpu`). - **NVIDIA specific implementation** : We extended the `NvidiaGPUAcceleratorManager` to be CDI aware and implement the `get_cdi_kind()`/`generate_cdi_spec()` methods mentioned above. At present, we generate CDI devices by shelling out to `nvidia-ctk cdi generate`, but the preferred long-term path is to build (or leverage) a canonical python library for CDI maintained upstream. Since gVisor only supports NVIDIA GPUs at the moment, the `GVisorSandboxBackend` gates GPU passthrough to CDI kinds it actually supports (i.e. `nvidia.com/gpu`), rejecting anything else rather than attempting unverified passthrough. - **`num_gpus` and `gpu_ids`**: When creating a `Sandbox` actor, you can now pass a `num_gpus` field in addition to the existing `cpu` and `memory` fields (similar to what is possible when creating a non-sandboxed actor). When doing so, the sandbox auto-inherits the full Ray GPU assignment derived from `num_gpus` (with no way to limit it further when calling `remote()` later on, unlike for cpus and memory). When creating a sandbox via `SandboxRuntime.create()` (i.e. within a pre-existing actor), there is no `num_gpus` field supported. Instead, we allow passing a `gpu_ids` field as an explicit parameter to specify which of the GPUs that have been granted to the surrounding actor should be isolated inside the sandbox. This allows a single actor with multiple GPUs to manage several sandboxes, each pinned to a different GPU. - **Overlayfs rootfs for GPU sandboxes**: NVIDIA's CDI spec relies on `createContainer` hooks that create library symlinks and update the ldcache in the sandbox's rootfs, and runsc creates mount points there for the driver files and device nodes. The default EROFS rootfs is read-only and shared by every sandbox of an image, so any sandbox with `gpu_ids` now runs on #66470's overlayfs rootfs. These writes land in the sandbox's own upper layer, and the cached image stays untouched. - **53 new unit tests and 9 real-GPU CI tests**: We added `test_cdi.py` and `test_cdi_lib.py` under `ray/experimental/sandbox/tests/`, and extended the existing suites there and under `ray/tests/accelerators/`. The real-GPU tests run via two new Buildkite jobs (`core: sandbox gpu tests`, 1 GPU; `core: sandbox multi gpu tests`, 4 GPUs). Validated end-to-end on an NVIDIA L4 GPU and a machine with 4 NVIDIA A100 GPUs. We also tested on a machine with 4 NVIDIA GB200 GPUs (ARM64/Grace CPU). All of the NVML-based tests passed, but the CUDA tests failed (because gVisor does not yet fully support GB200). Once gVisor supports GB200 we will need to revisit things to ensure that multi-node NVLink is properly supported as well. ## AI assistance Developed with Claude Code (Sonnet 5), including driving the hardware validation above. I reviewed every changed line and take responsibility for the change end-to-end. ## Related issues No tracking issue. Sibling of other active sandbox work: image cache LRU eviction (#65748), per-sandbox netns (#65820), HTTP API (#65633), gRPC facade (#65839), multi-uid netns (#65823); none overlap with this change. ## Duplicate check Searched open/closed issues and PRs for `sandbox gpu`, `CDI`, `gvisor`, `nvproxy`, `nvidia-ctk`, and `container device interface` — nothing addresses GPU or CDI support for Ray Sandboxes. ## Testing - `test_gvisor_gpu.py` (real `nvidia-ctk` generation, device injection, `--nvproxy` boot, `nvidia-smi` inside the sandbox, and a real CUDA kernel launch via NVIDIA's `vectorAdd` sample) — passes on a machine with an NVIDIA L4 GPU and a machine with 4 A100 GPUs. - `test_gvisor_multi_gpu.py` (all four tests, needing 4 GPUs) — only relies on NVML to test. Passes on both a machine with 4 A100 GPUs and a machine with 4 GB200 GPUs, each sandbox pinned to a distinct GPU. - `python/ray/experimental/sandbox/tests/` (full directory, including the above) — on the L4: 228 passed, 10 skipped. On the GB200 machine, as root: 283 passed, 3 failed, 1 skipped. As the non-root user `ray`: 269 passed, 3 failed, 15 skipped. The failures are the known CUDA failure (`test_sandbox_gpu_cuda_vectoradd_runs_a_real_kernel`, see above) and `test_netns_egress_and_dns` and `test_netns_udp_flows_do_not_cross`, which need public DNS that this machine's network doesn't provide. The skipped tests need a worker that can mount in the host's user namespace, which `ray` can't in this Docker test rig, or the CI sandbox job. - `pre-commit run` — passed (`SKIP=vale`; its Go/cgo toolchain doesn't build in this environment). ### Testing manually Building the published `ray` image needs a wheel via `./build-wheel.sh`, which needs Anyscale's internal `cr.ray.io`/Bazel-remote-cache access to build in reasonable time. To avoid long build times, we instead overlay this branch's changed `.py` files onto a stock published `rayproject/ray:2.58.0` image, allowing us to test without a core rebuild since nothing outside pure Python changed. These tests require a machine with an NVIDIA GPU, Docker, and the `nvidia-container-toolkit-base` package installed. Dockerfile: https://gist.github.com/klueska/9f1297a5d7f5a7b7cf9b31b3fb393feb Save it locally, then build from a checkout of this branch (the repo itself is the build context): ```bash cd ray curl -fsSL -o Dockerfile.sandbox-gpu-test https://gist.githubusercontent.com/klueska/9f1297a5d7f5a7b7cf9b31b3fb393feb/raw docker build -t ray-cdi-gpu-test:latest -f Dockerfile.sandbox-gpu-test . ``` Run it. Each test runs twice, once as root and once as the non-root user `ray`. `--device nvidia.com/gpu=all` for GPU access; `--privileged` is needed for gVisor in this specific nested-Docker test rig. `--basetemp` keeps pytest's temporary directories out of `/tmp`, which `test_image_utils.py::test_seeding_stays_inside_the_tree` requires: ```bash # Pure-logic CDI tests + real-nvidia-ctk accelerator tests, no gVisor/root needed: docker run --rm --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_cdi.py \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_cdi_lib.py \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/tests/accelerators/test_nvidia_gpu.py # The real end-to-end GPU sandbox test: exercises real nvidia-ctk generation, device injection, # and gVisor --nvproxy passthrough. No host setup needed -- nvidia-persistenced can be running # or not, both are handled. # The two commands below run these tests as root and as the non-root user ray. docker run --rm --privileged --user root --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_gpu.py docker run --rm --privileged --user ray --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_gpu.py # The four 4-GPU tests: three check that concurrent sandboxes each get a distinct GPU (separate # Sandbox actors, SandboxRuntime.create, and one actor pinning each of its sandboxes via # gpu_ids=...), and one checks that a single sandbox given 2 GPUs sees both. # Needs a machine with 4 GPUs; `--device nvidia.com/gpu=all` must expose at least 4. # The two commands below run these tests as root and as the non-root user ray. docker run --rm --privileged --user root --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_multi_gpu.py docker run --rm --privileged --user ray --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_multi_gpu.py # Full sandbox suite (mocked-GPU config/scheduling tests + real-gVisor CPU and GPU tests): # The two commands below run these tests as root and as the non-root user ray. docker run --rm --privileged --user root --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/ docker run --rm --privileged --user ray --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/ ``` --------- Signed-off-by: Kevin Klues <[email protected]> Signed-off-by: Philipp Moritz <[email protected]> Co-authored-by: Philipp Moritz <[email protected]>
…#65898) ## Description This PR adds GPU support to Ray Sandboxes by leveraging [CDI](https://github.com/cncf-tags/container-device-interface) (Container Device Interface) to inject GPU device nodes and their supported user-mode driver files into a gVisor sandbox at runtime. This PR builds on ray-project#66470, which adds the overlayfs rootfs that GPU sandboxes boot from, and on ray-project#66469 and ray-project#66528 underneath it. Only the last five commits are new here. The change is implemented as follows. - **Generic CDI framework**: We added a vendor-agnostic CDI module that can be used to parse CDI specs and merge devices from them with a standard OCI image spec. The implementation of this module is kept free of any Ray imports so it stays a candidate for extraction into a standalone library at some point in the future. As part of this, the`AcceleratorManager` class gains two new optional methods, `get_cdi_kind()`/`generate_cdi_spec()`. These methods are implemented by an `AcceleratorManager` to both generate a spec with the full set of CDI devices associated with the accelerator, as well as advertise what kind of CDI devices are associated with it (e.g. `nvidia.com/gpu`). - **NVIDIA specific implementation** : We extended the `NvidiaGPUAcceleratorManager` to be CDI aware and implement the `get_cdi_kind()`/`generate_cdi_spec()` methods mentioned above. At present, we generate CDI devices by shelling out to `nvidia-ctk cdi generate`, but the preferred long-term path is to build (or leverage) a canonical python library for CDI maintained upstream. Since gVisor only supports NVIDIA GPUs at the moment, the `GVisorSandboxBackend` gates GPU passthrough to CDI kinds it actually supports (i.e. `nvidia.com/gpu`), rejecting anything else rather than attempting unverified passthrough. - **`num_gpus` and `gpu_ids`**: When creating a `Sandbox` actor, you can now pass a `num_gpus` field in addition to the existing `cpu` and `memory` fields (similar to what is possible when creating a non-sandboxed actor). When doing so, the sandbox auto-inherits the full Ray GPU assignment derived from `num_gpus` (with no way to limit it further when calling `remote()` later on, unlike for cpus and memory). When creating a sandbox via `SandboxRuntime.create()` (i.e. within a pre-existing actor), there is no `num_gpus` field supported. Instead, we allow passing a `gpu_ids` field as an explicit parameter to specify which of the GPUs that have been granted to the surrounding actor should be isolated inside the sandbox. This allows a single actor with multiple GPUs to manage several sandboxes, each pinned to a different GPU. - **Overlayfs rootfs for GPU sandboxes**: NVIDIA's CDI spec relies on `createContainer` hooks that create library symlinks and update the ldcache in the sandbox's rootfs, and runsc creates mount points there for the driver files and device nodes. The default EROFS rootfs is read-only and shared by every sandbox of an image, so any sandbox with `gpu_ids` now runs on ray-project#66470's overlayfs rootfs. These writes land in the sandbox's own upper layer, and the cached image stays untouched. - **53 new unit tests and 9 real-GPU CI tests**: We added `test_cdi.py` and `test_cdi_lib.py` under `ray/experimental/sandbox/tests/`, and extended the existing suites there and under `ray/tests/accelerators/`. The real-GPU tests run via two new Buildkite jobs (`core: sandbox gpu tests`, 1 GPU; `core: sandbox multi gpu tests`, 4 GPUs). Validated end-to-end on an NVIDIA L4 GPU and a machine with 4 NVIDIA A100 GPUs. We also tested on a machine with 4 NVIDIA GB200 GPUs (ARM64/Grace CPU). All of the NVML-based tests passed, but the CUDA tests failed (because gVisor does not yet fully support GB200). Once gVisor supports GB200 we will need to revisit things to ensure that multi-node NVLink is properly supported as well. ## AI assistance Developed with Claude Code (Sonnet 5), including driving the hardware validation above. I reviewed every changed line and take responsibility for the change end-to-end. ## Related issues No tracking issue. Sibling of other active sandbox work: image cache LRU eviction (ray-project#65748), per-sandbox netns (ray-project#65820), HTTP API (ray-project#65633), gRPC facade (ray-project#65839), multi-uid netns (ray-project#65823); none overlap with this change. ## Duplicate check Searched open/closed issues and PRs for `sandbox gpu`, `CDI`, `gvisor`, `nvproxy`, `nvidia-ctk`, and `container device interface` — nothing addresses GPU or CDI support for Ray Sandboxes. ## Testing - `test_gvisor_gpu.py` (real `nvidia-ctk` generation, device injection, `--nvproxy` boot, `nvidia-smi` inside the sandbox, and a real CUDA kernel launch via NVIDIA's `vectorAdd` sample) — passes on a machine with an NVIDIA L4 GPU and a machine with 4 A100 GPUs. - `test_gvisor_multi_gpu.py` (all four tests, needing 4 GPUs) — only relies on NVML to test. Passes on both a machine with 4 A100 GPUs and a machine with 4 GB200 GPUs, each sandbox pinned to a distinct GPU. - `python/ray/experimental/sandbox/tests/` (full directory, including the above) — on the L4: 228 passed, 10 skipped. On the GB200 machine, as root: 283 passed, 3 failed, 1 skipped. As the non-root user `ray`: 269 passed, 3 failed, 15 skipped. The failures are the known CUDA failure (`test_sandbox_gpu_cuda_vectoradd_runs_a_real_kernel`, see above) and `test_netns_egress_and_dns` and `test_netns_udp_flows_do_not_cross`, which need public DNS that this machine's network doesn't provide. The skipped tests need a worker that can mount in the host's user namespace, which `ray` can't in this Docker test rig, or the CI sandbox job. - `pre-commit run` — passed (`SKIP=vale`; its Go/cgo toolchain doesn't build in this environment). ### Testing manually Building the published `ray` image needs a wheel via `./build-wheel.sh`, which needs Anyscale's internal `cr.ray.io`/Bazel-remote-cache access to build in reasonable time. To avoid long build times, we instead overlay this branch's changed `.py` files onto a stock published `rayproject/ray:2.58.0` image, allowing us to test without a core rebuild since nothing outside pure Python changed. These tests require a machine with an NVIDIA GPU, Docker, and the `nvidia-container-toolkit-base` package installed. Dockerfile: https://gist.github.com/klueska/9f1297a5d7f5a7b7cf9b31b3fb393feb Save it locally, then build from a checkout of this branch (the repo itself is the build context): ```bash cd ray curl -fsSL -o Dockerfile.sandbox-gpu-test https://gist.githubusercontent.com/klueska/9f1297a5d7f5a7b7cf9b31b3fb393feb/raw docker build -t ray-cdi-gpu-test:latest -f Dockerfile.sandbox-gpu-test . ``` Run it. Each test runs twice, once as root and once as the non-root user `ray`. `--device nvidia.com/gpu=all` for GPU access; `--privileged` is needed for gVisor in this specific nested-Docker test rig. `--basetemp` keeps pytest's temporary directories out of `/tmp`, which `test_image_utils.py::test_seeding_stays_inside_the_tree` requires: ```bash # Pure-logic CDI tests + real-nvidia-ctk accelerator tests, no gVisor/root needed: docker run --rm --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_cdi.py \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_cdi_lib.py \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/tests/accelerators/test_nvidia_gpu.py # The real end-to-end GPU sandbox test: exercises real nvidia-ctk generation, device injection, # and gVisor --nvproxy passthrough. No host setup needed -- nvidia-persistenced can be running # or not, both are handled. # The two commands below run these tests as root and as the non-root user ray. docker run --rm --privileged --user root --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_gpu.py docker run --rm --privileged --user ray --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_gpu.py # The four 4-GPU tests: three check that concurrent sandboxes each get a distinct GPU (separate # Sandbox actors, SandboxRuntime.create, and one actor pinning each of its sandboxes via # gpu_ids=...), and one checks that a single sandbox given 2 GPUs sees both. # Needs a machine with 4 GPUs; `--device nvidia.com/gpu=all` must expose at least 4. # The two commands below run these tests as root and as the non-root user ray. docker run --rm --privileged --user root --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_multi_gpu.py docker run --rm --privileged --user ray --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_multi_gpu.py # Full sandbox suite (mocked-GPU config/scheduling tests + real-gVisor CPU and GPU tests): # The two commands below run these tests as root and as the non-root user ray. docker run --rm --privileged --user root --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/ docker run --rm --privileged --user ray --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \ python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \ /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/ ``` --------- Signed-off-by: Kevin Klues <[email protected]> Signed-off-by: Philipp Moritz <[email protected]> Co-authored-by: Philipp Moritz <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Cherry-picked-from: c46d1e6 Co-authored-by: Copilot <[email protected]> Copilot-Session: 0baa3cf-af4e-472e-ad89-8f02c6e8be11
Description
network="public"sandboxes currently run with runsc--network=hostin 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 withhostfwd=tcp::2222-:22and then SSH tolocalhost:2222from inside the same sandbox. Under co-tenancy the second bind getsEADDRINUSE, and a verifier can connect to a different sandbox's guest.This PR gives each
publicsandbox a private user+network namespace pair bridged by pasta (passt) user-mode networking, the rootless-Podman topology:unshare --user --map-root-user --net) pins the namespaces for the sandbox's lifetime;pastaattaches from the pod side (--netns/--userns /proc/$PID/ns/*) and runs in the foreground inside the sandbox's process group, so teardown'skillpgtakes it with the rest of the tree.-t/-u/-T/-U none --no-map-gwmake 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 runexecutes inside viansenteras mapped root.--rootlessis dropped because nesting a second userns breaks the gofer's/procmagic-link derefs; since rootless mode is also what tolerated cgroup permission failures, the wrapper forces--ignore-cgroupsfor 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--rootkeep working for pod-sidestate/exec/kill/delete.What
publicdoes and does not isolatepublicisolates 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 apublicsandbox 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 keepnoneas the recommendation for untrusted code. Closing that gap needs egress policy outside pasta: a node-level netfilter rule set (which needsCAP_NET_ADMINin 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 fixed0 <uid> 1map inside new user, net, pid, mount, ipc, and uts namespaces. runsc boots fine, but the pod side loses control of it:runsc execfails withwaiting on pid 2: sandbox is not runningbecause the state file records the inner pid, andrunsc statesilently reportsrunningwhenever some unrelated pod process happens to have that pid. Every control call would have to be wrapped innsenter -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 extrasleepprocess.Requires
pastaandnsenteron nodes forpublicsandboxes. Docs updated (requirements, mode table with a warning admonition, install snippets, troubleshooting). Per-execuserandwrite_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=1in a privilegedrayproject/ray:nightly-py312container on arm64 as the non-rootrayuser, with pasta built from source: two concurrentpublicsandboxes both bind0.0.0.0:2222and each reaches its own listener on127.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_sandboxand 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-cgroupsare pinned by argv-level unit tests that run without runsc or pasta.