Skip to content

[core][sandbox] Move an image aside before deleting it - #66469

Merged
pcmoritz merged 1 commit into
ray-project:masterfrom
klueska:sandbox-image-cache-removal
Oct 27, 2026
Merged

pcmoritz merged 1 commit into
ray-project:masterfrom
klueska:sandbox-image-cache-removal

Conversation

@klueska

@klueska klueska commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Description

Previously, eviction and re-pulls deleted an image's directory in place. A worker killed midway through deleting it, for example by the OOM killer, can leave the directory with its .extracted marker but without files it needs, such as rootfs.erofs. After an eviction, the next pull takes the image as cached, and every sandbox using it fails with an incomplete cache entry until someone deletes it by hand.

In this PR, eviction and re-pulls atomically rename an image's directory to .deleting.<random> (see _rename_for_deletion) before deleting it, so a crash midway leaves nothing under the image's name, and the next pull pulls it again. Each pull first removes these stale directories, even with eviction disabled, so an interrupted deletion never leaves files behind in the cache. No image's name starts with a dot, so they never match an image.

Related issues

None.

Additional information

We ran test_image_utils.py with TEST_SANDBOX=1, both as root and as an unprivileged user. The new tests cover a simulated crash midway through an eviction and a re-pull, and eviction of images whose names end in .tar or are long.

@klueska
klueska requested a review from a team as a code owner September 24, 2026 18:26

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a custom _force_rmtree function to successfully delete directories with restricted permissions (such as 0555) and improves eviction crash safety by moving directories to a temporary .evicting path before deletion. The feedback suggests extending this atomic rename-and-delete pattern to the re-pull process when replacing an existing target directory, preventing a potential crash from leaving a partially deleted directory under the image's name.

@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Sep 24, 2026
@klueska
klueska force-pushed the sandbox-image-cache-removal branch from 5ff6798 to 2713c79 Compare September 24, 2026 20:38

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@klueska
klueska force-pushed the sandbox-image-cache-removal branch from 2713c79 to b3b5bdd Compare September 25, 2026 08:55

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@klueska
klueska force-pushed the sandbox-image-cache-removal branch 2 times, most recently from d6cd1e0 to d28eba4 Compare September 25, 2026 09:22
@klueska klueska changed the title [core][sandbox] Delete cached image trees reliably [core][sandbox] Delete image caches and sandbox bundles reliably Sep 25, 2026
@klueska
klueska force-pushed the sandbox-image-cache-removal branch from b9c3bef to 8abbad5 Compare September 25, 2026 12:09
@klueska
klueska force-pushed the sandbox-image-cache-removal branch 2 times, most recently from 4c26e69 to 511a6d0 Compare September 27, 2026 21:59
@karticam karticam assigned MengjinYan and Kunchd and unassigned MengjinYan Sep 29, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 13, 2026
@klueska

klueska commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

This issue is not stale. The fix for it is still in review: #65898

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Oct 14, 2026
xyuzh added a commit to xyuzh/ray that referenced this pull request Oct 14, 2026
…'s bundle at once

Review follow-ups:
- A create that failed before its owner file existed, say on a full
  disk, left a bundle that no reclaim would ever take. A failed create
  now deletes its bundle right away, as ray-project#66469 also does.
- A reclaim pass ran inside create_sandbox, so many dead owners, or a
  wedged runsc with its 10 s timeouts, delayed the create. The pass now
  runs in a daemon thread, still at most once a minute per process.

Signed-off-by: xyuzh <[email protected]>
pcmoritz pushed a commit that referenced this pull request Oct 14, 2026
## Description

The image cache is capped at half of the filesystem that holds it,
whatever else is on that disk. The cache shares the disk with sandboxes'
writable overlays, logs and spilled objects. SkyRL's SWE-bench
Multimodal report found nodes with 44 GB free, against about 115 GB that
its 46 images take as EROFS. The cap doesn't account for free space at
all. A disk that fills fails every sandbox on the node, and on
Kubernetes it gets the node's Pods evicted.

