Repository navigation
[core][sandbox] Bound the image cache: LRU eviction and opt-in tarball - #65748
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces an image cache eviction mechanism for Ray's sandbox environment to prevent disk space exhaustion, alongside making the retention of uncompressed image tarballs opt-in. Feedback on these changes highlights critical robustness and safety concerns: a race condition and resource leak in sandbox creation could lead to failed container starts or permanent image locking, concurrent file deletions during eviction could prematurely abort the cleanup process, and invalid environment variable parsing for the cache size cap could crash the sandbox creation. Addressing these issues with more granular exception handling and proper ordering of the image usage marking will ensure a more resilient and stable implementation.
2d8b9bb to
1b06549
Compare
Nodes cache the extracted rootfs of every image they ever ran plus an uncompressed re-tar of it, and nothing reclaims the space: a long-lived node fills its disk, which takes down far more than sandboxes (observed as opaque 500s from the whole Ray stack during Terminal-Bench sweeps of 89 distinct multi-GB images). - RAY_SANDBOX_IMAGE_CACHE_MAX_BYTES caps the cache: before each new pull, least-recently-extracted images are evicted until the cache fits. Images backing live sandboxes are protected by refcount markers (their extracted rootfs is the overlay lower layer), mid-pull directories by the .extracted marker, and concurrent pulls by taking each candidate's per-image lock non-blocking. - The uncompressed tarball becomes opt-in (RAY_SANDBOX_KEEP_IMAGE_TARBALL): it doubled every image's footprint for a rarely-exercised restore path. Signed-off-by: xyuzh <[email protected]>
Review feedback, three parts: - Tolerate concurrent deletions per entry while scanning the cache instead of aborting the whole eviction on the first OSError. - Never evict images extracted within a grace period (10 minutes): it covers the window between a pull returning and its sandbox registering as a user. - Release the in-use marker on every sandbox-creation failure path (init, bundle preparation, boot): a failed creation never reaches delete_sandbox, and the marker would have blocked eviction of that image forever. Signed-off-by: xyuzh <[email protected]>
test_pull_and_extract_remote_image pinned the old always-write-a-tar behavior; assert the new default (no tarball) and cover the opt-in env explicitly. Signed-off-by: xyuzh <[email protected]>
1b06549 to
77fc569
Compare
There was a problem hiding this comment.
I have a few comments:
- The default is not to evict anything, right? We should think about whether that's the right default, and also document this flag (especially if we don't evict anything by default, since that will use up the disk which will be very disruptive for anybody using it)
- Ideally this would be part of
ImageManagerso every backend will use it automatically without having to make too many API calls. In that case, the image manager should be able to callmark_image_in_useautomatically when the image is used, and we probably just need an explicitreleasecall to be called at the right time. Not necessary to address before merging, but if there is a natural API as part of the image manager, we should do it (for sure once we implement more backends).
| pass | ||
|
|
||
|
|
||
| def release_image_use(image_dir: str, instance_id: str) -> None: |
There was a problem hiding this comment.
Renamed in 0ccea5d: pinning moved into ImageManager, so the public API is pull_image(..., instance_id=) plus release_image(image, instance_id), and the file-level helpers are private (_mark_image_in_use / _release_image_use).
|
|
||
| _IMAGE_CACHE_MAX_BYTES_ENV = "RAY_SANDBOX_IMAGE_CACHE_MAX_BYTES" | ||
| _KEEP_IMAGE_TARBALL_ENV = "RAY_SANDBOX_KEEP_IMAGE_TARBALL" | ||
| _USERS_DIRNAME = ".users" |
There was a problem hiding this comment.
should this be an absolute path?
There was a problem hiding this comment.
It's a directory name, not a path: each cached image gets a .users/ subdirectory with one marker file per live sandbox, joined onto that image's cache dir. Renamed to _USERS_SUBDIR with a comment in 0ccea5d to make that clearer.
| return total | ||
|
|
||
|
|
||
| def evict_images_over_cap(images_dir: str, max_bytes: int) -> None: |
There was a problem hiding this comment.
nit: evict_least_recently_used_images?
There was a problem hiding this comment.
Renamed to evict_least_recently_used_images in 0ccea5d.
…default - `ImageManager.pull_image(..., instance_id=)` registers the sandbox as a user of the image while holding the image's lock, and `ImageManager.release_image` drops it; the gVisor backend no longer touches marker files directly. Eviction re-checks users under the same lock, so a pull can never race an eviction. The mtime grace period, which never covered cache hits, is gone. - The cache cap now defaults to half of the filesystem holding the cache; `RAY_SANDBOX_IMAGE_CACHE_MAX_BYTES` overrides it and `0` disables eviction. Invalid values log a warning and fall back to the default. - Eviction counts sibling and orphan `<name>.tar` archives toward the cap, never evicts the image being pulled, and runs after teardown in `delete_sandbox` so the overlay lower layer is unused when released. - Rename to `evict_least_recently_used_images`; document the cache settings.
|
Addressed the review comments in 0ccea5d:
|
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Reviewed by Cursor Bugbot for commit 0ccea5d. Configure here.
|
|
||
| shutil.rmtree(root_dir, ignore_errors=True) | ||
| # Only now is the overlay's lower layer unused. | ||
| self._image_manager.release_image(config.image, sandbox_id) |
There was a problem hiding this comment.
Delete can leak image pin forever
Medium Severity
delete_sandbox pops metadata first and only calls release_image after kill, runsc delete, and rmtree. An exception in that stretch (for example FileNotFoundError from subprocess.run) skips the release, and a retry finds no metadata. The .users marker stays on disk, so that image is never evicted again.
Reviewed by Cursor Bugbot for commit 0ccea5d. Configure here.
The archive's only reader was the restore branch in the same function, which re-extracted it when the extracted directory had gone missing, a path nothing exercised. Drop the archive, the restore branch, and the RAY_SANDBOX_KEEP_IMAGE_TARBALL opt-in. Eviction still removes archives left by earlier versions and counts them toward the cap. Docs: call out RAY_SANDBOX_IMAGE_CACHE_MAX_BYTES in the troubleshooting section as well.
|
Good call on the tarball: its only reader was the restore branch in the same function (re-extract from the archive when the extracted directory had gone missing), which nothing exercised. Removed it entirely in 51cdda2, along with |
Signed-off-by: Philipp Moritz <[email protected]>
Signed-off-by: Philipp Moritz <[email protected]>
ray-project#65748) ## Why are these changes needed? Nodes cache the extracted rootfs of every image they ever ran **plus an uncompressed re-tar of it**, and nothing reclaims the space. A long-lived node eventually fills its disk, which takes down far more than sandboxes: during Terminal-Bench 2.1 sweeps (89 distinct images, many multi-GB) under Harbor, aged nodes degraded into opaque 500s from the whole Ray stack while fresh nodes ran the same images fine. Changes: - **The image cache is bounded by default.** Before each pull, `ImageManager` evicts the least recently extracted images until the cache fits the cap. The cap defaults to half of the filesystem that holds the cache; `RAY_SANDBOX_IMAGE_CACHE_MAX_BYTES` sets it explicitly and `0` disables eviction. Sibling and orphan `<name>.tar` archives count toward the cap. - **Images in use are pinned through `ImageManager`.** `pull_image(..., instance_id=)` registers the sandbox as a user of the image while holding the image's lock, and `release_image(image, instance_id)` drops the pin. Eviction re-checks users under the same lock, so a pull can never race an eviction, and mid-pull images (no `.extracted` marker) and images whose lock is held are skipped. The gVisor backend pins on pull, releases on every creation-failure path, and releases after teardown in `delete_sandbox`, once the overlay's lower layer is unused. Backends built on `BaseImageManager` get this for free. - **The uncompressed tarball is gone.** Its only reader was a restore branch that re-extracted it when the extracted directory had disappeared, which nothing exercised, and it doubled every image's disk footprint. Archives left by earlier versions count toward the cap and are evicted with their image. `RAY_SANDBOX_IMAGE_CACHE_MAX_BYTES` is documented in the sandboxes guide under "Container images" and in the troubleshooting section. ## Related issue number Follow-up to ray-project#65570; sibling of ray-project#65737 / ray-project#65744 / ray-project#65745 (the Terminal-Bench fix series). ## Checks - [x] Signed off (DCO); `ruff`, `black`, and `pydoclint` pass with the pre-commit versions and flags. - [x] Unit tests run without gVisor: `test_image_cache_eviction` (LRU order, in-use and kept images protected, unextracted skipped, orphan tarballs counted), `test_pull_pins_image_until_release` (pin on pull and on cache hit, eviction blocked until release), `test_image_cache_max_bytes_default_and_env`. The gVisor-gated remote-pull test asserts no archive is written. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Philipp Moritz <[email protected]> Co-authored-by: Philipp Moritz <[email protected]>
ray-project#65748) ## Why are these changes needed? Nodes cache the extracted rootfs of every image they ever ran **plus an uncompressed re-tar of it**, and nothing reclaims the space. A long-lived node eventually fills its disk, which takes down far more than sandboxes: during Terminal-Bench 2.1 sweeps (89 distinct images, many multi-GB) under Harbor, aged nodes degraded into opaque 500s from the whole Ray stack while fresh nodes ran the same images fine. Changes: - **The image cache is bounded by default.** Before each pull, `ImageManager` evicts the least recently extracted images until the cache fits the cap. The cap defaults to half of the filesystem that holds the cache; `RAY_SANDBOX_IMAGE_CACHE_MAX_BYTES` sets it explicitly and `0` disables eviction. Sibling and orphan `<name>.tar` archives count toward the cap. - **Images in use are pinned through `ImageManager`.** `pull_image(..., instance_id=)` registers the sandbox as a user of the image while holding the image's lock, and `release_image(image, instance_id)` drops the pin. Eviction re-checks users under the same lock, so a pull can never race an eviction, and mid-pull images (no `.extracted` marker) and images whose lock is held are skipped. The gVisor backend pins on pull, releases on every creation-failure path, and releases after teardown in `delete_sandbox`, once the overlay's lower layer is unused. Backends built on `BaseImageManager` get this for free. - **The uncompressed tarball is gone.** Its only reader was a restore branch that re-extracted it when the extracted directory had disappeared, which nothing exercised, and it doubled every image's disk footprint. Archives left by earlier versions count toward the cap and are evicted with their image. `RAY_SANDBOX_IMAGE_CACHE_MAX_BYTES` is documented in the sandboxes guide under "Container images" and in the troubleshooting section. ## Related issue number Follow-up to ray-project#65570; sibling of ray-project#65737 / ray-project#65744 / ray-project#65745 (the Terminal-Bench fix series). ## Checks - [x] Signed off (DCO); `ruff`, `black`, and `pydoclint` pass with the pre-commit versions and flags. - [x] Unit tests run without gVisor: `test_image_cache_eviction` (LRU order, in-use and kept images protected, unextracted skipped, orphan tarballs counted), `test_pull_pins_image_until_release` (pin on pull and on cache hit, eviction blocked until release), `test_image_cache_max_bytes_default_and_env`. The gVisor-gated remote-pull test asserts no archive is written. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Philipp Moritz <[email protected]> Co-authored-by: Philipp Moritz <[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


