Repository navigation
[core][sandbox] Boot sandboxes from an overlayfs rootfs if required - #66470
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces support for an overlayfs root filesystem type in Ray's sandbox environment, allowing sandboxes to boot from a kernel overlay over unpacked image trees. Key additions include a new overlayfs.py module for managing mounts, EROFS image unpacking utilities in image_utils.py, and integration within the gVisor backend and sandbox configuration. The review feedback identifies critical missing imports (uuid in image_utils.py and json in gvisor.py) that would cause runtime errors, and suggests adding timeouts to subprocess.run calls in overlayfs.py to prevent potential indefinite hangs during initialization.
87d265f to
c53cdbc
Compare
c53cdbc to
9e57e70
Compare
310136e to
dd08549
Compare
74beb3a to
7a34a85
Compare
7a34a85 to
8929f37
Compare
7eccf7f to
a622f25
Compare
53ec2ea to
d5bb500
Compare
420488f to
4d08140
Compare
| rootfs_overlay is not None | ||
| and rootfs_overlay.userns is overlayfs.UserNamespaceType.PRIVATE | ||
| ) | ||
| create_userns_with_netns = config.network == "public" and rootfs_overlay is None |
There was a problem hiding this comment.
On a worker with mount privileges, an overlay public sandbox no longer gets its own user namespace. Both create_userns_* flags are False here, so the holder runs unshare --net alone, and slirp4netns's tap setup and nft -f then need CAP_NET_ADMIN in the worker's user namespace.
A root pod with SYS_ADMIN added but not NET_ADMIN (and no AppArmor, so the mount probe passes) can no longer start readonly=True, workdir=..., network="public", which works on master. Once #65898 lands, the same goes for any GPU sandbox with network="public". The comment at line 113 and sandboxes.md:694 still say the pod doesn't need CAP_NET_ADMIN. Could HOST mode check for it on public sandboxes and use a private user namespace otherwise, or the docs state the requirement?
There was a problem hiding this comment.
Reproduced as root with SYS_ADMIN but without NET_ADMIN. slirp4netns failed with:
ioctl(TUNSETIFF): Operation not permitted
For EROFS sandboxes, the public script already creates a user namespace that owns the sandbox's network namespace. It now does the same for overlayfs sandboxes mounted in the host's user namespace.
This works with and without CAP_NET_ADMIN, so the docs' "the worker Pod doesn't need CAP_NET_ADMIN" still holds.
| # the same time race, and all but one fail. flock on the image | ||
| # makes them take turns. | ||
| mount_image = [ | ||
| 'flock "$image" mount -t erofs -o ro,loop "$image" "$tmpfs/lower"' |
There was a problem hiding this comment.
KERNEL vs FUSE is probed once per process, and after that a single sandbox has no fallback. If mount -o loop fails later, for example in a privileged container that only has the /dev/loopN nodes it started with and more distinct images in use than free nodes, the sandbox fails with "rootfs overlay mount failed" though erofsfuse would have worked. sandboxes.md:178 says Ray falls back to erofsfuse. Something like flock ... mount ... || { <erofsfuse steps>; } here would match that.
There was a problem hiding this comment.
Agreed, done. The kernel mount step is now flock … mount -t erofs -o ro,loop … || { <erofsfuse steps>; }, so a loop mount that fails for one sandbox, such as when no loop device is free, falls back to erofsfuse for that sandbox, as the docs say.
7b54f0a to
a19c84c
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
Reviewed by Cursor Bugbot for commit a19c84c. Configure here.
Previously, every sandbox booted from its image's cached EROFS image, which gVisor mounts read-only inside the Sentry. Nothing on the host can prepare that root filesystem before the sandbox starts, and runsc can't create mount points in it for a read-only root. In this commit, a sandbox can instead boot from a kernel overlay private to the sandbox, mounted in a new mount namespace created for the sandbox. Whether it does is decided from its final OCI spec, after any transform of that spec has run. The overlay's read-only lower layer is the cached EROFS image itself, mounted in that namespace, and its upper layer sits on a small tmpfs. Host-side writes to the rootfs, such as those from OCI hooks and the mount points runsc creates, land in that upper layer, so they never modify the cached image or reach another sandbox. Writes made inside a writable sandbox still go to a gVisor overlay, as they do for an EROFS sandbox. Files in the overlay keep their owners from the image whenever the worker can map them. A worker running as root maps every id to itself. Only a worker running as any other user, with neither mount privileges nor subordinate ids, falls back to mapping root alone. When this happens, files owned by root keep their owner, and every other file shows up as owned by nobody. Note that this commit doesn't add any conditions yet for when a sandbox needs an overlay, so every sandbox still boots from its EROFS image. A subsequent commit decides from the spec when a sandbox needs one, such as when it has OCI hooks that run before it starts, or a read-only root with mounts that need new mount points. That sets up GPU sandboxes, whose CDI specs add both hooks and mounts, to run without modifying the cached image. Signed-off-by: Kevin Klues <[email protected]>
…d one Previously, no sandbox used the overlayfs rootfs. OCI hooks that run on the host before a sandbox starts had nowhere to write that keeps the cached image untouched. A readonly sandbox whose mounts need mount points the image lacks would fail to start, since runsc can't create them in a read-only EROFS image. The one such mount Ray adds itself, an explicit workdir, got around this by quietly making the rootfs writable, with its writes discarded along with the sandbox. In this commit, a sandbox boots from an overlayfs rootfs when its final spec has prestart, createRuntime or createContainer hooks, or when its rootfs is read-only and some of its mounts need mount points. That covers the workdir as well as mounts a transform adds, such as those from a CDI spec, so a readonly sandbox with a workdir now stays read-only. With a disk cap, gVisor's overlay covers its workdir's host directory too, so the workdir's writes stay under the cap. Mounts at the mount points every image is built with, or inside other mounts, don't count. A worker that can't mount an overlayfs rootfs still runs a readonly sandbox that needs mount points on a private writable overlay, and logs a warning. A sandbox with such hooks fails there instead. Signed-off-by: Kevin Klues <[email protected]>
Previously, the core CI image built erofs-utils with --disable-fuse, so it had mkfs.erofs but no erofsfuse. In this commit, it builds erofs-utils with FUSE support, which installs erofsfuse and the libfuse3 it links against. Sandbox tests can then mount an overlayfs sandbox's image with erofsfuse where the kernel's erofs driver can't. The core sandbox CI job also turns on the overlayfs tests that need erofsfuse, which skip everywhere else. Signed-off-by: Kevin Klues <[email protected]>
Previously, the docs only covered sandboxes that boot straight from their cached EROFS image. In this commit, a new section explains when Ray detects that a sandbox needs an overlayfs rootfs, and what nodes need to support one. Since any sandbox can end up needing one, the install instructions show a Dockerfile for each kernel page size in tabs, each with those tools included. Troubleshooting covers the errors and warnings overlayfs sandboxes can hit. Signed-off-by: Kevin Klues <[email protected]>
a19c84c to
0ada0c8
Compare
- image_utils: master's ray-project#66469 finishes interrupted deletions at the top of every pull. That stays on every call, cache hits included (one listdir), so a node that only hits its cache still gets the space back. Eviction stays on the pull path and below the free-space floor. - image_manager: ray-project#66470 boots a readonly sandbox with a workdir from a kernel overlay, so the warning this PR logged once per process is gone. The once-per-process rule moves to the warning that remains, for workers that can't mount an overlay and fall back to a writable root. - gvisor: kept master's `image_dir = pull_image(...)` with this PR's comment on when the pin is taken. Signed-off-by: xyuzh <[email protected]>
Resubmit the final upstream version of PR ray-project#66470 (096fce7), previously ported on local main as 841f674 and corrected by 15020ef. Integrate upstream mount-probe timeouts, kernel-to-FUSE fallback, launch cleanup, and checkpoint-compatible rootfs handling. Keep the dedicated sandbox log fixture required by the updated tests. Co-authored-by: Copilot <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
…t#66988) ## Description A writable sandbox keeps what it writes in a private overlay whose backing file sits on the node's disk, and nothing bounded it. In SkyRL's SWE-bench Multimodal runs, an 11 GiB write inside one sandbox succeeded, so one runaway build could fill the disk for every trial on the node. Harbor tasks declare a `storage` limit that had nothing to map to. This PR adds a `disk` cap: - `disk` on `create()`, `Sandbox`, `SandboxRuntime.create()` and `SandboxConfig`, in the units `memory` takes (`"10Gi"`, or bytes). Zero, the default, means no cap. The HTTP API takes `resources.disk_limit_mb`. The gRPC facade sets none, since the client SDK never requests disk for sandboxes. - `ImageManager.create_oci_spec` writes the cap into gVisor's `dev.gvisor.spec.rootfs.options: size=N` annotation. runsc ignores the size in its `--overlay2` flag for a rootfs that annotations configure. - `disk` needs an overlay: `readonly=False`, or a `workdir`, since a readonly sandbox with an explicit workdir already runs on a private writable overlay. With a cap, that workdir stays in the overlay instead of a bind-mounted node directory that writes could fill past the cap. Otherwise `SandboxConfig` raises `ValueError` and the HTTP API answers 422. Writes past the cap fail with `ENOSPC` inside the sandbox, the sandbox keeps running, and deleting files frees space. `/tmp` counts toward the cap and `/dev/shm` toward memory. The docs get a "Cap disk use" section. `dd if=/dev/zero of=/root/fill bs=1M count=2048` in a writable `python:3.12-slim` sandbox on a CoreWeave node: | | master | `disk="1Gi"` | | --- | --- | --- | | `dd` | 2 GiB written | `No space left on device` at 1 GiB | | `df -h /` in the sandbox | size 8.0E | size 1.0G | | Overlay file on the node | 2.0 GiB | 1.0 GiB | ## Related issues None filed. Found with SkyRL's Harbor environment for Ray Sandbox (skyrl-project/SkyRL#2467). ## Additional information - Not a duplicate: no open PR matching "sandbox disk", "sandbox storage limit" or "gvisor overlay size" adds a disk cap. ray-project#66470 moves the overlay annotation, so whichever lands second carries the size option over; its kernel-overlayfs boot path would need its own cap. - Tests: `test_disk_caps_the_writable_overlay` and `test_disk_caps_a_readonly_sandbox_with_a_workdir` write past a 64 MiB cap in real gVisor sandboxes, in `/` and `/workspace`, and expect `ENOSPC`. Unit tests cover the annotation, the `readonly`/`workdir` rule, the HTTP 422 and the `disk_limit_mb` pass-through. All fail on master. - Tested on a CoreWeave pod (runsc release-20261005.0, erofs-utils 1.9.4), `TEST_SANDBOX=1 pytest` in `python/ray/experimental/sandbox`: - `tests/test_gvisor_backend.py tests/test_image_manager.py tests/test_image_utils.py tests/test_sandbox_config.py tests/test_sandbox_runtime.py -k "not netns"`: 99 passed, 1 skipped; `test_create_sandbox_helper` alone: 1 passed. - `tests/test_gvisor_backend.py -k netns`: 7 passed. - `http/tests/test_http_app.py test_sandbox_host.py test_http_schemas.py test_http_integration.py`: 82 passed. - Tested on macOS: `pytest http/tests`: 150 passed, 11 skipped (no `modal`). pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
…ies (ray-project#66987) ## Description A `network="public"` sandbox's launch shell starts a namespace holder (`unshare` and its `sleep`) and `slirp4netns`, then exec'd runsc, which became their parent and never waits for them. A stopped sandbox's helpers were orphaned to the pod's init, and Anyscale's init, like many container entrypoints, doesn't reap orphans. So every `public` sandbox left three zombies under PID 1 until the pod restarted. SkyRL's SWE-bench Multimodal runs left about 300 per node. Changes in `backend/gvisor.py`: - The shell stays the parent. It runs runsc in the background and waits for it, and an exit trap kills the holder's `sleep` (so `unshare` reaps it) and `slirp4netns`, then waits for both. - Teardown (`_terminate_tree`) gives the shell 2 s to exit on its own. It kills the process group only if the shell is still running, before reaping it, so the signal can't reach a group that reused the pid. - The holder, `slirp4netns` and runsc run under `setpriv --pdeathsig KILL`, so they die with the shell, which is what Ray kills when the owning worker exits. - `create_sandbox` checks for `setpriv` up front. The docs ask for util-linux 2.33 or later, which added `--pdeathsig`. On an Anyscale node whose PID 1 doesn't reap orphans: | | master | This PR | | --- | --- | --- | | New zombies after 5 `public` sandboxes are created and deleted | 16 | 0 | | 15 s after `ray.kill` of a `public` sandbox's owner, without `delete` | Holder still running | Nothing running | ray-project#67022, stacked on this PR, reclaims the runsc state and bundle that a killed owner leaves. ## Related issues None filed. Found with SkyRL's Harbor environment for Ray Sandbox (skyrl-project/SkyRL#2467). ## Additional information - Not a duplicate: no open PR changes how these helpers are reaped (I searched "sandbox zombie", "slirp4netns zombie" and "sandbox reap"). ray-project#66470, ray-project#65898 and ray-project#66471 also edit the end of the `public` launch script, so whichever lands later needs the same change. - Tests: `test_netns_teardown_leaves_no_zombies` and `test_netns_launch_shell_death_stops_the_sandbox` make the test process a child subreaper, so a helper the backend fails to reap becomes the test's own zombie. Both fail on master. `test_terminate_tree_kills_the_group_only_before_reaping_it` needs no gVisor and fails on the first commit. - Tested in a CoreWeave pod (Ubuntu 22.04, runsc release-20261005.0, Ray nightly) with `TEST_SANDBOX=1 pytest --import-mode=importlib` in `python/ray/experimental/sandbox/tests`: `test_gvisor_backend.py -k netns`: 11 passed; `test_gvisor_backend.py test_image_manager.py test_image_utils.py test_sandbox_config.py test_sandbox_runtime.py -k "not netns"`: 89 passed, 1 skipped (`test_create_sandbox_helper` deselected, since it starts its own Ray). pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
…ay-project#66985) ## Description The image cache named each entry after the literal image reference. `python:3.12-slim`, `library/python:3.12-slim` and `docker.io/library/python:3.12-slim` name the same image, but each one pulled it and built its own EROFS root filesystem. SkyRL's SWE-bench Multimodal tasks spell their images in different ways, and on a CoreWeave node each extra spelling of a 1.1 GiB image cost about a minute and 2.9 GiB of disk. This PR names each entry after the normalized reference (registry, repository, and tag or digest, with Docker Hub written as `docker.io`), followed by a short hash of it. The spellings above all map to `docker.io_library_python_3.12-slim-ea59dc550ffd7fa7`. - The hash keeps apart references that look the same once `/`, `:` and `@` become `_`, such as `repo@sha256:<hex>` and a tag named `sha256_<hex>`. Master's literal names had the same collisions. - The readable part stops at 128 characters, so a long reference stays under the file-name limit. - `parse_image_ref` lowercases the registry host. `Docker.io/python` used to be pulled from https://Docker.io and fail. - A local archive spelled as a path or ending in `.tar` keeps its file name, as before. Existing entries have literal names, so after an upgrade each node pulls each image once more. The old entries are the least recently extracted, so eviction removes them first when the cache needs room. ## Related issues None filed. Found with SkyRL's Harbor environment for Ray Sandbox (skyrl-project/SkyRL#2467). ## Additional information - Not a duplicate: searches for "sandbox image cache" and "sandbox image reference" found no open PR that normalizes references. ray-project#66469, ray-project#66470 and ray-project#65898 check entry names in this module, and the new names pass their check. - Tests: new tests cover one entry and one pull for the spellings, separate entries for colliding references, short names for long references, uppercase hosts, and releasing a pin after its relative archive path is deleted. The spelling, digest-versus-tag and host-case tests fail on master. - Tested on a CoreWeave pod (runsc release-20261005.0, erofs-utils 1.9.4): `TEST_SANDBOX=1 pytest tests/test_gvisor_backend.py tests/test_image_manager.py tests/test_image_utils.py tests/test_sandbox_config.py tests/test_sandbox_runtime.py -k "not netns and not test_create_sandbox_helper"`: 93 passed, 1 skipped (95 passed merged with master); `-k netns`: 9 passed. pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
…output leniently (ray-project#66986) ## Description On timeout, `exec_command` killed only the `runsc exec` client, then waited without a timeout for the output pipes, which the command kept open in the sandbox: `exec("sleep 30; echo done", timeout=1)` returned after 30 s. Separately, one byte of output that isn't UTF-8 failed the whole exec (`'utf-8' codec can't decode byte 0xff`), losing the exit code and output. This PR changes `backend/gvisor.py`: - On timeout, `_kill_exec` lists the sandbox's processes with `runsc trace procfs` and kills by PID everything in the command's session plus its descendants (the command's PID comes from `runsc exec -internal-pid-file`). It lists before killing anything, so a `setsid` child is still found through its parent, and lists again until nothing is left, at most 5 times, because a process can fork between a listing and its kill. - Output is read as bytes and decoded with U+FFFD for invalid UTF-8. Why sessions: `runsc exec` makes the command a session leader, and its processes stay in the session unless they call `setsid()`, even after their parent exits or they change process group (GNU `timeout` does). Only `runsc trace procfs` reports sessions; the PGID column of `runsc ps` and `runsc kill --pgid` are new (April 2026) and cover one group. Behavior changes: - A timed-out exec returns at its timeout and leaves nothing running, except a daemon that called `setsid` and whose parent exited. The docs say so next to the exec example. - Line endings come back as printed. `text=True` used to turn `\r` and `\r\n` into `\n`. ## Related issues None filed. Found running SkyRL's Harbor environment on Ray Sandbox (skyrl-project/SkyRL#2467), where a stuck command held its trial for the agent's full 5,400 s timeout. ## Additional information - Not a duplicate: open PRs that touch the gVisor backend (ray-project#66932, ray-project#67022, ray-project#66821, ray-project#66471, ray-project#66470, ray-project#65898) don't change exec timeouts or output decoding. ray-project#66932 wraps `runsc exec` in its cgroup launcher, so whichever lands second needs a small merge in `exec_command`. - Tests: a parser unit test and five gVisor tests. The plain timeout and UTF-8 tests fail on master; the background-job and fork-loop tests fail on this PR's first commit (d4fafd8), and the `setsid`-child test fails if the command is killed before the listing. - Tested on a CoreWeave pod (runsc release-20261012.0), rebased on master afd4ccf: `TEST_SANDBOX=1 pytest tests/test_gvisor_backend.py tests/test_image_manager.py tests/test_image_utils.py tests/test_sandbox_config.py tests/test_sandbox_runtime.py -k "not netns"`: 117 passed, 1 skipped (`test_create_sandbox_helper` ran on its own and passed); `-k netns`: 13 passed. pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
…aves (ray-project#67022) ## Description When the Ray worker that owns a sandbox crashed or was OOM-killed, the sandbox kept running with nobody to delete it: its launch process had a session of its own, out of reach of the raylet's process-group cleanup, and its TTL died with the actor. However the owner died, its runsc state, bundle (with the overlay's backing file) and image-cache pin stayed on the node, and the pin kept the image from being evicted. In `backend/gvisor.py`: - The launch process stays in its owner's process group (no `start_new_session`), so when the raylet kills a dead worker's group, the sandbox goes too: runsc's sandbox through runsc's parent-death signal, a `public` sandbox's helpers through ray-project#66987's `setpriv --pdeathsig`. Teardown kills only the launch process. - Every launch command starts with `trap '' INT QUIT`, so a Ctrl-C in the creator's terminal, or a Jupyter kernel interrupt, still leaves its sandboxes running, as on master. A SIGQUIT (Ctrl-\\) still stops them, since runsc is a Go program and installs its own handler. - Each bundle holds an `.owner` file that the owning backend keeps `flock`ed, and the kernel drops the lock when the owner dies. `create_sandbox` starts a background pass, at most once a minute per process, that reclaims every bundle whose lock is free: it kills a sandbox still running there, runs `runsc delete -force`, releases the image pin and removes the bundle, owner file last. The file is locked before it gets its name, so a bundle being created is never taken, and it holds flags rather than a command line, so a planted file can't make the reclaim run anything. Start with `_own_bundle` and `_reclaim_if_unowned`. - A create that fails before its sandbox starts deletes its bundle at once. A sandbox now stops with the worker that created it. One created outside a Ray worker, such as by a driver script, outlives its creator until a later reclaim pass stops it, and `sandboxes.md` says so. Sandbox processes 3 s and 15 s after its owner's worker is SIGKILLed, without `delete`: | | ray-project#66987 | This PR | | --- | --- | --- | | `network="none"` | 3 and 3 | 0 and 0 | | `network="public"` | 5 and 5 | 0 and 0 | | runsc state, bundle and image pin after the next create | Still there | Gone | ## Related issues None filed. Found with SkyRL's Harbor environment for Ray Sandbox (skyrl-project/SkyRL#2467). Its SWE-bench Multimodal report notes both leaks. ## Additional information - Not a duplicate: no open PR ties a sandbox to its owner or reclaims a dead owner's files (I searched "sandbox orphan", "owner", "crash", "leak", "reclaim", "process group" and "TTL"). My ray-project#66932 also deletes dead owners' files for sandboxes with limits, and ray-project#66469 also deletes a failed create's bundle; whichever lands second drops its copy. ray-project#66471 and ray-project#66470 add launch paths that still use `start_new_session`. - Builds on ray-project#66987, which is merged. - Tests: four gVisor tests kill an owner with its group (as the raylet does) or alone (as a driver can die), for `none` and `public`, and check that the sandbox stops and the reclaim deletes its files and pin. Two more (`test_owner_interrupt_leaves_its_sandbox_running` and its `netns` twin) send the owner's group SIGINT, then SIGTERM: the sandbox must keep running, network included, and then stop. Six unit tests cover which bundles a reclaim takes, what it runs, the order it deletes in, failed creates, the background pass and teardown. All fail on ray-project#66987. - Tested in a CoreWeave pod (Ubuntu 22.04, runsc release-20261012.0, Ray nightly), rebased on master afd4ccf, with `TEST_SANDBOX=1 pytest --import-mode=importlib` in `python/ray/experimental/sandbox/tests`, on `test_gvisor_backend.py test_image_manager.py test_image_utils.py test_sandbox_config.py test_sandbox_runtime.py`: `-k netns`: 16 passed; `-k "not netns"`: 120 passed, 1 skipped (`test_create_sandbox_helper` deselected; it passes on its own). pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Philipp Moritz <[email protected]> Co-authored-by: Philipp Moritz <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
## Description 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
This PR is based on #66469 and #66528, and depends on both. Only the top four commits are new.
At present, every sandbox boots straight from its image's cached EROFS image. In doing so, gVisor mounts the rootfs backed by that image as read-only inside the sandbox. There is no opportunity to "customize" or "modify" that root filesystem on a per-sandbox basis before it starts.
This leaves two gaps in Ray's support for standard OCI features:
prestart,createRuntime, andcreateContainerhooks run on the host before a sandbox starts, and often write into its rootfs. For example, NVIDIA's CDI hooks create library symlinks and update the ldcache in a sandbox's rootfs using information (and tools) only available on the host. Without a per-sandbox rootfs for them to write to, master has no way to support these hooks.workdirmounts a host directory at a path most images don't have. Master works around this by making the rootfs writable in that case, with a warning, but that isn't a robust or long-term solution.This PR adds support for booting a sandbox from a kernel overlayfs over its cached EROFS image when its final OCI spec needs one. Ray makes this decision after any spec transform has run, so it takes into account any hooks or mounts a transform adds. Every other sandbox keeps booting from its EROFS image, as before.
In fact, the EROFS path is unchanged apart from the order of a few flags in the
network="public"script. The one behavior change is that a read-only sandbox with an explicitworkdirnow stays read-only, since it boots from an overlay instead of becoming writable.test_gvisor_backend_readonly_rootfs, which master skips, now runs successfully.prestart,createRuntime, orcreateContainerhooks, which run on the host and can write into the sandbox's rootfs. It's also when the rootfs is read-only and some of the spec's mounts need mount points the image might lack. Mounts at the mount points every image is built with don't count, and neither do mounts inside another mount, such as a device node under/dev.--overlay2layer, and a read-only sandbox still sees a read-only root. A worker with mount privileges mounts the image with the kernel'serofsdriver, or witherofsfuseif that fails. A worker without mount privileges mounts it witherofsfusein a new user namespace for each sandbox, which needs Linux 5.11 or later. In that user namespace, a worker running as root maps every ID to itself, and a worker running as any other user maps its subordinate IDs, so files keep their owners from the image. A worker with no subordinate IDs maps only root and logs a warning, and every file root doesn't own shows up as owned by nobody.Prerequisites for this new support include
unshare,mount,mountpoint,flock, andsetprivfrom util-linux on every worker. Workers without mount privileges also neederofsfuse, as do workers whose kernel lacks theerofsdriver or free loop devices. Workers without mount privileges that also run as a user other than root neednewuidmapandnewgidmapfrom theuidmappackage.The core CI image now builds
erofs-utilswith FUSE support, so CI haserofsfuse. The docs gain a section on when Ray boots a sandbox from an overlayfs rootfs and what nodes need to support one. They also gain a Dockerfile for each kernel page size that installs those tools, and troubleshooting for the errors and warnings overlayfs sandboxes can hit.The GPU support PR (#65898) builds on this. A GPU's CDI spec adds both
createContainerhooks and mounts for the driver files and device nodes, so GPU sandboxes boot from an overlayfs rootfs.Related issues
Fixes #66408. Depends on #66469 and #66528. This branch carries their commits until they merge.
Additional information
We ran the full sandbox test suite (
python/ray/experimental/sandbox/tests/withTEST_SANDBOX=1) on a node with 64 KiB pages, both as root (overlay mounted directly) and as an unprivileged user (overlay mounted witherofsfusein a user namespace).In a user namespace, the overlay keeps its metadata in user xattrs on the tmpfs, which tmpfs supports from Linux 6.6. On older kernels, host-side writes there can't rename or replace a directory from the lower layer. In practice, that doesn't get in the way. Hooks such as NVIDIA's CDI hooks, and runsc itself, only create or replace files, symlinks, and mount points in the rootfs. Writes made inside the sandbox go to gVisor's own overlay, not this one, so the limit never applies to them.