This PR keeps a free-space floor under the cache:

- **Eviction also frees space.** Before each pull, eviction now also
removes unused images, least recently extracted first, until the cache's
filesystem has a minimum of free space, besides fitting the size cap.
Images that a running sandbox uses, and the image being pulled, are
never evicted, as before.
- **The floor.** `RAY_SANDBOX_IMAGE_CACHE_MIN_FREE_BYTES` sets it. The
default is a tenth of the filesystem, the level of the kubelet's default
`nodefs.available<10%` eviction threshold. Setting both it and
`RAY_SANDBOX_IMAGE_CACHE_MAX_BYTES` to `0` disables eviction.
- **Tests turn it off.** The sandbox tests set the floor to 0 in
`conftest.py`, so a full runner disk can't change their results. The
laptop I tested on had 2% free.
- **Docs.** The "Bound the image cache" section describes the floor.

## Related issues

None filed. Found with SkyRL's Harbor environment for Ray Sandbox
(skyrl-project/SkyRL#2467).

## Additional information

- **Not a duplicate.** I searched open PRs for "sandbox image cache",
"sandbox disk", "sandbox eviction" and "erofs". None changes when the
cache evicts. #66469 changes how an evicted image's directory is deleted
(rename first) in the same loop. Whichever lands second needs a small
merge.
- **Experiment.** Anyscale staging didn't start clusters on 2026-10-14,
so I ran this as a pod on a CoreWeave Kubernetes cluster:
`rayproject/ray:nightly-py312` (Ray 3.0.0.dev0 1ba2dca), runsc
release-20261005.0, erofs-utils 1.9.4. I pulled `busybox:latest`, which
no sandbox uses, and `alpine:3.20`, pinned as a live sandbox's image.
Then I set the floor one byte above the current free space, as on a disk
that other data has filled, and pulled `debian:bookworm-slim`:

  | | master | This PR |
  | --- | --- | --- |
  | `busybox:latest` (unused) | still cached | evicted (4.5 MB) |
  | `alpine:3.20` (in use) | still cached | still cached |
  | `debian:bookworm-slim` | pulled | pulled |

- **Tests.** In the same pod, with `TEST_SANDBOX=1 pytest
--import-mode=importlib` in `python/ray/experimental/sandbox/tests`:
  - `test_gvisor_backend.py -k netns`: 7 passed.
- `test_image_utils.py test_image_manager.py test_sandbox_config.py
test_sandbox_runtime.py test_gvisor_backend.py -k "not netns"`: 90
passed, 1 skipped. `test_create_sandbox_helper` was deselected because
it starts its own Ray driver.
- The new tests are `test_image_cache_eviction_keeps_a_free_space_floor`
and `test_image_cache_min_free_bytes_default_and_env`. The first works
with no size cap: eviction frees space down to the floor, oldest first,
and keeps an image in use even when the floor can't be met. Both fail on
master.
- Lint: the repo's pre-commit hooks (pre-commit 3.5.0: ruff, black,
pydoclint) pass on commit.
- **Review follow-up (fb71212).** As gemini suggested, the floor's
test asserts the warning that an unparsable setting logs, and a
redundant import is gone.
- AI assistance (Claude Code) was used to prepare this change and run
the tests above.

---------

Signed-off-by: xyuzh <[email protected]>
pcmoritz pushed a commit that referenced this pull request Oct 19, 2026
…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. #66469, #66470
and #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]>
xyuzh added a commit to xyuzh/ray that referenced this pull request Oct 19, 2026
…'s bundle at once

Review follow-ups:
- A create that failed before its owner file existed, say on a full
  disk, left a bundle that no reclaim would ever take. A failed create
  now deletes its bundle right away, as ray-project#66469 also does.
- A reclaim pass ran inside create_sandbox, so many dead owners, or a
  wedged runsc with its 10 s timeouts, delayed the create. The pass now
  runs in a daemon thread, still at most once a minute per process.

