Repository navigation
[core][sandbox] Give a public sandbox's gofer its own network namespace - #66528
Conversation
There was a problem hiding this comment.
Code Review
This pull request updates the gVisor backend in Ray's experimental sandbox to append the '--gofer-network-namespace=new' argument to runsc when public networking is enabled. This ensures that the gofer process creates and uses its own empty network namespace, resolving an issue where it cannot join a network namespace created outside its user namespace. A corresponding unit test has been added to verify this behavior. There are no review comments, and we have no additional feedback to provide.
|
A followup question: how can the user monitor the Namespace resource overhead? On machines with many concurrent public sandboxes, this could add minor resource overhead. |
The extra cost is small. Each public sandbox gets one more empty network namespace (loopback only, no traffic) that lives only as long as its gofer, on top of the user namespace and slirp4netns process it already has. In a quick experiment, I measured about 150 kB of kernel memory per namespace, charged to the worker's cgroup. Since it's charged to the cgroup, Ray's memory monitor already counts it, so it shows up in the worker's memory usage like anything else. As far as I know, there are no sandbox-specific metrics gathered today, so if per-sandbox resource metrics would be useful, that seems like a good follow-up beyond this PR. |
72beda4 to
9c9414b
Compare
Previously, runsc shared one network namespace between the gofers of all sandboxes under its root. A network="public" sandbox runs runsc inside a user namespace its script creates, while sandboxes with other network modes run it outside any. A gofer in that user namespace can't join a network namespace created outside it, so a public sandbox fails to boot when another sandbox created the shared one. On a worker running as root, the public network tests skip for this reason. In this commit, runsc gives the gofer of a public sandbox a network namespace of its own, with --gofer-network-namespace=new. Signed-off-by: Kevin Klues <[email protected]>
9c9414b to
2917265
Compare
test_netns_sandbox_actor_changes_its_egress_allowlist fails on CI for every sandbox PR since ray-project#66528 stopped CI from skipping network="public" tests. CI has no slirp4netns, so ensure_slirp4netns downloads one and adds it to the test process's PATH, but an earlier test in the file has already started Ray's workers with the old PATH, and the actor can't find it. The actor now gets the test's PATH through its runtime_env. Signed-off-by: xyuzh <[email protected]>
## Description Sandbox CPU and memory limits aren't enforced today. Ray writes them into the OCI spec, but `network="public"` runs runsc with `--ignore-cgroups`, and rootless runsc skips cgroup errors. On master, four busy processes in a `cpu=1` sandbox finish about as fast as one, and a `memory="512Mi"` sandbox can allocate 1.5 GiB. This PR gives each limited sandbox a cgroup v2 that Ray creates in a subtree the node delegates (`RAY_SANDBOX_CGROUP_PATH`): - Ray writes `cpu.max`, `memory.max`, `memory.swap.max=0` and `memory.oom.group=1`. runsc, its network helpers, and every exec and file operation start through a small launcher that joins the cgroup first. runsc keeps `--ignore-cgroups`, because its own setup writes into every ancestor's `cgroup.subtree_control` (see the review discussion). - A sandbox with a CPU limit runs on `max(2, ceil(cpu))` CPUs, so `nproc` matches its budget. Ray picks them under a node-wide file lock and records them in the sandbox's owner file from #67022, so sandboxes created at the same time spread out. - Cleanup reuses #67022. A sandbox stops with the worker that owns it, and the reclaim pass that deletes a dead owner's bundle also kills and removes the sandbox's cgroup. - An OOM kill stops the sandbox, not its worker, and becomes the sandbox's termination reason. Exclusive CPU cores (`cpu_isolation="exclusive"`) follow in a separate PR stacked on this one, so this PR adds no API parameter. Behavior changes: - A positive `cpu` or `memory` on a node without a delegated subtree now fails before the image pull instead of being ignored. Sandboxes without limits are unaffected. - `cpu=0` means no limit. The `Sandbox` actor derives a limit from its assigned CPUs only for `cpu=None`. - A create error that isn't a `SandboxError` now becomes a `SandboxCreationError`, and a failed launch no longer leaves its bundle behind. - Known gap: `MemTotal` inside the sandbox still shows the node's memory, because runsc sizes memory only from a cgroup it set up. How to review: `_internal/cgroup.py` and `cgroup_launcher.py`, then `create_sandbox`, `_start_sandbox`, `delete_sandbox` and `_reclaim_if_unowned` in `backend/gvisor.py`, the plumbing in `runtime.py`, `sandbox.py` and `http/host.py`, then the tests. ## Related issues Related to #65352 (why CI needs `--ignore-cgroups`). #65751 asks for limits on container workers, which this PR doesn't touch. ## Additional information - Not a duplicate: no open PR enforces sandbox limits (searched "sandbox cgroup", "resource limits", "cpu limit", "memory limit", "gvisor cgroup"). It builds on #66528 and #67022, which are merged. - Tests: `test_cgroup.py` uses fake cgroup files. `test_resource_limits.py` checks real enforcement, OOM and a dead owner's cleanup, and CI skips it because CI has no delegated subtree. - Tested on a CoreWeave pod (rayproject/ray:nightly-py312, runsc release-20261012.0, root with `SYS_ADMIN`), `TEST_SANDBOX=1 pytest test_gvisor_backend.py test_image_manager.py test_image_utils.py test_sandbox_config.py test_sandbox_runtime.py test_cgroup.py test_resource_limits.py test_egress_guard.py -k "not netns"`, with `test_create_sandbox_helper` deselected: - Without `RAY_SANDBOX_CGROUP_PATH`, as in CI: 189 passed, 11 skipped. `-k netns`: 21 passed. `test_sandbox.py`: 7 passed, 1 skipped. `http/tests/test_http_integration.py`: 2 passed. - With a delegated pool: 199 passed, 1 skipped. `-k netns`: 21 passed. `test_sandbox.py`: 7 passed, 1 skipped. `test_resource_limits.py` on its own: 10 passed. Four processes that created `cpu=1` sandboxes at once got four disjoint CPU pairs. - macOS: `test_cgroup.py` 19 passed, 1 skipped. `http/tests` 168 passed, 10 skipped, plus `test_full_sandbox_lifecycle`, which needs gVisor. pre-commit and the API parameter coverage check pass. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]>
…66470) ## 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: - **OCI hooks have nowhere to write.** `prestart`, `createRuntime`, and `createContainer` hooks 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. - **Read-only sandboxes can't gain mount points.** Every mount in a sandbox's OCI spec needs a mount point in its rootfs, which runsc creates before the sandbox starts if the image lacks one. For a read-only root, runsc applies no overlay of its own, so it can't create any missing mount points in the immutable EROFS image. For example, an explicit `workdir` mounts 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 explicit `workdir` now stays read-only, since it boots from an overlay instead of becoming writable. `test_gvisor_backend_readonly_rootfs`, which master skips, now runs successfully. - **How Ray decides a sandbox needs an overlay.** Ray boots a sandbox from an overlay only when its final OCI spec needs one. That's when the spec has `prestart`, `createRuntime`, or `createContainer` hooks, 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`. - **How the overlay works.** The overlay's read-only lower layer is the sandbox's cached EROFS image itself, mounted separately for each sandbox, so nothing is unpacked or copied. Its upper layer is a small tmpfs in the sandbox's bundle. Host-side writes, such as those from OCI hooks and the mount points runsc creates, land in that upper layer and never reach the cached image or another sandbox. Writes made inside a writable sandbox still go to gVisor's `--overlay2` layer, and a read-only sandbox still sees a read-only root. A worker with mount privileges mounts the image with the kernel's `erofs` driver, or with `erofsfuse` if that fails. A worker without mount privileges mounts it with `erofsfuse` in 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. - **What happens when a sandbox needs an overlay that can't be mounted.** Each worker process checks once whether it can mount an overlay, by mounting a throwaway one. On a worker that can't, a sandbox whose spec has hooks that run on the host fails to start, with an error that reports why each way of mounting the image failed. A read-only sandbox that needs mount points still starts, but on a private writable gVisor overlay instead of a read-only root, and Ray logs a warning. Prerequisites for this new support include `unshare`, `mount`, `mountpoint`, `flock`, and `setpriv` from util-linux on every worker. Workers without mount privileges also need `erofsfuse`, as do workers whose kernel lacks the `erofs` driver or free loop devices. Workers without mount privileges that also run as a user other than root need `newuidmap` and `newgidmap` from the `uidmap` package. The core CI image now builds `erofs-utils` with FUSE support, so CI has `erofsfuse`. 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 `createContainer` hooks 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/` with `TEST_SANDBOX=1`) on a node with 64 KiB pages, both as root (overlay mounted directly) and as an unprivileged user (overlay mounted with `erofsfuse` in 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. --------- Signed-off-by: Kevin Klues <[email protected]>
…project#66932) ## Description Sandbox CPU and memory limits aren't enforced today. Ray writes them into the OCI spec, but `network="public"` runs runsc with `--ignore-cgroups`, and rootless runsc skips cgroup errors. On master, four busy processes in a `cpu=1` sandbox finish about as fast as one, and a `memory="512Mi"` sandbox can allocate 1.5 GiB. This PR gives each limited sandbox a cgroup v2 that Ray creates in a subtree the node delegates (`RAY_SANDBOX_CGROUP_PATH`): - Ray writes `cpu.max`, `memory.max`, `memory.swap.max=0` and `memory.oom.group=1`. runsc, its network helpers, and every exec and file operation start through a small launcher that joins the cgroup first. runsc keeps `--ignore-cgroups`, because its own setup writes into every ancestor's `cgroup.subtree_control` (see the review discussion). - A sandbox with a CPU limit runs on `max(2, ceil(cpu))` CPUs, so `nproc` matches its budget. Ray picks them under a node-wide file lock and records them in the sandbox's owner file from ray-project#67022, so sandboxes created at the same time spread out. - Cleanup reuses ray-project#67022. A sandbox stops with the worker that owns it, and the reclaim pass that deletes a dead owner's bundle also kills and removes the sandbox's cgroup. - An OOM kill stops the sandbox, not its worker, and becomes the sandbox's termination reason. Exclusive CPU cores (`cpu_isolation="exclusive"`) follow in a separate PR stacked on this one, so this PR adds no API parameter. Behavior changes: - A positive `cpu` or `memory` on a node without a delegated subtree now fails before the image pull instead of being ignored. Sandboxes without limits are unaffected. - `cpu=0` means no limit. The `Sandbox` actor derives a limit from its assigned CPUs only for `cpu=None`. - A create error that isn't a `SandboxError` now becomes a `SandboxCreationError`, and a failed launch no longer leaves its bundle behind. - Known gap: `MemTotal` inside the sandbox still shows the node's memory, because runsc sizes memory only from a cgroup it set up. How to review: `_internal/cgroup.py` and `cgroup_launcher.py`, then `create_sandbox`, `_start_sandbox`, `delete_sandbox` and `_reclaim_if_unowned` in `backend/gvisor.py`, the plumbing in `runtime.py`, `sandbox.py` and `http/host.py`, then the tests. ## Related issues Related to ray-project#65352 (why CI needs `--ignore-cgroups`). ray-project#65751 asks for limits on container workers, which this PR doesn't touch. ## Additional information - Not a duplicate: no open PR enforces sandbox limits (searched "sandbox cgroup", "resource limits", "cpu limit", "memory limit", "gvisor cgroup"). It builds on ray-project#66528 and ray-project#67022, which are merged. - Tests: `test_cgroup.py` uses fake cgroup files. `test_resource_limits.py` checks real enforcement, OOM and a dead owner's cleanup, and CI skips it because CI has no delegated subtree. - Tested on a CoreWeave pod (rayproject/ray:nightly-py312, runsc release-20261012.0, root with `SYS_ADMIN`), `TEST_SANDBOX=1 pytest test_gvisor_backend.py test_image_manager.py test_image_utils.py test_sandbox_config.py test_sandbox_runtime.py test_cgroup.py test_resource_limits.py test_egress_guard.py -k "not netns"`, with `test_create_sandbox_helper` deselected: - Without `RAY_SANDBOX_CGROUP_PATH`, as in CI: 189 passed, 11 skipped. `-k netns`: 21 passed. `test_sandbox.py`: 7 passed, 1 skipped. `http/tests/test_http_integration.py`: 2 passed. - With a delegated pool: 199 passed, 1 skipped. `-k netns`: 21 passed. `test_sandbox.py`: 7 passed, 1 skipped. `test_resource_limits.py` on its own: 10 passed. Four processes that created `cpu=1` sandboxes at once got four disjoint CPU pairs. - macOS: `test_cgroup.py` 19 passed, 1 skipped. `http/tests` 168 passed, 10 skipped, plus `test_full_sandbox_lifecycle`, which needs gVisor. pre-commit and the API parameter coverage check pass. - 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
Carry over the remaining integration adjustments from 95b7f76f4e: deletion-tombstone regression tests, explicit free-space disabling in cache tests, sandbox logging fixtures, and overlayfs-compatible disk-cap documentation. Preserve the upstream host-owned facade exec-state documentation and existing GPU/CDI integration. Validation on macOS using the existing virtualenv and checked-out sandbox modules: 320 portable prerequisite/runtime/restore/overlayfs tests passed (2 skipped, 15 native-only cases deselected); 70 selected GPU/launch/egress/cleanup unit tests passed; 174 HTTP/gRPC tests passed (10 skipped). Repository pre-commit checks passed. Native Linux runsc, mount, namespace, cgroup integration, Linux-specific socket behavior, and hardware GPU tests were not run. The requested upstream PRs remain separate commits, and the two supplied Resubmit commits were cherry-picked separately. No duplicate port of ray-project#66528 was added. AI assistance was used to integrate and validate these ports. 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 fixes
network="public"sandboxes that fail to boot on a worker running as root, so thenetwork="public"sandbox tests intest_gvisor_backend.pyare no longer skipped.By default, runsc puts the gofers of all sandboxes that use the same state directory (
--root) into a single network namespace, created by the first gofer that needs it. Ray starts every sandbox on a worker with the same state directory, so all of their gofers join that one namespace. Anetwork="public"sandbox runs runsc inside a user namespace that its script creates. Its gofer can't join a network namespace created outside that user namespace, so the sandbox fails to boot if another sandbox on the worker created the shared namespace first. The test fixture treats that boot failure as an environment that forbids nested user namespaces, so on a worker running as root, everynetwork="public"sandbox test gets skipped.In this PR, runsc gives the gofer of a public sandbox a network namespace of its own, with
--gofer-network-namespace=new. Sandboxes with other network modes are unchanged.Related issues
#66470, which boots some sandboxes from an overlayfs rootfs inside a user namespace, extends the same flag to those sandboxes as well.
Additional information
We ran
test_gvisor_backend.pywithTEST_SANDBOX=1as root, in a privileged container with runsc in/usr/local/bin:network="public"sandbox tests, whose sandboxes fail to boot.network="public"sandbox tests boot and run. The only skip left is master's unconditional skip oftest_gvisor_backend_readonly_rootfs.