Why are these changes needed?
Nodes cache the extracted rootfs of every image they ever ran plus an uncompressed re-tar of it, and nothing reclaims the space. A long-lived node eventually fills its disk, which takes down far more than sandboxes: during Terminal-Bench 2.1 sweeps (89 distinct images, many multi-GB) under Harbor, aged nodes degraded into opaque 500s from the whole Ray stack while fresh nodes ran the same images fine.
Changes:
ImageManagerevicts the least recently extracted images until the cache fits the cap. The cap defaults to half of the filesystem that holds the cache;RAY_SANDBOX_IMAGE_CACHE_MAX_BYTESsets it explicitly and0disables eviction. Sibling and orphan<name>.tararchives count toward the cap.ImageManager.pull_image(..., instance_id=)registers the sandbox as a user of the image while holding the image's lock, andrelease_image(image, instance_id)drops the pin. Eviction re-checks users under the same lock, so a pull can never race an eviction, and mid-pull images (no.extractedmarker) and images whose lock is held are skipped. The gVisor backend pins on pull, releases on every creation-failure path, and releases after teardown indelete_sandbox, once the overlay's lower layer is unused. Backends built onBaseImageManagerget this for free.RAY_SANDBOX_IMAGE_CACHE_MAX_BYTESis documented in the sandboxes guide under "Container images" and in the troubleshooting section.Related issue number
Follow-up to #65570; sibling of #65737 / #65744 / #65745 (the Terminal-Bench fix series).
Checks
ruff,black, andpydoclintpass with the pre-commit versions and flags.test_image_cache_eviction(LRU order, in-use and kept images protected, unextracted skipped, orphan tarballs counted),test_pull_pins_image_until_release(pin on pull and on cache hit, eviction blocked until release),test_image_cache_max_bytes_default_and_env. The gVisor-gated remote-pull test asserts no archive is written.