Signed-off-by: xyuzh <[email protected]>
pcmoritz added a commit that referenced this pull request Oct 20, 2026
…aves (#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 #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`:

| | #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 #66932 also deletes
dead owners' files for sandboxes with limits, and #66469 also deletes a
failed create's bundle; whichever lands second drops its copy. #66471
and #66470 add launch paths that still use `start_new_session`.
- Builds on #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 #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]>
@klueska
klueska force-pushed the sandbox-image-cache-removal branch from fb3b9ba to 1e8d54f Compare October 26, 2026 14:44

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@klueska
klueska force-pushed the sandbox-image-cache-removal branch from 1e8d54f to a7c44e4 Compare October 26, 2026 17:21

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit a7c44e4. Configure here.

@klueska
klueska force-pushed the sandbox-image-cache-removal branch from a7c44e4 to 95d7e74 Compare October 26, 2026 17:57
@klueska klueska changed the title [core][sandbox] Delete image caches and sandbox bundles reliably [core][sandbox] Move an image aside before deleting it Oct 26, 2026
@klueska
klueska force-pushed the sandbox-image-cache-removal branch from 95d7e74 to 54774b7 Compare October 26, 2026 19:07

@xyuzh xyuzh left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Renaming first is the right fix, and sweeping .deleting.* on every pull also covers the case where eviction is off. One optional suggestion inline.

os.replace(old_tree, tmp_rootfs_dir)
if os.path.exists(target_dir):
shutil.rmtree(target_dir, ignore_errors=True)
shutil.rmtree(_rename_for_deletion(target_dir), ignore_errors=True)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: since the old dir now moves out of the way first, you could swap the new one in before deleting it:

old_dir = _rename_for_deletion(target_dir) if os.path.exists(target_dir) else None
os.replace(tmp_extract_dir, target_dir)
for user in users:
    _mark_image_in_use(target_dir, user)
if old_dir is not None:
    shutil.rmtree(old_dir, ignore_errors=True)

Right now a crash during this rmtree leaves no image under the name (the new test asserts that), so the image this pull just built stays in <name>.tmp.<uuid> and the next pull downloads it again. With the swap first, the image is only missing between two renames instead of for the whole delete, and test_repull_crash_leaves_no_partial_image could assert it's still there after the crash.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, thanks. The new image now takes the name before the old one is deleted. After a simulated crash during the delete, the test checks the new image is still in place and the next pull reuses it rather than downloading it again.

I also moved the delete itself outside the image's lock. Re-pulls and eviction now only rename the old directory aside while holding the lock, and the .deleting.* sweep deletes it once the lock is released, so another pull of the same image doesn't wait for a large rmtree.

@klueska
klueska force-pushed the sandbox-image-cache-removal branch from 54774b7 to 8cd3edc Compare October 27, 2026 09:52
@pcmoritz pcmoritz added the go add ONLY when ready to merge, run all tests label Oct 27, 2026
@pcmoritz
pcmoritz enabled auto-merge (squash) October 27, 2026 18:28
Previously, eviction and re-pulls deleted an image's directory in place.
A worker killed midway, for example by the OOM killer, can leave the
directory with its `.extracted` marker but without files it needs, such
as `rootfs.erofs`. After an eviction, the next pull takes the image as
cached, and every sandbox using it fails with an incomplete cache entry
until someone deletes it by hand.

In this commit, eviction and re-pulls atomically rename the directory to
`.deleting.<random>`, and delete it once the image's lock is released so
other pulls of the image don't wait. A crash midway leaves nothing under
the image's name, and a re-pull puts the new image in place before
deleting the old one. Each pull removes these leftover directories, even
with eviction disabled. No image's name starts with a dot, so they never
match an image.

Signed-off-by: Kevin Klues <[email protected]>
auto-merge was automatically disabled October 27, 2026 19:21

Head branch was pushed to by a user without write access

@klueska
klueska force-pushed the sandbox-image-cache-removal branch from 8cd3edc to d2fa335 Compare October 27, 2026 19:21
@pcmoritz
pcmoritz enabled auto-merge (squash) October 27, 2026 19:25
@pcmoritz
pcmoritz merged commit 253db62 into ray-project:master Oct 27, 2026
7 checks passed
justinyeh1995 pushed a commit to justinyeh1995/ray that referenced this pull request Oct 28, 2026
…6469)

## Description

Previously, eviction and re-pulls deleted an image's directory in place.
A worker killed midway through deleting it, for example by the OOM
killer, can leave the directory with its `.extracted` marker but without
files it needs, such as `rootfs.erofs`. After an eviction, the next pull
takes the image as cached, and every sandbox using it fails with an
incomplete cache entry until someone deletes it by hand.

In this PR, eviction and re-pulls atomically rename an image's directory
to `.deleting.<random>` (see `_rename_for_deletion`) before deleting it,
so a crash midway leaves nothing under the image's name, and the next
pull pulls it again. Each pull first removes these stale directories,
even with eviction disabled, so an interrupted deletion never leaves
files behind in the cache. No image's name starts with a dot, so they
never match an image.

## Related issues

None.

## Additional information

We ran `test_image_utils.py` with `TEST_SANDBOX=1`, both as root and as
an unprivileged user. The new tests cover a simulated crash midway
through an eviction and a re-pull, and eviction of images whose names
end in `.tar` or are long.

Signed-off-by: Kevin Klues <[email protected]>
pcmoritz pushed a commit that referenced this pull request Oct 29, 2026
…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]>
xyuzh added a commit to xyuzh/ray that referenced this pull request Nov 2, 2026
- 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]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 2, 2026
Resubmit the final upstream version of PR ray-project#66469 (253db62), previously ported on local main as da2f1c4.

Use short deletion tombstones, release image locks before cleanup, and install replacement images before deleting the old cache.

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
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 2, 2026
…oject#67025)

## Description

The image cache is capped at half of the filesystem that holds it,
whatever else is on that disk. The cache shares the disk with sandboxes'
writable overlays, logs and spilled objects. SkyRL's SWE-bench
Multimodal report found nodes with 44 GB free, against about 115 GB that
its 46 images take as EROFS. The cap doesn't account for free space at
all. A disk that fills fails every sandbox on the node, and on
Kubernetes it gets the node's Pods evicted.

This PR keeps a free-space floor under the cache:

- **Eviction also frees space.** Before each pull, eviction now also
removes unused images, least recently extracted first, until the cache's
filesystem has a minimum of free space, besides fitting the size cap.
Images that a running sandbox uses, and the image being pulled, are
never evicted, as before.
- **The floor.** `RAY_SANDBOX_IMAGE_CACHE_MIN_FREE_BYTES` sets it. The
default is a tenth of the filesystem, the level of the kubelet's default
`nodefs.available<10%` eviction threshold. Setting both it and
`RAY_SANDBOX_IMAGE_CACHE_MAX_BYTES` to `0` disables eviction.
- **Tests turn it off.** The sandbox tests set the floor to 0 in
`conftest.py`, so a full runner disk can't change their results. The
laptop I tested on had 2% free.
- **Docs.** The "Bound the image cache" section describes the floor.

## Related issues

None filed. Found with SkyRL's Harbor environment for Ray Sandbox
(skyrl-project/SkyRL#2467).

## Additional information

- **Not a duplicate.** I searched open PRs for "sandbox image cache",
"sandbox disk", "sandbox eviction" and "erofs". None changes when the
cache evicts. ray-project#66469 changes how an evicted image's directory is deleted
(rename first) in the same loop. Whichever lands second needs a small
merge.
- **Experiment.** Anyscale staging didn't start clusters on 2026-10-14,
so I ran this as a pod on a CoreWeave Kubernetes cluster:
`rayproject/ray:nightly-py312` (Ray 3.0.0.dev0 1ba2dca), runsc
release-20261005.0, erofs-utils 1.9.4. I pulled `busybox:latest`, which
no sandbox uses, and `alpine:3.20`, pinned as a live sandbox's image.
Then I set the floor one byte above the current free space, as on a disk
that other data has filled, and pulled `debian:bookworm-slim`:

  | | master | This PR |
  | --- | --- | --- |
  | `busybox:latest` (unused) | still cached | evicted (4.5 MB) |
  | `alpine:3.20` (in use) | still cached | still cached |
  | `debian:bookworm-slim` | pulled | pulled |

- **Tests.** In the same pod, with `TEST_SANDBOX=1 pytest
--import-mode=importlib` in `python/ray/experimental/sandbox/tests`:
  - `test_gvisor_backend.py -k netns`: 7 passed.
- `test_image_utils.py test_image_manager.py test_sandbox_config.py
test_sandbox_runtime.py test_gvisor_backend.py -k "not netns"`: 90
passed, 1 skipped. `test_create_sandbox_helper` was deselected because
it starts its own Ray driver.
- The new tests are `test_image_cache_eviction_keeps_a_free_space_floor`
and `test_image_cache_min_free_bytes_default_and_env`. The first works
with no size cap: eviction frees space down to the floor, oldest first,
and keeps an image in use even when the floor can't be met. Both fail on
master.
- Lint: the repo's pre-commit hooks (pre-commit 3.5.0: ruff, black,
pydoclint) pass on commit.
- **Review follow-up (fb71212).** As gemini suggested, the floor's
test asserts the warning that an unparsable setting logs, and a
redundant import is gone.
- AI assistance (Claude Code) was used to prepare this change and run
the tests above.

---------

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
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 2, 2026
… once (ray-project#67023)

## Description

Cold pulls of large images are slow. A SWE-bench image with 1.1 GiB of
layers took 57-64 s to pull on a CoreWeave node, and two things wasted
most of that time:

- Layers were downloaded one at a time, and each was extracted only
after its download finished.
- Each layer was decompressed twice: `tar.getmembers()` reads the whole
gzip stream, then `extractfile()` seeks back and decompresses it again.

This PR downloads up to three layers at once (Docker's default) into
temporary files and extracts them in manifest order as they arrive, so
whiteouts and overrides apply exactly as before. A failed download fails
the pull right away. The other downloads stop at their next read, and
ones that haven't started never connect.

`extract_tar_layer` iterates the archive instead of calling
`getmembers()` first, so it reads each layer once. It keeps the `r:*`
reader rather than stream mode (`r|*`), because only `r:*` checks where
a gzip stream ends. That check catches a layer download the registry
closed early.

Same image, two cold pulls each, alternating:

| | master | this PR |
| --- | --- | --- |
| Whole pull | 63.7 s / 56.7 s | 37.6 s / 37.8 s |
| Download and extraction | 38.1 s / 33.0 s | 18.6 s / 16.8 s |

This PR doesn't touch the EROFS build. It took 17-24 s in these runs,
and both sides built the same 2.92 GiB image.

## Related issues

None filed. Found while running SkyRL's SWE-bench Multimodal tasks on
Ray Sandbox (skyrl-project/SkyRL#2467).

## Additional information

- Not a duplicate: no open PR changes how layers are fetched or read.
ray-project#66469, ray-project#66985 and ray-project#67026 edit other parts of `image_utils.py`.
- Tests: four new tests. Three layer downloads must run at once and
still apply in order. A failed layer must fail the pull within 5 s and
close the other downloads. A layer download cut short on a member
boundary must fail the pull. A 2 MiB layer must be read once. The first,
second and fourth fail on master, and the third fails with stream mode.
- 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"`: 93 passed, 1 skipped. `-k netns`: 7 passed. 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
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 2, 2026
…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
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 2, 2026
…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
pcmoritz added a commit that referenced this pull request Nov 3, 2026
## 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]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 9, 2026
…#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community core Issues that should be addressed in Ray Core go add ONLY when ready to merge, run all tests unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants