Skip to content

[core][sandbox] Cache images as EROFS root filesystems - #65992

Merged
pcmoritz merged 1 commit into
ray-project:masterfrom
xyuzh:sandbox-erofs-rootfs
Sep 22, 2026
Merged

pcmoritz merged 1 commit into
ray-project:masterfrom
xyuzh:sandbox-erofs-rootfs

Conversation

@xyuzh

@xyuzh xyuzh commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

Description

Rootless gVisor serves each image's extracted directory through the gofer, so every file inside a sandbox reads as the worker's uid (root), image-baked ownership (postfix's 0700 uid-101 spool, mailman's uid-38 data) flattens away, and chown to another uid fails. Fixing that on the host needs subordinate id ranges and setuid helpers (#65823), which many environments can't provide.

This caches each image as an EROFS root filesystem instead. gVisor mounts it inside the Sentry, so uids and gids live in the image and in the private overlay upper layer and never need a host representation: files keep their real owners and chown works for any uid, from an unprivileged worker, with no id mapping and no user namespace of ours.

  • Build without root. Extraction records each layer's non-root owners (whiteout-aware; a later root-owned layer drops the entry; hardlinks are recorded under their own name so the re-pack keeps the owner whichever name it emits first), the tree is re-packed as a tar whose headers carry them, and mkfs.erofs --tar (erofs-utils 1.7+) turns that into the image with -E^inline_data (gVisor's EROFS reader maps the image and only handles the flat-plain layout) and 4 KiB blocks. The extracted tree is deleted afterwards; the cache holds one file per image plus the image config.
  • Mount via annotations. The bundle gets dev.gvisor.spec.rootfs.source/type/overlay; the self overlay is anchored at a per-sandbox directory, and runsc no longer gets --overlay2. readonly=True keeps its semantics because the standard mount points (/proc, /sys, /dev, /dev/pts, /dev/shm, /run, /tmp, /etc/{resolv.conf,hosts,hostname}) are seeded into the image at build time; runsc applies no rootfs overlay to a read-only root and can't create mount points in an immutable image.
  • Paths resolve inside the tree. Extraction resolves each member's parent with the extracted tree as / (an absolute symlink target restarts at the root, .. never climbs above it), so a member under a symlinked directory (UsrMerge's bin -> usr/bin, Debian's /var/run -> /run) lands where the image means it, its owner is recorded under that canonical path (where the re-pack finds it), and whiteouts delete through the same resolution. Before, a relative link left the owner keyed under the link path and the built image had the file as 0:0; an absolute link dropped the member. The /tmp and mount-point seeding use the same resolver, so an image whose etc, dev or tmp links to a host directory gets its seeds inside the tree, never on the host; created files use O_NOFOLLOW, and a hardlink to a symlink links the symlink itself.
  • EROFS is the only layout. Per review, the extracted-directory layout (and its RAY_SANDBOX_ROOTFS=dir switch) is gone, so mkfs.erofs 1.7+ is a hard requirement on worker nodes next to runsc. A pull checks for it before downloading anything and fails with an error naming what to install. Ubuntu 24.04 and Debian 13 package a new enough erofs-utils; Ubuntu 22.04's is 1.4 and predates --tar, so nodes built on today's rayproject/ray images need it built from source (the docs carry the recipe). The .extracted marker moves to format 3, so a cache left by an earlier Ray re-pulls once; sandboxes still running on an old extracted tree keep it (the tree moves into the rebuilt entry, since a rename leaves the gofer's open root fd alone) and it is deleted on a later pull once no sandbox uses the image.
  • CI. The sandbox tests boot real sandboxes with TEST_SANDBOX=1, so the corebuild image now builds erofs-utils v1.9.4 from source (pinned to the tag's commit). Unit tests build images through a fake mkfs.erofs from conftest.py and inspect the resulting tar, so they run anywhere.

One known gap. readonly=True with an explicit workdir runs on a private writable overlay (warned at spec time and documented): runsc drops the requested rootfs overlay for read-only roots, and an immutable image can't grow the workdir mount point. The clean fix is a small upstream change to runsc (initGoferConfs) to honor an explicitly requested rootfs overlay on a read-only root; mountAll already makes the root writable only while creating mount points. The test for the intended behavior is skipped with that reason and a new test pins today's behavior.

Together with a Sentry-side network adapter that proxies to the host without unshare --net, this leaves no host requirements beyond runsc and mkfs.erofs.

Related issues

Supersedes #65823 (closed). Related to #65820 and #66004.

Merge order: this PR first. #65942 (per-exec user), #65633 (HTTP API), and #65839 (gRPC facade) are stacked on this branch in that order; each carries the commits below it until those merge, so their diffs on GitHub include this commit until it lands. #65942 resolves exec(user=<name>) inside the running sandbox, so it works unchanged on this cache layout.

Additional information

Validated on x86_64 as well: an Anyscale staging cluster (anyscale/ray:2.58.0-py312 + runsc release-20260817 + erofs-utils 1.9.4, three 8-CPU nodes) running Terminal-Bench 2.1 with the oracle agent through the ray.experimental.sandbox Python API. The mailman task, which depends on image-baked postfix/mailman file ownership surviving inside the sandbox, scores 0 on the directory layout and 1.0 with this change; the other 88 tasks are unchanged (89 trials, 0 errored). That is the exact ownership scenario this PR exists for, on a real cluster rather than a privileged dev container.

Measured in a privileged rayproject/ray:nightly-py312 container on arm64 (erofs-utils 1.9.4 built from source, runsc release-20260817):

image pull + build rootfs.erofs extracted tree
python:3.10-slim 7.1 s 156.8 MB 147 MB
ubuntu:24.04 4.6 s 108.0 MB 104 MB

mkfs.erofs itself takes about 2 s for python:3.10-slim; -E^inline_data costs roughly 6% over the tree size, and the tree is gone afterwards, so the cache shrinks. A cache hit no longer walks an extracted tree for eviction accounting either (one file per image), which removes the ~60 ms per pull_image that @OneSizeFitsQuorum profiled on the directory layout.

Runtime tests in that container as the unprivileged ray user with TEST_SANDBOX=1 (test_gvisor_backend.py, test_image_utils.py, test_image_manager.py): 79 passed, 1 skipped (the readonly + workdir case above); the ray.init smoke test was run on its own. The run started from the cache the directory layout had left on that node, which the first pull rebuilt to the format-3 marker. They cover image-baked ownership from a local tar (101:0:700, 101:104:2710 setgid dir, a setuid tool), root traversing another user's 0700 directory, chown to arbitrary uids and chown -R with setgid inheritance, a readonly EROFS root with writable /tmp, network="host" egress, the network="public" netns suite, and the existing lifecycle, overlay isolation, and workdir suites. Unit tests cover ownership recording across layers including hardlinks, the owner-restoring tar filter, the build through a fake mkfs.erofs, the missing/too-old mkfs.erofs error, the format-3 re-pull with and without running sandboxes, and the EROFS OCI spec.

@xyuzh
xyuzh force-pushed the sandbox-erofs-rootfs branch 2 times, most recently from 442a6b8 to d5e933e Compare September 9, 2026 22:13
@xyuzh
xyuzh marked this pull request as ready for review September 10, 2026 03:16
@xyuzh
xyuzh requested review from a team as code owners September 10, 2026 03:16

@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 support for caching container images as EROFS files when mkfs.erofs is available, allowing gVisor to mount the image directly and preserve file ownership without host privileges. Feedback on the changes suggests critical improvements, including tracking hard link ownership to prevent inode corruption, checking for active users before replacing directories to avoid disrupting running sandboxes, and adding timeouts to subprocess calls to prevent hangs. Additionally, optimization of path normalization in whiteout handling and enhancing the fallback test to write to a rootfs path were recommended.

Comment on lines +397 to +402
if ownership is not None and rel != "." and not member.islnk():
if member.uid or member.gid:
ownership[rel] = (member.uid, member.gid)
else:
# A later layer re-shipping the path as root wins.
ownership.pop(rel, None)

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.

high

Hard links share the same inode as their target file. If we do not record the hard link's path in the ownership map, _owner_filter will not find it and will default its UID/GID to 0:0 (root) in the tarball. When mkfs.erofs builds the image, this inconsistent ownership on the same inode can corrupt or reset the target file's ownership to root. Copying the target's recorded ownership to the hard link's path prevents this issue.

            if ownership is not None and rel != ".":
                if member.islnk():
                    target_rel = os.path.normpath(member.linkname.lstrip("/"))
                    if target_rel in ownership:
                        ownership[rel] = ownership[target_rel]
                elif member.uid or member.gid:
                    ownership[rel] = (member.uid, member.gid)
                else:
                    # A later layer re-shipping the path as root wins.
                    ownership.pop(rel, None)

Comment on lines 771 to 777
# A cache from another layout re-pulls once.
if marker_current:
if os.path.isfile(image):
if os.path.getmtime(marker_path) >= os.path.getmtime(image):
return _finish()
else:
return _finish()

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.

high

If there are active sandboxes running on the image, deleting and replacing target_dir during a layout transition or re-extraction will immediately break those running sandboxes with I/O errors (e.g., ESTALE or ENOENT). Reusing the existing layout when there are active users (_has_users(target_dir)) prevents runtime disruption, deferring the transition until all active sandboxes exit.

Suggested change
# A cache from another layout re-pulls once.
if marker_current:
if os.path.isfile(image):
if os.path.getmtime(marker_path) >= os.path.getmtime(image):
return _finish()
else:
return _finish()
# A cache from another layout re-pulls once, unless there are active users.
if marker_current or _has_users(target_dir):
if os.path.isfile(image):
if os.path.getmtime(marker_path) >= os.path.getmtime(image):
return _finish()
else:
return _finish()

Comment on lines +298 to +305
if basename == ".wh..wh..opq":
if ownership is not None and dirname:
for key in [
k
for k in ownership
if k.startswith(os.path.normpath(dirname) + "/")
]:
del ownership[key]

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.

medium

Evaluating os.path.normpath(dirname) + "/" inside the list comprehension is inefficient because it runs for every single key in the ownership dictionary. Since ownership can contain thousands of files, computing this prefix once outside the comprehension significantly improves performance.

            if basename == ".wh..wh..opq":
                if ownership is not None and dirname:
                    prefix = os.path.normpath(dirname) + "/"
                    for key in [k for k in ownership if k.startswith(prefix)]:
                        del ownership[key]

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.

I would add this, the new code also reads a little nicer than the existing one

Comment on lines +425 to +428
try:
res = subprocess.run([path, "--help"], capture_output=True, text=True)
except OSError:
return None

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.

medium

Executing subprocess.run without a timeout can cause the worker thread to hang indefinitely if the subprocess blocks or encounters an environmental issue. Adding a short timeout and handling subprocess.TimeoutExpired ensures robustness.

Suggested change
try:
res = subprocess.run([path, "--help"], capture_output=True, text=True)
except OSError:
return None
try:
res = subprocess.run([path, "--help"], capture_output=True, text=True, timeout=5)
except (OSError, subprocess.TimeoutExpired):
return None

Comment on lines +529 to +533
res = subprocess.run(
[mkfs, "--tar=f", "-b4096", "-E^inline_data", out_path, flat_tar],
capture_output=True,
text=True,
)

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.

medium

Executing subprocess.run without a timeout can cause the worker thread to hang indefinitely if mkfs.erofs blocks. Adding a reasonable timeout prevents infinite hangs.

Suggested change
res = subprocess.run(
[mkfs, "--tar=f", "-b4096", "-E^inline_data", out_path, flat_tar],
capture_output=True,
text=True,
)
res = subprocess.run(
[mkfs, "--tar=f", "-b4096", "-E^inline_data", out_path, flat_tar],
capture_output=True,
text=True,
timeout=300,
)

Comment on lines +277 to +281
res = backend.exec_command(
sb, "echo ws_ok > /workspace/ws.txt && cat /workspace/ws.txt", timeout=30
)
assert res.exit_code == 0, res.stderr
assert "ws_ok" in res.stdout

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.

medium

The test test_readonly_rootfs_erofs_fallback is intended to verify that rootfs writes are discarded rather than rejected under the fallback behavior. However, it currently only writes to /workspace, which is already writable by default. Writing to a rootfs path (like /test_fallback.txt) is necessary to actually validate that the rootfs fallback writable overlay is active and working.

Suggested change
res = backend.exec_command(
sb, "echo ws_ok > /workspace/ws.txt && cat /workspace/ws.txt", timeout=30
)
assert res.exit_code == 0, res.stderr
assert "ws_ok" in res.stdout
res = backend.exec_command(
sb, "echo ws_ok > /workspace/ws.txt && echo root_ok > /test_fallback.txt && cat /workspace/ws.txt /test_fallback.txt", timeout=30
)
assert res.exit_code == 0, res.stderr
assert "ws_ok" in res.stdout
assert "root_ok" in res.stdout

@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.

if res.returncode != 0:
raise SandboxCreationError(
f"mkfs.erofs failed: {(res.stderr or res.stdout).strip()[-500:]}"
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Build error masks real failure

Low Severity

build_erofs_image assigns res only after the tar is written. If tar.add fails, the finally still runs and the following res.returncode check raises UnboundLocalError, hiding the original error such as a full disk.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d5e933e. Configure here.

@xyuzh

xyuzh commented Sep 14, 2026 •

Copy link
Copy Markdown
Member Author

Pushed e9973cd: EROFS is now the only layout, following the discussion about standardizing on it. Changes since d5e933e:

  • The extracted-directory code path and RAY_SANDBOX_ROOTFS=dir are gone. mkfs.erofs 1.7+ is a hard requirement next to runsc; a pull checks for it before downloading anything and fails with an error naming what to install. The docs list it as required (Ubuntu 24.04 and Debian 13 package it; Ubuntu 22.04 needs a source build, recipe included).
  • .extracted marker format 3, so a directory-layout cache from an earlier Ray re-pulls once. Sandboxes still running on the old tree keep it: the tree moves into the rebuilt entry (a rename leaves the gofer's open root fd alone) and is removed on a later pull once no sandbox uses the image. That also resolves the "re-extract deletes live rootfs" finding from both bots.
  • Hardlinks are recorded under their own name in the ownership map (the hardlink-ownership finding); a test covers a link name that sorts before its target.
  • get_rootfs_path is gone from both image managers and the backend asks the manager nothing layout-specific anymore (the custom-manager AttributeError finding). runsc never gets --overlay2.
  • The registry download and layer flattening moved into _extract_image_layers; the runtime tests use it to build their owned-busybox tar instead of forcing a directory cache.
  • CI: ci/docker/core.build.Dockerfile builds erofs-utils v1.9.4 from source (pinned to the tag's commit), since the sandbox job boots real sandboxes with TEST_SANDBOX=1 on Ubuntu 22.04. Unit tests build images through a fake mkfs.erofs fixture in conftest.py and inspect the resulting tar, so they need neither erofs-utils nor runsc.
  • The --help probe now has a timeout. Not taken: a timeout on the mkfs.erofs build itself (it only reads a local tar, and a fixed bound would kill legitimate large-image builds), and the UnboundLocalError finding (an exception in tar.add propagates through the finally before res is read).
  • [core][sandbox] Support per-exec user and appending writes in the gVisor backend #65942 now resolves exec(user=<name>) inside the running sandbox, so the passwd/group snapshot this branch kept for it is gone too.

Runtime suite in the privileged rayproject/ray:nightly-py312 container as the unprivileged ray user (erofs-utils 1.9.4, runsc release-20260817): 79 passed, 1 skipped (readonly + explicit workdir), starting from a directory-layout cache that the first pull rebuilt to format 3.

@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.

with open(path, "a", encoding="utf-8"):
pass
except OSError:
pass

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Mountpoint seeding follows image symlinks

Low Severity

_seed_mountpoints uses os.path.lexists on the final path, then os.makedirs and open, which follow intermediate symlinks. An image can point etc or dev at a host path and have the seed step create resolv.conf, hosts, hostname, dev/pts, or dev/shm outside the extract tree.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 331345e. Configure here.

@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.

@xyuzh
xyuzh force-pushed the sandbox-erofs-rootfs branch from 3d07508 to e9973cd Compare September 16, 2026 03:17
@xyuzh

xyuzh commented Sep 16, 2026

Copy link
Copy Markdown
Member Author

CI note: the corebuild-py3.10 image build failed with exit code 141 (SIGPIPE) in the erofs-utils step, which left every core test job in waiting_failed. The build and install themselves succeeded; the self-check mkfs.erofs --help 2>&1 | grep -q -- --tar was the problem: grep -q exits at the first match and closes the pipe while mkfs.erofs is still writing its help text, and the block runs under set -o pipefail, so the SIGPIPE became a step failure. e9973cd captures the help text into a variable and tests it instead, so the whole output is read. The windowsbuild failure in the same run is unrelated: that agent failed while installing the wanda binary before touching the repo. The stack above (#65942, #65633, #65839) is rebased onto this head.

@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.

users = []
old_tree = os.path.join(target_dir, "rootfs")
if users and os.path.isdir(old_tree):
os.replace(old_tree, tmp_rootfs_dir)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Extracted tree rmtree misses non-writable dirs

Medium Severity

Extraction applies archived directory modes before deleting the temporary tree, then shutil.rmtree is called with ignore_errors=True. A non-empty 0500/0555 directory cannot be removed by its owner, so rootfs/ is left in the cache. A later re-pull that still has users then fails on os.replace because the destination tree is not empty, so new sandboxes cannot start until every old user of that image exits.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit e9973cd. Configure here.

@pcmoritz pcmoritz 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.

This approach looks good to me. It is worth trying if the alternative approach of using mkfs.erofs to convert each layer separately and then merging them with mkfs.erof is simpler and faster (it likely is). We can try that as a follow up PR. It would work like this:

mkfs.erofs --tar=f --aufs --ovlfs-strip=0 layer0.erofs layer0.tar
mkfs.erofs --tar=f --aufs --ovlfs-strip=0 layer1.erofs layer1.tar

mkfs.erofs --clean=data --ovlfs-strip=1 rootfs.erofs \
    layer0.erofs layer1.erofs

And should handle things like whiteouts and ownership automatically.

@pcmoritz pcmoritz added the go add ONLY when ready to merge, run all tests label Sep 21, 2026
@xyuzh
xyuzh force-pushed the sandbox-erofs-rootfs branch from e9973cd to dec934c Compare September 21, 2026 22:10
uv pip uninstall --system ray

EOF

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

ill make a new image for the sandbox tests in the near future but for now this works

Rootless gVisor served each image's extracted directory through the
gofer, so every file inside the sandbox read as the worker's uid (root),
image-baked ownership (postfix's 0700 uid-101 spool, mailman's uid-38
data) flattened away, and chown to another uid failed. Fixing that on the
host needs subordinate id ranges and setuid helpers (ray-project#65823).

Cache each image as an EROFS file instead. gVisor mounts it inside the
Sentry, so uids and gids live in the image and the private overlay upper
layer and never need a host representation: files keep their real owners
and chown works for any uid, from an unprivileged worker, with no id
mapping and no user namespace. The image is built without root:
extraction records each layer's non-root owners (whiteout-aware, and
hardlinks under their own name), the tree is re-packed as a tar whose
headers carry them, and `mkfs.erofs --tar` (erofs-utils 1.7+) turns that
into the image with `-E^inline_data` (gVisor reads only the flat-plain
layout) and 4 KiB blocks. The rootfs then comes from the
`dev.gvisor.spec.rootfs.*` annotations with a "self" overlay anchored at a
per-sandbox directory, so runsc gets no `--overlay2`. The cache holds one
file per image instead of a tree.

EROFS is the only layout: the extracted-directory code path is gone, so
mkfs.erofs 1.7+ is a hard requirement on worker nodes next to runsc, and a
pull checks for it before downloading anything. The `.extracted` marker
moves to format 3, so a cache left by an earlier Ray re-pulls once;
sandboxes still running on an old extracted tree keep it (the tree moves
into the rebuilt entry, a rename leaving the gofer's open root fd alone)
and it goes on a later pull once no sandbox uses the image. The CI
corebuild image builds erofs-utils v1.9.4 from source, since Ubuntu 22.04
packages 1.4 and the sandbox tests boot real sandboxes.

runsc applies no rootfs overlay to a read-only root and cannot create
mount points in an immutable image, so the standard mount points are
seeded at build time and readonly=True keeps its semantics; the one gap
is readonly=True with an explicit workdir, which runs on a private
writable overlay (warned and documented) until runsc honors a requested
overlay on a read-only root.

Extraction resolves each member's parent inside the tree, with the tree
as `/`: an absolute symlink target restarts at the root and `..` never
climbs above it. A member under a symlinked directory (UsrMerge's `bin ->
usr/bin`, Debian's `/var/run -> /run`) so lands where the image means it,
its owner is recorded under that canonical path, which is where the
re-pack finds it, and whiteouts delete through the same resolution;
before, a relative link left the owner keyed under the link path and the
built image had the file as root, and an absolute link dropped the member
altogether. The `/tmp` and mount-point seeding use the same resolver, so
an image whose `etc`, `dev` or `tmp` links to a host directory gets its
seeds inside the tree, never on the host; seeded and extracted files are
created with O_NOFOLLOW, and a hardlink to a symlink links the symlink.

Signed-off-by: xyuzh <[email protected]>
@xyuzh
xyuzh force-pushed the sandbox-erofs-rootfs branch from dec934c to 47fe3f9 Compare September 22, 2026 04:13

@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 using default effort and found 1 potential issue.

There are 3 total unresolved issues (including 2 from previous reviews).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 47fe3f9. Configure here.

shutil.rmtree(target_dir, ignore_errors=True)
os.replace(tmp_extract_dir, target_dir)
for user in users:
_mark_image_in_use(target_dir, user)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Re-pull can resurrect released image pins

Medium Severity

A format-upgrade or local-tar re-pull snapshots .users, replaces the cache directory, then re-creates every pin. _release_image_use does not take the image lock, so a sandbox that exits during that window is written back as a live user. The leaked pin keeps the image (and any leftover rootfs/ tree) unevictable until the node restarts.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 47fe3f9. Configure here.

@pcmoritz
pcmoritz merged commit 973bafe into ray-project:master Sep 22, 2026
6 checks passed
owenowenisme pushed a commit to owenowenisme/ray that referenced this pull request Sep 23, 2026
…5992)

## Description

Rootless gVisor serves each image's extracted directory through the
gofer, so every file inside a sandbox reads as the worker's uid (root),
image-baked ownership (postfix's `0700` uid-101 spool, mailman's uid-38
data) flattens away, and `chown` to another uid fails. Fixing that on
the host needs subordinate id ranges and setuid helpers (ray-project#65823), which
many environments can't provide.

This caches each image as an **EROFS root filesystem** instead. gVisor
mounts it inside the Sentry, so uids and gids live in the image and in
the private overlay upper layer and never need a host representation:
files keep their real owners and `chown` works for any uid, from an
unprivileged worker, with no id mapping and no user namespace of ours.

- **Build without root.** Extraction records each layer's non-root
owners (whiteout-aware; a later root-owned layer drops the entry;
hardlinks are recorded under their own name so the re-pack keeps the
owner whichever name it emits first), the tree is re-packed as a tar
whose headers carry them, and `mkfs.erofs --tar` (erofs-utils 1.7+)
turns that into the image with `-E^inline_data` (gVisor's EROFS reader
maps the image and only handles the flat-plain layout) and 4 KiB blocks.
The extracted tree is deleted afterwards; the cache holds one file per
image plus the image config.
- **Mount via annotations.** The bundle gets
`dev.gvisor.spec.rootfs.source/type/overlay`; the `self` overlay is
anchored at a per-sandbox directory, and runsc no longer gets
`--overlay2`. `readonly=True` keeps its semantics because the standard
mount points (`/proc`, `/sys`, `/dev`, `/dev/pts`, `/dev/shm`, `/run`,
`/tmp`, `/etc/{resolv.conf,hosts,hostname}`) are seeded into the image
at build time; runsc applies no rootfs overlay to a read-only root and
can't create mount points in an immutable image.
- **Paths resolve inside the tree.** Extraction resolves each member's
parent with the extracted tree as `/` (an absolute symlink target
restarts at the root, `..` never climbs above it), so a member under a
symlinked directory (UsrMerge's `bin -> usr/bin`, Debian's `/var/run ->
/run`) lands where the image means it, its owner is recorded under that
canonical path (where the re-pack finds it), and whiteouts delete
through the same resolution. Before, a relative link left the owner
keyed under the link path and the built image had the file as `0:0`; an
absolute link dropped the member. The `/tmp` and mount-point seeding use
the same resolver, so an image whose `etc`, `dev` or `tmp` links to a
host directory gets its seeds inside the tree, never on the host;
created files use `O_NOFOLLOW`, and a hardlink to a symlink links the
symlink itself.
- **EROFS is the only layout.** Per review, the extracted-directory
layout (and its `RAY_SANDBOX_ROOTFS=dir` switch) is gone, so
`mkfs.erofs` 1.7+ is a hard requirement on worker nodes next to `runsc`.
A pull checks for it before downloading anything and fails with an error
naming what to install. Ubuntu 24.04 and Debian 13 package a new enough
erofs-utils; Ubuntu 22.04's is 1.4 and predates `--tar`, so nodes built
on today's `rayproject/ray` images need it built from source (the docs
carry the recipe). The `.extracted` marker moves to format 3, so a cache
left by an earlier Ray re-pulls once; sandboxes still running on an old
extracted tree keep it (the tree moves into the rebuilt entry, since a
rename leaves the gofer's open root fd alone) and it is deleted on a
later pull once no sandbox uses the image.
- **CI.** The sandbox tests boot real sandboxes with `TEST_SANDBOX=1`,
so the `corebuild` image now builds erofs-utils v1.9.4 from source
(pinned to the tag's commit). Unit tests build images through a fake
`mkfs.erofs` from `conftest.py` and inspect the resulting tar, so they
run anywhere.

**One known gap.** `readonly=True` with an explicit `workdir` runs on a
private writable overlay (warned at spec time and documented): runsc
drops the requested rootfs overlay for read-only roots, and an immutable
image can't grow the workdir mount point. The clean fix is a small
upstream change to runsc (`initGoferConfs`) to honor an explicitly
requested rootfs overlay on a read-only root; `mountAll` already makes
the root writable only while creating mount points. The test for the
intended behavior is skipped with that reason and a new test pins
today's behavior.

Together with a Sentry-side network adapter that proxies to the host
without `unshare --net`, this leaves no host requirements beyond `runsc`
and `mkfs.erofs`.

## Related issues

Supersedes ray-project#65823 (closed). Related to ray-project#65820 and ray-project#66004.

**Merge order: this PR first.** ray-project#65942 (per-exec user), ray-project#65633 (HTTP
API), and ray-project#65839 (gRPC facade) are stacked on this branch in that order;
each carries the commits below it until those merge, so their diffs on
GitHub include this commit until it lands. ray-project#65942 resolves
`exec(user=<name>)` inside the running sandbox, so it works unchanged on
this cache layout.

## Additional information

Validated on x86_64 as well: an Anyscale staging cluster
(`anyscale/ray:2.58.0-py312` + runsc release-20260817 + erofs-utils
1.9.4, three 8-CPU nodes) running Terminal-Bench 2.1 with the oracle
agent through the `ray.experimental.sandbox` Python API. The `mailman`
task, which depends on image-baked postfix/mailman file ownership
surviving inside the sandbox, scores 0 on the directory layout and 1.0
with this change; the other 88 tasks are unchanged (89 trials, 0
errored). That is the exact ownership scenario this PR exists for, on a
real cluster rather than a privileged dev container.

Measured in a privileged `rayproject/ray:nightly-py312` container on
arm64 (erofs-utils 1.9.4 built from source, runsc release-20260817):

| image | pull + build | `rootfs.erofs` | extracted tree |
| --- | --- | --- | --- |
| python:3.10-slim | 7.1 s | 156.8 MB | 147 MB |
| ubuntu:24.04 | 4.6 s | 108.0 MB | 104 MB |

`mkfs.erofs` itself takes about 2 s for python:3.10-slim;
`-E^inline_data` costs roughly 6% over the tree size, and the tree is
gone afterwards, so the cache shrinks. A cache hit no longer walks an
extracted tree for eviction accounting either (one file per image),
which removes the ~60 ms per `pull_image` that @OneSizeFitsQuorum
profiled on the directory layout.

Runtime tests in that container as the unprivileged `ray` user with
`TEST_SANDBOX=1` (`test_gvisor_backend.py`, `test_image_utils.py`,
`test_image_manager.py`): 79 passed, 1 skipped (the readonly + workdir
case above); the `ray.init` smoke test was run on its own. The run
started from the cache the directory layout had left on that node, which
the first pull rebuilt to the format-3 marker. They cover image-baked
ownership from a local tar (`101:0:700`, `101:104:2710` setgid dir, a
setuid tool), root traversing another user's `0700` directory, `chown`
to arbitrary uids and `chown -R` with setgid inheritance, a readonly
EROFS root with writable `/tmp`, `network="host"` egress, the
`network="public"` netns suite, and the existing lifecycle, overlay
isolation, and workdir suites. Unit tests cover ownership recording
across layers including hardlinks, the owner-restoring tar filter, the
build through a fake `mkfs.erofs`, the missing/too-old `mkfs.erofs`
error, the format-3 re-pull with and without running sandboxes, and the
EROFS OCI spec.

Signed-off-by: xyuzh <[email protected]>
pcmoritz pushed a commit that referenced this pull request Sep 23, 2026
…sor backend (#65942)

## Description

Two small additions to the gVisor backend and `SandboxRuntime`, split
out of #65820 at reviewer request so that PR stays about network
namespaces:

- **Per-exec user.** `exec(..., user=)` runs a command as a numeric uid,
`uid:gid`, or a user (and optionally group) name. runsc only accepts
numeric ids, so names resolve against the `/etc/passwd` and `/etc/group`
**inside the running sandbox**, read through a first exec (`cat`) before
the real command runs. That covers users the image ships and users added
since (`adduser` in the sandbox), and it needs no host copy of the root
filesystem, so it works the same on the EROFS cache of #65992. A named
user with no explicit group gets its login group; numeric ids never
touch the sandbox.
- **Appending writes.** `write_file(..., append=True)` extends a file
instead of truncating it, so callers can upload large files in chunks
under proxy body-size limits.

Both are plumbed through `SandboxRuntime`. The external sandbox APIs
(#65633 and the gRPC facade in #65839) build on them; those PRs will
rebase onto this one.

## Related issues

Split from #65820 per review.

**Next to review.** #65992 (EROFS) has merged and this branch is rebased
onto master, so the diff is this PR's commit alone. Merge order for the
rest of the stack is #65942 → #65633 → #65839; #65633 and #65839 are
stacked on this PR.

## Additional information

`test_resolve_exec_user` covers numeric pass-through, `name`,
`name:gid`, `name:group`, `uid:group`, a truncated passwd line, the
unknown user/group errors, an unreadable account file, and that the
group file is only read for a group name; it stubs the in-sandbox read
and runs without runsc.
`test_exec_as_named_user_resolves_inside_the_sandbox` boots busybox and
checks that `user="nobody"` and `user="65534"` agree, that a user added
with `adduser` after boot resolves, and that an unknown name is a
`SandboxExecError`. Container run (`rayproject/ray:nightly-py312`, runsc
release-20260817, as the `ray` user): `TEST_SANDBOX=1 pytest
test_gvisor_backend.py` 24 passed (netns suite included), with the
`ray.init` smoke test run on its own.

`ruff check`, `ruff check --select I`, `black`, and `pydoclint` pass
with the pre-commit versions and flags.

Signed-off-by: xyuzh <[email protected]>
pcmoritz pushed a commit that referenced this pull request Sep 24, 2026
…65633)

## Why are these changes needed?

Ray Sandbox (`ray.experimental.sandbox`) can currently only be driven
from inside the cluster as Ray actors. This PR adds an **experimental
HTTP API service** so sandboxes can be managed from outside the cluster
with nothing but an HTTP client and a bearer token — for example as an
Anyscale service, or from agent-evaluation frameworks (a Harbor
`ray-sandbox` environment built on this API is submitted alongside:
harbor-framework/harbor PR to follow).

This is the second step of the plan from #65570 (first: make the Python
API run Docker-built images out of the box; second: make Ray Sandbox
consumable as a standalone service).

## Design

```
client ──HTTP/bearer──▶ FastAPI on Ray Serve (ray.experimental.sandbox.http, stateless replicas)
                          │ ray.get_actor(name, namespace)
                          ▼
                        SandboxHost — named, detached actor per sandbox
                          │ composes SandboxRuntime
                          ▼
                        gVisor (runsc) on the node
```

- **Named detached actors are the registry.** Any replica resolves any
sandbox by name; list = `ray.util.list_named_actors`. The service keeps
no state, so replicas scale/restart freely.
- **Async submit + poll.** Image pulls and commands outlive HTTP
requests and LB limits, so `POST /sandboxes` and `POST .../execs` return
`202` immediately; clients poll, optionally long-polling with
`wait_seconds` (≤ 30 s per request). Boot progress is observable:
`pending → pulling → starting → running | error`.
- **One TTL owner.** The API's TTL reclaims the sandbox **and** its
hosting actor (the core runtime TTL is deliberately disabled here); an
abandoned sandbox never strands an actor reservation.
- **Everything sandbox-behavioral is the core `SandboxConfig`'s**
(#65570): capabilities (default `DOCKER_DEFAULT_CAPABILITIES`, sets
written exactly), network modes (validated against
`VALID_NETWORK_MODES`, so a new mode needs no API change), `dns`,
`shell` (sandbox-level and per-exec override), and the workdir/readonly
writability contract. The API patches nothing.
- **Auth**: `Authorization: Bearer <token>` enforced when
`RAY_SANDBOX_API_TOKEN` is set; an Anyscale service can leave it unset
because the platform edge already requires the service bearer token.
`GET /health` is always open.
- **Isolation from core**: importing `ray.experimental.sandbox.http`
requires `ray[serve]`; the base sandbox package never imports it.

Endpoints (`/api/v1`): create/list/get/delete sandboxes, start/poll
execs, PUT/GET files, JSON error envelope
(`401/404/409/400/413/422/503/500`). Full table in the new docs section.

## E2E validation

Deployed as an Anyscale service (runsc-equipped cluster image) and as a
local `serve run`; drove real gVisor sandboxes through create → exec →
file transfer → delete, including a full Harbor evaluation run (oracle
agent, reward 1.0) against the service URL + token.

## Update (2026-09-24)

Rebased onto master and addressed the latest review:

- **A DELETE or TTL during boot no longer orphans a container** (from
the approval review). A terminate that arrives during the image pull
stops the boot before anything starts. One that arrives while
`runtime.create` runs waits for it and deletes the new instance before
the host exits, and the boot no longer flips a terminated host back to
`running`. Tests cover a terminate during start and during pull, a TTL
during start, and a boot after terminate; the start-race tests fail on
the previous `host.py`.
- **Typing:** `spec` and `settings` are `SandboxSpec` / `HostSettings`
TypedDicts, and the runtime is typed as `SandboxRuntime`.
- **Named-actor cost, measured** (see the scalability thread). The
resolver built a fresh `ray.remote(SandboxHost)` for every sandbox,
which re-exported the class on each create: 9.15 ms per create on the
event loop (Ray 2.58, local), versus 0.76 ms with one cached ActorClass.
Resolver calls (create, lookups, kill, list) now run in worker threads,
so a GCS round trip never stalls the replica's event loop. Handles of
sandboxes created under fresh random ids are cached; deterministic names
(client tokens) keep resolving through `ray.get_actor`, whose cache
follows actor deaths and re-creations.
- **Ids:** random and token-derived ids are `sb-` plus 22 hex chars (88
bits, the facade's shape) instead of 12, and a fresh create skips
`get_if_exists`, so a random-id collision fails loudly instead of
attaching a second client to someone else's sandbox.
- **Errors:** a file write the sandbox can't perform (a directory, a
read-only rootfs outside the workdir) returns `409 write_failed` instead
of `500`, and one sandbox that fails to describe no longer fails the
whole listing. The docs list `write_failed` and the existing `503
sandbox_unavailable`.
- **Second pass** (Bugbot on the update): exec, file, and network calls
are refused once `terminate()` has started, not only after the status
flips. A `client_token` retry re-sends the idempotent `boot()`, so a
first boot that never reached the actor can't leave a sandbox pending
without its TTL. The `ResourceSpec` docs no longer claim a CPU quota is
derived from the request: only `cpu_limit` caps. The resolver and
actor-error helpers moved to `http/resolver.py`, and the package
resolves its REST exports lazily, so importing it doesn't require
FastAPI.

## Related issue number

Follow-up to #65570.

#65992 and #65942 have merged, so this PR is now a single commit on
master. Merge order for the rest of the stack: #65633 → #65839 → #66359.

## Checks

- [x] I've signed off every commit (DCO).
- [x] I've run pre-commit hooks (`ruff`, `pydoclint`, docstyle, semgrep,
import order) on the changed files.
- [x] Unit tests run with **no cluster and no runsc** (fake runtime +
fake resolver + FastAPI `TestClient`), including an OpenAPI **contract
snapshot** that pins the v1 surface: `pytest --import-mode=importlib
python/ray/experimental/sandbox/http/tests/{test_http_app,test_sandbox_host,test_http_schemas}.py`
→ 77 passed. `test_http_integration.py` is gated on the sandbox test env
+ `runsc` like the existing sandbox tests; in a privileged container
with runsc release-20260817 and erofs-utils 1.9.4 (`TEST_SANDBOX=1
RAY_SANDBOX_IGNORE_CGROUPS=1`), it and
`sandbox/tests/test_gvisor_backend.py` pass at the top of the stack (40
passed, 1 skipped). `BUILD.bazel` uses the same
`sandbox_tests`/`team:core` tags so the existing CI job picks the
package up.
- [x] Release tests: N/A (experimental, off by default; nothing imports
this package unless deployed).
- This PR was prepared with AI assistance. It is not a duplicate: it is
one step of the Ray Sandbox series (#65570 → #65992 → #65942 → #65633 →
#65839 → #66359), and no other open PR covers it.

Signed-off-by: xyuzh <[email protected]>
pcmoritz pushed a commit that referenced this pull request Sep 26, 2026
## Why are these changes needed?

#65992, #65942, and #65633 have merged, and this PR is rebased onto
master, so the diff is the facade commit alone. #66359 stacks on it.

#65633 (merged) exposes the sandbox control plane as a REST service.
This PR adds a gRPC facade in front of the same detached `SandboxHost`
actors, so an unmodified third-party sandbox client SDK pointed at this
server can create sandboxes, exec commands, and use its filesystem API
against a Ray cluster.

The facade implements the subset of the SDK's control-plane
(`ModalClient`) and command-router (`TaskCommandRouter`) services that
its Sandbox API uses. The wire contract is vendored under `http/_proto/`
as a minimal protobuf/grpclib stub set generated from checked-in
`.proto` sources, so nothing third-party is needed to build or test.
gRPC routes on the fully qualified method path and protobuf frames
fields by number, so the vendored service, method, and field identifiers
reproduce the external service's on-the-wire names verbatim; only the
surface the facade uses is declared. The proto packages carry a
`ray_sandbox_facade.` prefix that never reaches the wire, so the stubs
can share a process with the client SDK.

Design:

- **Stateless where possible.** Object ids carry their payload (`im-<b64
image ref>`, `st-<b64 env json>`) and the sandbox id doubles as the
client task id. Named creates are scoped to the client app and
idempotent; a dead actor under a live name is killed and recreated. The
one in-process table is the exec table, which keeps finished records for
120 s (the SDK reads output lazily) under a 50,000-record cap, so run a
single facade process per cluster.
- **Filesystem API via exec emulation.** The SDK implements its
filesystem API by exec-ing a helper binary that sandbox images don't
contain. The router recognizes its argv and emulates WriteFile /
ReadFile / ListFiles with `SandboxHost` file operations; large writes
flush in bounded slices.
- **Scheduling-aware.** Every actor call is bounded, so an unscheduled
actor on a scaling cluster surfaces as `UNAVAILABLE` (retried by the
SDK) instead of hanging, and a dead actor maps to `NOT_FOUND` (the SDK's
"task shut down" signal).

Run with `python -m ray.experimental.sandbox.http.grpc_facade` (requires
`grpclib`). Documented in the sandboxes guide under the HTTP API service
section.

One commit: the vendored wire contract (`.proto` sources, generated
stubs, lint excludes), the facade, its tests, and docs. Review fixes
that touch code shared with the lower PRs (`name:group` exec-user
resolution, a bounded runsc download, a bounded `DELETE`, docs wording)
live on those branches and are included here through the stack.

Review fixes from the 2026-09-15 pass:

- A `cidr_allowlist` the facade cannot enforce now fails `SandboxCreate`
with `INVALID_ARGUMENT` instead of granting open egress behind a
server-side warning, and `TaskSetNetworkAccess` fails with
`UNIMPLEMENTED` instead of being acknowledged and ignored, so a client
never runs with fewer restrictions than it asked for.
- `TaskExecStart` reserves the exec id before anything reaches the actor
and carries the start in its own task. A retry (the SDK retries
`UNAVAILABLE`, which the facade answers when the actor has not replied
within the scheduling grace) joins that in-flight start instead of
running the command again; a start that fails for good is forgotten so a
retry may start afresh. A test holds the first start in flight past the
grace, retries, and checks the command ran once.
- The exec record kind is `sandbox` or `fs` (was `host`), since both run
in the sandbox.

Update (2026-09-24), rebased onto the new #65633:

- **Tests with the Modal client** (review request):
`test_modal_client.py` runs the unmodified `modal` SDK (1.5.5) against
the facade: create, exec with exit codes and stdout/stderr,
`filesystem.write_bytes` / `read_bytes` including the typed not-found
error, terminate, and the network-policy mappings.
- **The facade and the Modal SDK can share a process.** The vendored
protos declared `package modal.client`, which registered the same full
names as the SDK's own protos in protobuf's process-wide descriptor
pool, so importing both failed with `duplicate symbol
'modal.client.ObjectCreationType'` (hit while load-testing on Anyscale).
The packages now carry a `ray_sandbox_facade.` prefix, and the generated
gRPC stubs are rewritten to the external method paths, so the wire is
unchanged: the regenerated `_grpc.py` files are byte-identical, every
served path exists in the SDK's stubs, and the SDK's serialized messages
parse into the vendored classes. `_proto/README.md` documents the
regeneration step.
- **`SandboxTerminate` no longer kills a host whose `terminate()`
outlasts the wait** (Bugbot). As in the REST `DELETE`, the queued
terminate finishes (with #65633's boot fix it first deletes a container
that was still starting) and the host exits on its own.
- **Exec records outlive fast traffic.** The SDK reads a command's
stdout and stderr lazily, often after `wait()` returned. With the
1,000-record cap, a finished record lasted about a second at 700 execs/s
and a late read got `NOT_FOUND`. Finished records now stay 120 s (hard
cap 50,000), evicted by a bounded O(1) scan instead of a full-table copy
per exec.
- **Event loop:** resolver calls (create, lookups, kill) run in worker
threads, and creates reuse one ActorClass (#65633). With real
`SandboxHost` actors on a local Ray cluster and the Modal SDK issuing 48
concurrent creates, throughput went from 56 to 353–550 creates/s, the
create RPC's p50 from 387 ms to 78–104 ms, and the facade's worst
event-loop stall during the burst from 838 ms to 36 ms. Exec throughput
is unchanged (about 1.3k/s on that machine).
- **Malformed input is `INVALID_ARGUMENT`, not `INTERNAL`:** a bare
`FROM` line, and fs-tools commands whose JSON isn't an object with an
object payload (gemini, on #66359).
- The image-seeding symlink finding (Bugbot) was fixed in #65992 before
it merged (`_resolve_in_root`); `image_utils.py` is no longer part of
this diff.
- **Second pass** (Bugbot on the update): importing the facade no longer
needs FastAPI (it takes the resolver from #65633's `http/resolver.py`),
so it needs only `grpclib` and `ray[default]`, as the docs now say.
Buffered `WriteFile` content is capped at `max_file_bytes`
(`RESOURCE_EXHAUSTED` past it), and named-create retries re-send the
idempotent `boot()`.

## Related issue number

Follows #65633 (merged).

## Checks

- `test_grpc_facade.py` drives the facade end to end over gRPC with the
vendored stubs, and `test_modal_client.py` with the unmodified Modal
SDK, both backed by the same fake resolver and runtime seams the REST
app tests use. They skip when `grpclib` (and, for the latter, `modal`)
is absent, so the sandbox core CI job, which installs neither, adds no
new dependency. Ran locally with grpclib 0.4.9 and modal 1.5.5: `pytest
--import-mode=importlib python/ray/experimental/sandbox/http/tests/` →
101 passed (21 wire tests, 3 Modal-client tests, and the 77-test HTTP
API suite).
- The facade module is never imported from `sandbox/__init__.py` or the
REST `app.py` import graph, so it stays inert unless explicitly run.
- `ruff check`, `ruff check --select I`, `black`, and `pydoclint` (the
pre-commit versions and flags) pass on the changed files.
- This PR was prepared with AI assistance. It is not a duplicate: it is
one step of the Ray Sandbox series (#65570 → #65992 → #65942 → #65633 →
#65839 → #66359), and no other open PR covers it (#66089, a KubeRay +
Modal SDK guide, builds on it).

Signed-off-by: xyuzh <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…5992)

## Description

Rootless gVisor serves each image's extracted directory through the
gofer, so every file inside a sandbox reads as the worker's uid (root),
image-baked ownership (postfix's `0700` uid-101 spool, mailman's uid-38
data) flattens away, and `chown` to another uid fails. Fixing that on
the host needs subordinate id ranges and setuid helpers (ray-project#65823), which
many environments can't provide.

This caches each image as an **EROFS root filesystem** instead. gVisor
mounts it inside the Sentry, so uids and gids live in the image and in
the private overlay upper layer and never need a host representation:
files keep their real owners and `chown` works for any uid, from an
unprivileged worker, with no id mapping and no user namespace of ours.

- **Build without root.** Extraction records each layer's non-root
owners (whiteout-aware; a later root-owned layer drops the entry;
hardlinks are recorded under their own name so the re-pack keeps the
owner whichever name it emits first), the tree is re-packed as a tar
whose headers carry them, and `mkfs.erofs --tar` (erofs-utils 1.7+)
turns that into the image with `-E^inline_data` (gVisor's EROFS reader
maps the image and only handles the flat-plain layout) and 4 KiB blocks.
The extracted tree is deleted afterwards; the cache holds one file per
image plus the image config.
- **Mount via annotations.** The bundle gets
`dev.gvisor.spec.rootfs.source/type/overlay`; the `self` overlay is
anchored at a per-sandbox directory, and runsc no longer gets
`--overlay2`. `readonly=True` keeps its semantics because the standard
mount points (`/proc`, `/sys`, `/dev`, `/dev/pts`, `/dev/shm`, `/run`,
`/tmp`, `/etc/{resolv.conf,hosts,hostname}`) are seeded into the image
at build time; runsc applies no rootfs overlay to a read-only root and
can't create mount points in an immutable image.
- **Paths resolve inside the tree.** Extraction resolves each member's
parent with the extracted tree as `/` (an absolute symlink target
restarts at the root, `..` never climbs above it), so a member under a
symlinked directory (UsrMerge's `bin -> usr/bin`, Debian's `/var/run ->
/run`) lands where the image means it, its owner is recorded under that
canonical path (where the re-pack finds it), and whiteouts delete
through the same resolution. Before, a relative link left the owner
keyed under the link path and the built image had the file as `0:0`; an
absolute link dropped the member. The `/tmp` and mount-point seeding use
the same resolver, so an image whose `etc`, `dev` or `tmp` links to a
host directory gets its seeds inside the tree, never on the host;
created files use `O_NOFOLLOW`, and a hardlink to a symlink links the
symlink itself.
- **EROFS is the only layout.** Per review, the extracted-directory
layout (and its `RAY_SANDBOX_ROOTFS=dir` switch) is gone, so
`mkfs.erofs` 1.7+ is a hard requirement on worker nodes next to `runsc`.
A pull checks for it before downloading anything and fails with an error
naming what to install. Ubuntu 24.04 and Debian 13 package a new enough
erofs-utils; Ubuntu 22.04's is 1.4 and predates `--tar`, so nodes built
on today's `rayproject/ray` images need it built from source (the docs
carry the recipe). The `.extracted` marker moves to format 3, so a cache
left by an earlier Ray re-pulls once; sandboxes still running on an old
extracted tree keep it (the tree moves into the rebuilt entry, since a
rename leaves the gofer's open root fd alone) and it is deleted on a
later pull once no sandbox uses the image.
- **CI.** The sandbox tests boot real sandboxes with `TEST_SANDBOX=1`,
so the `corebuild` image now builds erofs-utils v1.9.4 from source
(pinned to the tag's commit). Unit tests build images through a fake
`mkfs.erofs` from `conftest.py` and inspect the resulting tar, so they
run anywhere.

**One known gap.** `readonly=True` with an explicit `workdir` runs on a
private writable overlay (warned at spec time and documented): runsc
drops the requested rootfs overlay for read-only roots, and an immutable
image can't grow the workdir mount point. The clean fix is a small
upstream change to runsc (`initGoferConfs`) to honor an explicitly
requested rootfs overlay on a read-only root; `mountAll` already makes
the root writable only while creating mount points. The test for the
intended behavior is skipped with that reason and a new test pins
today's behavior.

Together with a Sentry-side network adapter that proxies to the host
without `unshare --net`, this leaves no host requirements beyond `runsc`
and `mkfs.erofs`.

## Related issues

Supersedes ray-project#65823 (closed). Related to ray-project#65820 and ray-project#66004.

**Merge order: this PR first.** ray-project#65942 (per-exec user), ray-project#65633 (HTTP
API), and ray-project#65839 (gRPC facade) are stacked on this branch in that order;
each carries the commits below it until those merge, so their diffs on
GitHub include this commit until it lands. ray-project#65942 resolves
`exec(user=<name>)` inside the running sandbox, so it works unchanged on
this cache layout.

## Additional information

Validated on x86_64 as well: an Anyscale staging cluster
(`anyscale/ray:2.58.0-py312` + runsc release-20260817 + erofs-utils
1.9.4, three 8-CPU nodes) running Terminal-Bench 2.1 with the oracle
agent through the `ray.experimental.sandbox` Python API. The `mailman`
task, which depends on image-baked postfix/mailman file ownership
surviving inside the sandbox, scores 0 on the directory layout and 1.0
with this change; the other 88 tasks are unchanged (89 trials, 0
errored). That is the exact ownership scenario this PR exists for, on a
real cluster rather than a privileged dev container.

Measured in a privileged `rayproject/ray:nightly-py312` container on
arm64 (erofs-utils 1.9.4 built from source, runsc release-20260817):

| image | pull + build | `rootfs.erofs` | extracted tree |
| --- | --- | --- | --- |
| python:3.10-slim | 7.1 s | 156.8 MB | 147 MB |
| ubuntu:24.04 | 4.6 s | 108.0 MB | 104 MB |

`mkfs.erofs` itself takes about 2 s for python:3.10-slim;
`-E^inline_data` costs roughly 6% over the tree size, and the tree is
gone afterwards, so the cache shrinks. A cache hit no longer walks an
extracted tree for eviction accounting either (one file per image),
which removes the ~60 ms per `pull_image` that @OneSizeFitsQuorum
profiled on the directory layout.

Runtime tests in that container as the unprivileged `ray` user with
`TEST_SANDBOX=1` (`test_gvisor_backend.py`, `test_image_utils.py`,
`test_image_manager.py`): 79 passed, 1 skipped (the readonly + workdir
case above); the `ray.init` smoke test was run on its own. The run
started from the cache the directory layout had left on that node, which
the first pull rebuilt to the format-3 marker. They cover image-baked
ownership from a local tar (`101:0:700`, `101:104:2710` setgid dir, a
setuid tool), root traversing another user's `0700` directory, `chown`
to arbitrary uids and `chown -R` with setgid inheritance, a readonly
EROFS root with writable `/tmp`, `network="host"` egress, the
`network="public"` netns suite, and the existing lifecycle, overlay
isolation, and workdir suites. Unit tests cover ownership recording
across layers including hardlinks, the owner-restoring tar filter, the
build through a fake `mkfs.erofs`, the missing/too-old `mkfs.erofs`
error, the format-3 re-pull with and without running sandboxes, and the
EROFS OCI spec.

Signed-off-by: xyuzh <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…sor backend (ray-project#65942)

## Description

Two small additions to the gVisor backend and `SandboxRuntime`, split
out of ray-project#65820 at reviewer request so that PR stays about network
namespaces:

- **Per-exec user.** `exec(..., user=)` runs a command as a numeric uid,
`uid:gid`, or a user (and optionally group) name. runsc only accepts
numeric ids, so names resolve against the `/etc/passwd` and `/etc/group`
**inside the running sandbox**, read through a first exec (`cat`) before
the real command runs. That covers users the image ships and users added
since (`adduser` in the sandbox), and it needs no host copy of the root
filesystem, so it works the same on the EROFS cache of ray-project#65992. A named
user with no explicit group gets its login group; numeric ids never
touch the sandbox.
- **Appending writes.** `write_file(..., append=True)` extends a file
instead of truncating it, so callers can upload large files in chunks
under proxy body-size limits.

Both are plumbed through `SandboxRuntime`. The external sandbox APIs
(ray-project#65633 and the gRPC facade in ray-project#65839) build on them; those PRs will
rebase onto this one.

## Related issues

Split from ray-project#65820 per review.

**Next to review.** ray-project#65992 (EROFS) has merged and this branch is rebased
onto master, so the diff is this PR's commit alone. Merge order for the
rest of the stack is ray-project#65942 → ray-project#65633 → ray-project#65839; ray-project#65633 and ray-project#65839 are
stacked on this PR.

## Additional information

`test_resolve_exec_user` covers numeric pass-through, `name`,
`name:gid`, `name:group`, `uid:group`, a truncated passwd line, the
unknown user/group errors, an unreadable account file, and that the
group file is only read for a group name; it stubs the in-sandbox read
and runs without runsc.
`test_exec_as_named_user_resolves_inside_the_sandbox` boots busybox and
checks that `user="nobody"` and `user="65534"` agree, that a user added
with `adduser` after boot resolves, and that an unknown name is a
`SandboxExecError`. Container run (`rayproject/ray:nightly-py312`, runsc
release-20260817, as the `ray` user): `TEST_SANDBOX=1 pytest
test_gvisor_backend.py` 24 passed (netns suite included), with the
`ray.init` smoke test run on its own.

`ruff check`, `ruff check --select I`, `black`, and `pydoclint` pass
with the pre-commit versions and flags.

Signed-off-by: xyuzh <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…ay-project#65633)

## Why are these changes needed?

Ray Sandbox (`ray.experimental.sandbox`) can currently only be driven
from inside the cluster as Ray actors. This PR adds an **experimental
HTTP API service** so sandboxes can be managed from outside the cluster
with nothing but an HTTP client and a bearer token — for example as an
Anyscale service, or from agent-evaluation frameworks (a Harbor
`ray-sandbox` environment built on this API is submitted alongside:
harbor-framework/harbor PR to follow).

This is the second step of the plan from ray-project#65570 (first: make the Python
API run Docker-built images out of the box; second: make Ray Sandbox
consumable as a standalone service).

## Design

```
client ──HTTP/bearer──▶ FastAPI on Ray Serve (ray.experimental.sandbox.http, stateless replicas)
                          │ ray.get_actor(name, namespace)
                          ▼
                        SandboxHost — named, detached actor per sandbox
                          │ composes SandboxRuntime
                          ▼
                        gVisor (runsc) on the node
```

- **Named detached actors are the registry.** Any replica resolves any
sandbox by name; list = `ray.util.list_named_actors`. The service keeps
no state, so replicas scale/restart freely.
- **Async submit + poll.** Image pulls and commands outlive HTTP
requests and LB limits, so `POST /sandboxes` and `POST .../execs` return
`202` immediately; clients poll, optionally long-polling with
`wait_seconds` (≤ 30 s per request). Boot progress is observable:
`pending → pulling → starting → running | error`.
- **One TTL owner.** The API's TTL reclaims the sandbox **and** its
hosting actor (the core runtime TTL is deliberately disabled here); an
abandoned sandbox never strands an actor reservation.
- **Everything sandbox-behavioral is the core `SandboxConfig`'s**
(ray-project#65570): capabilities (default `DOCKER_DEFAULT_CAPABILITIES`, sets
written exactly), network modes (validated against
`VALID_NETWORK_MODES`, so a new mode needs no API change), `dns`,
`shell` (sandbox-level and per-exec override), and the workdir/readonly
writability contract. The API patches nothing.
- **Auth**: `Authorization: Bearer <token>` enforced when
`RAY_SANDBOX_API_TOKEN` is set; an Anyscale service can leave it unset
because the platform edge already requires the service bearer token.
`GET /health` is always open.
- **Isolation from core**: importing `ray.experimental.sandbox.http`
requires `ray[serve]`; the base sandbox package never imports it.

Endpoints (`/api/v1`): create/list/get/delete sandboxes, start/poll
execs, PUT/GET files, JSON error envelope
(`401/404/409/400/413/422/503/500`). Full table in the new docs section.

## E2E validation

Deployed as an Anyscale service (runsc-equipped cluster image) and as a
local `serve run`; drove real gVisor sandboxes through create → exec →
file transfer → delete, including a full Harbor evaluation run (oracle
agent, reward 1.0) against the service URL + token.

## Update (2026-09-24)

Rebased onto master and addressed the latest review:

- **A DELETE or TTL during boot no longer orphans a container** (from
the approval review). A terminate that arrives during the image pull
stops the boot before anything starts. One that arrives while
`runtime.create` runs waits for it and deletes the new instance before
the host exits, and the boot no longer flips a terminated host back to
`running`. Tests cover a terminate during start and during pull, a TTL
during start, and a boot after terminate; the start-race tests fail on
the previous `host.py`.
- **Typing:** `spec` and `settings` are `SandboxSpec` / `HostSettings`
TypedDicts, and the runtime is typed as `SandboxRuntime`.
- **Named-actor cost, measured** (see the scalability thread). The
resolver built a fresh `ray.remote(SandboxHost)` for every sandbox,
which re-exported the class on each create: 9.15 ms per create on the
event loop (Ray 2.58, local), versus 0.76 ms with one cached ActorClass.
Resolver calls (create, lookups, kill, list) now run in worker threads,
so a GCS round trip never stalls the replica's event loop. Handles of
sandboxes created under fresh random ids are cached; deterministic names
(client tokens) keep resolving through `ray.get_actor`, whose cache
follows actor deaths and re-creations.
- **Ids:** random and token-derived ids are `sb-` plus 22 hex chars (88
bits, the facade's shape) instead of 12, and a fresh create skips
`get_if_exists`, so a random-id collision fails loudly instead of
attaching a second client to someone else's sandbox.
- **Errors:** a file write the sandbox can't perform (a directory, a
read-only rootfs outside the workdir) returns `409 write_failed` instead
of `500`, and one sandbox that fails to describe no longer fails the
whole listing. The docs list `write_failed` and the existing `503
sandbox_unavailable`.
- **Second pass** (Bugbot on the update): exec, file, and network calls
are refused once `terminate()` has started, not only after the status
flips. A `client_token` retry re-sends the idempotent `boot()`, so a
first boot that never reached the actor can't leave a sandbox pending
without its TTL. The `ResourceSpec` docs no longer claim a CPU quota is
derived from the request: only `cpu_limit` caps. The resolver and
actor-error helpers moved to `http/resolver.py`, and the package
resolves its REST exports lazily, so importing it doesn't require
FastAPI.

## Related issue number

Follow-up to ray-project#65570.

ray-project#65992 and ray-project#65942 have merged, so this PR is now a single commit on
master. Merge order for the rest of the stack: ray-project#65633 → ray-project#65839 → ray-project#66359.

## Checks

- [x] I've signed off every commit (DCO).
- [x] I've run pre-commit hooks (`ruff`, `pydoclint`, docstyle, semgrep,
import order) on the changed files.
- [x] Unit tests run with **no cluster and no runsc** (fake runtime +
fake resolver + FastAPI `TestClient`), including an OpenAPI **contract
snapshot** that pins the v1 surface: `pytest --import-mode=importlib
python/ray/experimental/sandbox/http/tests/{test_http_app,test_sandbox_host,test_http_schemas}.py`
→ 77 passed. `test_http_integration.py` is gated on the sandbox test env
+ `runsc` like the existing sandbox tests; in a privileged container
with runsc release-20260817 and erofs-utils 1.9.4 (`TEST_SANDBOX=1
RAY_SANDBOX_IGNORE_CGROUPS=1`), it and
`sandbox/tests/test_gvisor_backend.py` pass at the top of the stack (40
passed, 1 skipped). `BUILD.bazel` uses the same
`sandbox_tests`/`team:core` tags so the existing CI job picks the
package up.
- [x] Release tests: N/A (experimental, off by default; nothing imports
this package unless deployed).
- This PR was prepared with AI assistance. It is not a duplicate: it is
one step of the Ray Sandbox series (ray-project#65570 → ray-project#65992 → ray-project#65942 → ray-project#65633 →
ray-project#65839 → ray-project#66359), and no other open PR covers it.

Signed-off-by: xyuzh <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…roject#65839)

## Why are these changes needed?

ray-project#65992, ray-project#65942, and ray-project#65633 have merged, and this PR is rebased onto
master, so the diff is the facade commit alone. ray-project#66359 stacks on it.

ray-project#65633 (merged) exposes the sandbox control plane as a REST service.
This PR adds a gRPC facade in front of the same detached `SandboxHost`
actors, so an unmodified third-party sandbox client SDK pointed at this
server can create sandboxes, exec commands, and use its filesystem API
against a Ray cluster.

The facade implements the subset of the SDK's control-plane
(`ModalClient`) and command-router (`TaskCommandRouter`) services that
its Sandbox API uses. The wire contract is vendored under `http/_proto/`
as a minimal protobuf/grpclib stub set generated from checked-in
`.proto` sources, so nothing third-party is needed to build or test.
gRPC routes on the fully qualified method path and protobuf frames
fields by number, so the vendored service, method, and field identifiers
reproduce the external service's on-the-wire names verbatim; only the
surface the facade uses is declared. The proto packages carry a
`ray_sandbox_facade.` prefix that never reaches the wire, so the stubs
can share a process with the client SDK.

Design:

- **Stateless where possible.** Object ids carry their payload (`im-<b64
image ref>`, `st-<b64 env json>`) and the sandbox id doubles as the
client task id. Named creates are scoped to the client app and
idempotent; a dead actor under a live name is killed and recreated. The
one in-process table is the exec table, which keeps finished records for
120 s (the SDK reads output lazily) under a 50,000-record cap, so run a
single facade process per cluster.
- **Filesystem API via exec emulation.** The SDK implements its
filesystem API by exec-ing a helper binary that sandbox images don't
contain. The router recognizes its argv and emulates WriteFile /
ReadFile / ListFiles with `SandboxHost` file operations; large writes
flush in bounded slices.
- **Scheduling-aware.** Every actor call is bounded, so an unscheduled
actor on a scaling cluster surfaces as `UNAVAILABLE` (retried by the
SDK) instead of hanging, and a dead actor maps to `NOT_FOUND` (the SDK's
"task shut down" signal).

Run with `python -m ray.experimental.sandbox.http.grpc_facade` (requires
`grpclib`). Documented in the sandboxes guide under the HTTP API service
section.

One commit: the vendored wire contract (`.proto` sources, generated
stubs, lint excludes), the facade, its tests, and docs. Review fixes
that touch code shared with the lower PRs (`name:group` exec-user
resolution, a bounded runsc download, a bounded `DELETE`, docs wording)
live on those branches and are included here through the stack.

Review fixes from the 2026-09-15 pass:

- A `cidr_allowlist` the facade cannot enforce now fails `SandboxCreate`
with `INVALID_ARGUMENT` instead of granting open egress behind a
server-side warning, and `TaskSetNetworkAccess` fails with
`UNIMPLEMENTED` instead of being acknowledged and ignored, so a client
never runs with fewer restrictions than it asked for.
- `TaskExecStart` reserves the exec id before anything reaches the actor
and carries the start in its own task. A retry (the SDK retries
`UNAVAILABLE`, which the facade answers when the actor has not replied
within the scheduling grace) joins that in-flight start instead of
running the command again; a start that fails for good is forgotten so a
retry may start afresh. A test holds the first start in flight past the
grace, retries, and checks the command ran once.
- The exec record kind is `sandbox` or `fs` (was `host`), since both run
in the sandbox.

Update (2026-09-24), rebased onto the new ray-project#65633:

- **Tests with the Modal client** (review request):
`test_modal_client.py` runs the unmodified `modal` SDK (1.5.5) against
the facade: create, exec with exit codes and stdout/stderr,
`filesystem.write_bytes` / `read_bytes` including the typed not-found
error, terminate, and the network-policy mappings.
- **The facade and the Modal SDK can share a process.** The vendored
protos declared `package modal.client`, which registered the same full
names as the SDK's own protos in protobuf's process-wide descriptor
pool, so importing both failed with `duplicate symbol
'modal.client.ObjectCreationType'` (hit while load-testing on Anyscale).
The packages now carry a `ray_sandbox_facade.` prefix, and the generated
gRPC stubs are rewritten to the external method paths, so the wire is
unchanged: the regenerated `_grpc.py` files are byte-identical, every
served path exists in the SDK's stubs, and the SDK's serialized messages
parse into the vendored classes. `_proto/README.md` documents the
regeneration step.
- **`SandboxTerminate` no longer kills a host whose `terminate()`
outlasts the wait** (Bugbot). As in the REST `DELETE`, the queued
terminate finishes (with ray-project#65633's boot fix it first deletes a container
that was still starting) and the host exits on its own.
- **Exec records outlive fast traffic.** The SDK reads a command's
stdout and stderr lazily, often after `wait()` returned. With the
1,000-record cap, a finished record lasted about a second at 700 execs/s
and a late read got `NOT_FOUND`. Finished records now stay 120 s (hard
cap 50,000), evicted by a bounded O(1) scan instead of a full-table copy
per exec.
- **Event loop:** resolver calls (create, lookups, kill) run in worker
threads, and creates reuse one ActorClass (ray-project#65633). With real
`SandboxHost` actors on a local Ray cluster and the Modal SDK issuing 48
concurrent creates, throughput went from 56 to 353–550 creates/s, the
create RPC's p50 from 387 ms to 78–104 ms, and the facade's worst
event-loop stall during the burst from 838 ms to 36 ms. Exec throughput
is unchanged (about 1.3k/s on that machine).
- **Malformed input is `INVALID_ARGUMENT`, not `INTERNAL`:** a bare
`FROM` line, and fs-tools commands whose JSON isn't an object with an
object payload (gemini, on ray-project#66359).
- The image-seeding symlink finding (Bugbot) was fixed in ray-project#65992 before
it merged (`_resolve_in_root`); `image_utils.py` is no longer part of
this diff.
- **Second pass** (Bugbot on the update): importing the facade no longer
needs FastAPI (it takes the resolver from ray-project#65633's `http/resolver.py`),
so it needs only `grpclib` and `ray[default]`, as the docs now say.
Buffered `WriteFile` content is capped at `max_file_bytes`
(`RESOURCE_EXHAUSTED` past it), and named-create retries re-send the
idempotent `boot()`.

## Related issue number

Follows ray-project#65633 (merged).

## Checks

- `test_grpc_facade.py` drives the facade end to end over gRPC with the
vendored stubs, and `test_modal_client.py` with the unmodified Modal
SDK, both backed by the same fake resolver and runtime seams the REST
app tests use. They skip when `grpclib` (and, for the latter, `modal`)
is absent, so the sandbox core CI job, which installs neither, adds no
new dependency. Ran locally with grpclib 0.4.9 and modal 1.5.5: `pytest
--import-mode=importlib python/ray/experimental/sandbox/http/tests/` →
101 passed (21 wire tests, 3 Modal-client tests, and the 77-test HTTP
API suite).
- The facade module is never imported from `sandbox/__init__.py` or the
REST `app.py` import graph, so it stays inert unless explicitly run.
- `ruff check`, `ruff check --select I`, `black`, and `pydoclint` (the
pre-commit versions and flags) pass on the changed files.
- This PR was prepared with AI assistance. It is not a duplicate: it is
one step of the Ray Sandbox series (ray-project#65570 → ray-project#65992 → ray-project#65942 → ray-project#65633 →
ray-project#65839 → ray-project#66359), and no other open PR covers it (ray-project#66089, a KubeRay +
Modal SDK guide, builds on it).

Signed-off-by: xyuzh <[email protected]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Oct 23, 2026
…5992)

## Description

Rootless gVisor serves each image's extracted directory through the
gofer, so every file inside a sandbox reads as the worker's uid (root),
image-baked ownership (postfix's `0700` uid-101 spool, mailman's uid-38
data) flattens away, and `chown` to another uid fails. Fixing that on
the host needs subordinate id ranges and setuid helpers (ray-project#65823), which
many environments can't provide.

This caches each image as an **EROFS root filesystem** instead. gVisor
mounts it inside the Sentry, so uids and gids live in the image and in
the private overlay upper layer and never need a host representation:
files keep their real owners and `chown` works for any uid, from an
unprivileged worker, with no id mapping and no user namespace of ours.

- **Build without root.** Extraction records each layer's non-root
owners (whiteout-aware; a later root-owned layer drops the entry;
hardlinks are recorded under their own name so the re-pack keeps the
owner whichever name it emits first), the tree is re-packed as a tar
whose headers carry them, and `mkfs.erofs --tar` (erofs-utils 1.7+)
turns that into the image with `-E^inline_data` (gVisor's EROFS reader
maps the image and only handles the flat-plain layout) and 4 KiB blocks.
The extracted tree is deleted afterwards; the cache holds one file per
image plus the image config.
- **Mount via annotations.** The bundle gets
`dev.gvisor.spec.rootfs.source/type/overlay`; the `self` overlay is
anchored at a per-sandbox directory, and runsc no longer gets
`--overlay2`. `readonly=True` keeps its semantics because the standard
mount points (`/proc`, `/sys`, `/dev`, `/dev/pts`, `/dev/shm`, `/run`,
`/tmp`, `/etc/{resolv.conf,hosts,hostname}`) are seeded into the image
at build time; runsc applies no rootfs overlay to a read-only root and
can't create mount points in an immutable image.
- **Paths resolve inside the tree.** Extraction resolves each member's
parent with the extracted tree as `/` (an absolute symlink target
restarts at the root, `..` never climbs above it), so a member under a
symlinked directory (UsrMerge's `bin -> usr/bin`, Debian's `/var/run ->
/run`) lands where the image means it, its owner is recorded under that
canonical path (where the re-pack finds it), and whiteouts delete
through the same resolution. Before, a relative link left the owner
keyed under the link path and the built image had the file as `0:0`; an
absolute link dropped the member. The `/tmp` and mount-point seeding use
the same resolver, so an image whose `etc`, `dev` or `tmp` links to a
host directory gets its seeds inside the tree, never on the host;
created files use `O_NOFOLLOW`, and a hardlink to a symlink links the
symlink itself.
- **EROFS is the only layout.** Per review, the extracted-directory
layout (and its `RAY_SANDBOX_ROOTFS=dir` switch) is gone, so
`mkfs.erofs` 1.7+ is a hard requirement on worker nodes next to `runsc`.
A pull checks for it before downloading anything and fails with an error
naming what to install. Ubuntu 24.04 and Debian 13 package a new enough
erofs-utils; Ubuntu 22.04's is 1.4 and predates `--tar`, so nodes built
on today's `rayproject/ray` images need it built from source (the docs
carry the recipe). The `.extracted` marker moves to format 3, so a cache
left by an earlier Ray re-pulls once; sandboxes still running on an old
extracted tree keep it (the tree moves into the rebuilt entry, since a
rename leaves the gofer's open root fd alone) and it is deleted on a
later pull once no sandbox uses the image.
- **CI.** The sandbox tests boot real sandboxes with `TEST_SANDBOX=1`,
so the `corebuild` image now builds erofs-utils v1.9.4 from source
(pinned to the tag's commit). Unit tests build images through a fake
`mkfs.erofs` from `conftest.py` and inspect the resulting tar, so they
run anywhere.

**One known gap.** `readonly=True` with an explicit `workdir` runs on a
private writable overlay (warned at spec time and documented): runsc
drops the requested rootfs overlay for read-only roots, and an immutable
image can't grow the workdir mount point. The clean fix is a small
upstream change to runsc (`initGoferConfs`) to honor an explicitly
requested rootfs overlay on a read-only root; `mountAll` already makes
the root writable only while creating mount points. The test for the
intended behavior is skipped with that reason and a new test pins
today's behavior.

Together with a Sentry-side network adapter that proxies to the host
without `unshare --net`, this leaves no host requirements beyond `runsc`
and `mkfs.erofs`.

## Related issues

Supersedes ray-project#65823 (closed). Related to ray-project#65820 and ray-project#66004.

**Merge order: this PR first.** ray-project#65942 (per-exec user), ray-project#65633 (HTTP
API), and ray-project#65839 (gRPC facade) are stacked on this branch in that order;
each carries the commits below it until those merge, so their diffs on
GitHub include this commit until it lands. ray-project#65942 resolves
`exec(user=<name>)` inside the running sandbox, so it works unchanged on
this cache layout.

## Additional information

Validated on x86_64 as well: an Anyscale staging cluster
(`anyscale/ray:2.58.0-py312` + runsc release-20260817 + erofs-utils
1.9.4, three 8-CPU nodes) running Terminal-Bench 2.1 with the oracle
agent through the `ray.experimental.sandbox` Python API. The `mailman`
task, which depends on image-baked postfix/mailman file ownership
surviving inside the sandbox, scores 0 on the directory layout and 1.0
with this change; the other 88 tasks are unchanged (89 trials, 0
errored). That is the exact ownership scenario this PR exists for, on a
real cluster rather than a privileged dev container.

Measured in a privileged `rayproject/ray:nightly-py312` container on
arm64 (erofs-utils 1.9.4 built from source, runsc release-20260817):

| image | pull + build | `rootfs.erofs` | extracted tree |
| --- | --- | --- | --- |
| python:3.10-slim | 7.1 s | 156.8 MB | 147 MB |
| ubuntu:24.04 | 4.6 s | 108.0 MB | 104 MB |

`mkfs.erofs` itself takes about 2 s for python:3.10-slim;
`-E^inline_data` costs roughly 6% over the tree size, and the tree is
gone afterwards, so the cache shrinks. A cache hit no longer walks an
extracted tree for eviction accounting either (one file per image),
which removes the ~60 ms per `pull_image` that @OneSizeFitsQuorum
profiled on the directory layout.

Runtime tests in that container as the unprivileged `ray` user with
`TEST_SANDBOX=1` (`test_gvisor_backend.py`, `test_image_utils.py`,
`test_image_manager.py`): 79 passed, 1 skipped (the readonly + workdir
case above); the `ray.init` smoke test was run on its own. The run
started from the cache the directory layout had left on that node, which
the first pull rebuilt to the format-3 marker. They cover image-baked
ownership from a local tar (`101:0:700`, `101:104:2710` setgid dir, a
setuid tool), root traversing another user's `0700` directory, `chown`
to arbitrary uids and `chown -R` with setgid inheritance, a readonly
EROFS root with writable `/tmp`, `network="host"` egress, the
`network="public"` netns suite, and the existing lifecycle, overlay
isolation, and workdir suites. Unit tests cover ownership recording
across layers including hardlinks, the owner-restoring tar filter, the
build through a fake `mkfs.erofs`, the missing/too-old `mkfs.erofs`
error, the format-3 re-pull with and without running sandboxes, and the
EROFS OCI spec.

Signed-off-by: xyuzh <[email protected]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Oct 23, 2026
…sor backend (ray-project#65942)

## Description

Two small additions to the gVisor backend and `SandboxRuntime`, split
out of ray-project#65820 at reviewer request so that PR stays about network
namespaces:

- **Per-exec user.** `exec(..., user=)` runs a command as a numeric uid,
`uid:gid`, or a user (and optionally group) name. runsc only accepts
numeric ids, so names resolve against the `/etc/passwd` and `/etc/group`
**inside the running sandbox**, read through a first exec (`cat`) before
the real command runs. That covers users the image ships and users added
since (`adduser` in the sandbox), and it needs no host copy of the root
filesystem, so it works the same on the EROFS cache of ray-project#65992. A named
user with no explicit group gets its login group; numeric ids never
touch the sandbox.
- **Appending writes.** `write_file(..., append=True)` extends a file
instead of truncating it, so callers can upload large files in chunks
under proxy body-size limits.

Both are plumbed through `SandboxRuntime`. The external sandbox APIs
(ray-project#65633 and the gRPC facade in ray-project#65839) build on them; those PRs will
rebase onto this one.

## Related issues

Split from ray-project#65820 per review.

**Next to review.** ray-project#65992 (EROFS) has merged and this branch is rebased
onto master, so the diff is this PR's commit alone. Merge order for the
rest of the stack is ray-project#65942 → ray-project#65633 → ray-project#65839; ray-project#65633 and ray-project#65839 are
stacked on this PR.

## Additional information

`test_resolve_exec_user` covers numeric pass-through, `name`,
`name:gid`, `name:group`, `uid:group`, a truncated passwd line, the
unknown user/group errors, an unreadable account file, and that the
group file is only read for a group name; it stubs the in-sandbox read
and runs without runsc.
`test_exec_as_named_user_resolves_inside_the_sandbox` boots busybox and
checks that `user="nobody"` and `user="65534"` agree, that a user added
with `adduser` after boot resolves, and that an unknown name is a
`SandboxExecError`. Container run (`rayproject/ray:nightly-py312`, runsc
release-20260817, as the `ray` user): `TEST_SANDBOX=1 pytest
test_gvisor_backend.py` 24 passed (netns suite included), with the
`ray.init` smoke test run on its own.

`ruff check`, `ruff check --select I`, `black`, and `pydoclint` pass
with the pre-commit versions and flags.

Signed-off-by: xyuzh <[email protected]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Oct 23, 2026
…ay-project#65633)

## Why are these changes needed?

Ray Sandbox (`ray.experimental.sandbox`) can currently only be driven
from inside the cluster as Ray actors. This PR adds an **experimental
HTTP API service** so sandboxes can be managed from outside the cluster
with nothing but an HTTP client and a bearer token — for example as an
Anyscale service, or from agent-evaluation frameworks (a Harbor
`ray-sandbox` environment built on this API is submitted alongside:
harbor-framework/harbor PR to follow).

This is the second step of the plan from ray-project#65570 (first: make the Python
API run Docker-built images out of the box; second: make Ray Sandbox
consumable as a standalone service).

## Design

```
client ──HTTP/bearer──▶ FastAPI on Ray Serve (ray.experimental.sandbox.http, stateless replicas)
                          │ ray.get_actor(name, namespace)
                          ▼
                        SandboxHost — named, detached actor per sandbox
                          │ composes SandboxRuntime
                          ▼
                        gVisor (runsc) on the node
```

- **Named detached actors are the registry.** Any replica resolves any
sandbox by name; list = `ray.util.list_named_actors`. The service keeps
no state, so replicas scale/restart freely.
- **Async submit + poll.** Image pulls and commands outlive HTTP
requests and LB limits, so `POST /sandboxes` and `POST .../execs` return
`202` immediately; clients poll, optionally long-polling with
`wait_seconds` (≤ 30 s per request). Boot progress is observable:
`pending → pulling → starting → running | error`.
- **One TTL owner.** The API's TTL reclaims the sandbox **and** its
hosting actor (the core runtime TTL is deliberately disabled here); an
abandoned sandbox never strands an actor reservation.
- **Everything sandbox-behavioral is the core `SandboxConfig`'s**
(ray-project#65570): capabilities (default `DOCKER_DEFAULT_CAPABILITIES`, sets
written exactly), network modes (validated against
`VALID_NETWORK_MODES`, so a new mode needs no API change), `dns`,
`shell` (sandbox-level and per-exec override), and the workdir/readonly
writability contract. The API patches nothing.
- **Auth**: `Authorization: Bearer <token>` enforced when
`RAY_SANDBOX_API_TOKEN` is set; an Anyscale service can leave it unset
because the platform edge already requires the service bearer token.
`GET /health` is always open.
- **Isolation from core**: importing `ray.experimental.sandbox.http`
requires `ray[serve]`; the base sandbox package never imports it.

Endpoints (`/api/v1`): create/list/get/delete sandboxes, start/poll
execs, PUT/GET files, JSON error envelope
(`401/404/409/400/413/422/503/500`). Full table in the new docs section.

## E2E validation

Deployed as an Anyscale service (runsc-equipped cluster image) and as a
local `serve run`; drove real gVisor sandboxes through create → exec →
file transfer → delete, including a full Harbor evaluation run (oracle
agent, reward 1.0) against the service URL + token.

## Update (2026-09-24)

Rebased onto master and addressed the latest review:

- **A DELETE or TTL during boot no longer orphans a container** (from
the approval review). A terminate that arrives during the image pull
stops the boot before anything starts. One that arrives while
`runtime.create` runs waits for it and deletes the new instance before
the host exits, and the boot no longer flips a terminated host back to
`running`. Tests cover a terminate during start and during pull, a TTL
during start, and a boot after terminate; the start-race tests fail on
the previous `host.py`.
- **Typing:** `spec` and `settings` are `SandboxSpec` / `HostSettings`
TypedDicts, and the runtime is typed as `SandboxRuntime`.
- **Named-actor cost, measured** (see the scalability thread). The
resolver built a fresh `ray.remote(SandboxHost)` for every sandbox,
which re-exported the class on each create: 9.15 ms per create on the
event loop (Ray 2.58, local), versus 0.76 ms with one cached ActorClass.
Resolver calls (create, lookups, kill, list) now run in worker threads,
so a GCS round trip never stalls the replica's event loop. Handles of
sandboxes created under fresh random ids are cached; deterministic names
(client tokens) keep resolving through `ray.get_actor`, whose cache
follows actor deaths and re-creations.
- **Ids:** random and token-derived ids are `sb-` plus 22 hex chars (88
bits, the facade's shape) instead of 12, and a fresh create skips
`get_if_exists`, so a random-id collision fails loudly instead of
attaching a second client to someone else's sandbox.
- **Errors:** a file write the sandbox can't perform (a directory, a
read-only rootfs outside the workdir) returns `409 write_failed` instead
of `500`, and one sandbox that fails to describe no longer fails the
whole listing. The docs list `write_failed` and the existing `503
sandbox_unavailable`.
- **Second pass** (Bugbot on the update): exec, file, and network calls
are refused once `terminate()` has started, not only after the status
flips. A `client_token` retry re-sends the idempotent `boot()`, so a
first boot that never reached the actor can't leave a sandbox pending
without its TTL. The `ResourceSpec` docs no longer claim a CPU quota is
derived from the request: only `cpu_limit` caps. The resolver and
actor-error helpers moved to `http/resolver.py`, and the package
resolves its REST exports lazily, so importing it doesn't require
FastAPI.

## Related issue number

Follow-up to ray-project#65570.

ray-project#65992 and ray-project#65942 have merged, so this PR is now a single commit on
master. Merge order for the rest of the stack: ray-project#65633 → ray-project#65839 → ray-project#66359.

## Checks

- [x] I've signed off every commit (DCO).
- [x] I've run pre-commit hooks (`ruff`, `pydoclint`, docstyle, semgrep,
import order) on the changed files.
- [x] Unit tests run with **no cluster and no runsc** (fake runtime +
fake resolver + FastAPI `TestClient`), including an OpenAPI **contract
snapshot** that pins the v1 surface: `pytest --import-mode=importlib
python/ray/experimental/sandbox/http/tests/{test_http_app,test_sandbox_host,test_http_schemas}.py`
→ 77 passed. `test_http_integration.py` is gated on the sandbox test env
+ `runsc` like the existing sandbox tests; in a privileged container
with runsc release-20260817 and erofs-utils 1.9.4 (`TEST_SANDBOX=1
RAY_SANDBOX_IGNORE_CGROUPS=1`), it and
`sandbox/tests/test_gvisor_backend.py` pass at the top of the stack (40
passed, 1 skipped). `BUILD.bazel` uses the same
`sandbox_tests`/`team:core` tags so the existing CI job picks the
package up.
- [x] Release tests: N/A (experimental, off by default; nothing imports
this package unless deployed).
- This PR was prepared with AI assistance. It is not a duplicate: it is
one step of the Ray Sandbox series (ray-project#65570 → ray-project#65992 → ray-project#65942 → ray-project#65633 →
ray-project#65839 → ray-project#66359), and no other open PR covers it.

Signed-off-by: xyuzh <[email protected]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Oct 23, 2026
…roject#65839)

## Why are these changes needed?

ray-project#65992, ray-project#65942, and ray-project#65633 have merged, and this PR is rebased onto
master, so the diff is the facade commit alone. ray-project#66359 stacks on it.

ray-project#65633 (merged) exposes the sandbox control plane as a REST service.
This PR adds a gRPC facade in front of the same detached `SandboxHost`
actors, so an unmodified third-party sandbox client SDK pointed at this
server can create sandboxes, exec commands, and use its filesystem API
against a Ray cluster.

The facade implements the subset of the SDK's control-plane
(`ModalClient`) and command-router (`TaskCommandRouter`) services that
its Sandbox API uses. The wire contract is vendored under `http/_proto/`
as a minimal protobuf/grpclib stub set generated from checked-in
`.proto` sources, so nothing third-party is needed to build or test.
gRPC routes on the fully qualified method path and protobuf frames
fields by number, so the vendored service, method, and field identifiers
reproduce the external service's on-the-wire names verbatim; only the
surface the facade uses is declared. The proto packages carry a
`ray_sandbox_facade.` prefix that never reaches the wire, so the stubs
can share a process with the client SDK.

Design:

- **Stateless where possible.** Object ids carry their payload (`im-<b64
image ref>`, `st-<b64 env json>`) and the sandbox id doubles as the
client task id. Named creates are scoped to the client app and
idempotent; a dead actor under a live name is killed and recreated. The
one in-process table is the exec table, which keeps finished records for
120 s (the SDK reads output lazily) under a 50,000-record cap, so run a
single facade process per cluster.
- **Filesystem API via exec emulation.** The SDK implements its
filesystem API by exec-ing a helper binary that sandbox images don't
contain. The router recognizes its argv and emulates WriteFile /
ReadFile / ListFiles with `SandboxHost` file operations; large writes
flush in bounded slices.
- **Scheduling-aware.** Every actor call is bounded, so an unscheduled
actor on a scaling cluster surfaces as `UNAVAILABLE` (retried by the
SDK) instead of hanging, and a dead actor maps to `NOT_FOUND` (the SDK's
"task shut down" signal).

Run with `python -m ray.experimental.sandbox.http.grpc_facade` (requires
`grpclib`). Documented in the sandboxes guide under the HTTP API service
section.

One commit: the vendored wire contract (`.proto` sources, generated
stubs, lint excludes), the facade, its tests, and docs. Review fixes
that touch code shared with the lower PRs (`name:group` exec-user
resolution, a bounded runsc download, a bounded `DELETE`, docs wording)
live on those branches and are included here through the stack.

Review fixes from the 2026-09-15 pass:

- A `cidr_allowlist` the facade cannot enforce now fails `SandboxCreate`
with `INVALID_ARGUMENT` instead of granting open egress behind a
server-side warning, and `TaskSetNetworkAccess` fails with
`UNIMPLEMENTED` instead of being acknowledged and ignored, so a client
never runs with fewer restrictions than it asked for.
- `TaskExecStart` reserves the exec id before anything reaches the actor
and carries the start in its own task. A retry (the SDK retries
`UNAVAILABLE`, which the facade answers when the actor has not replied
within the scheduling grace) joins that in-flight start instead of
running the command again; a start that fails for good is forgotten so a
retry may start afresh. A test holds the first start in flight past the
grace, retries, and checks the command ran once.
- The exec record kind is `sandbox` or `fs` (was `host`), since both run
in the sandbox.

Update (2026-09-24), rebased onto the new ray-project#65633:

- **Tests with the Modal client** (review request):
`test_modal_client.py` runs the unmodified `modal` SDK (1.5.5) against
the facade: create, exec with exit codes and stdout/stderr,
`filesystem.write_bytes` / `read_bytes` including the typed not-found
error, terminate, and the network-policy mappings.
- **The facade and the Modal SDK can share a process.** The vendored
protos declared `package modal.client`, which registered the same full
names as the SDK's own protos in protobuf's process-wide descriptor
pool, so importing both failed with `duplicate symbol
'modal.client.ObjectCreationType'` (hit while load-testing on Anyscale).
The packages now carry a `ray_sandbox_facade.` prefix, and the generated
gRPC stubs are rewritten to the external method paths, so the wire is
unchanged: the regenerated `_grpc.py` files are byte-identical, every
served path exists in the SDK's stubs, and the SDK's serialized messages
parse into the vendored classes. `_proto/README.md` documents the
regeneration step.
- **`SandboxTerminate` no longer kills a host whose `terminate()`
outlasts the wait** (Bugbot). As in the REST `DELETE`, the queued
terminate finishes (with ray-project#65633's boot fix it first deletes a container
that was still starting) and the host exits on its own.
- **Exec records outlive fast traffic.** The SDK reads a command's
stdout and stderr lazily, often after `wait()` returned. With the
1,000-record cap, a finished record lasted about a second at 700 execs/s
and a late read got `NOT_FOUND`. Finished records now stay 120 s (hard
cap 50,000), evicted by a bounded O(1) scan instead of a full-table copy
per exec.
- **Event loop:** resolver calls (create, lookups, kill) run in worker
threads, and creates reuse one ActorClass (ray-project#65633). With real
`SandboxHost` actors on a local Ray cluster and the Modal SDK issuing 48
concurrent creates, throughput went from 56 to 353–550 creates/s, the
create RPC's p50 from 387 ms to 78–104 ms, and the facade's worst
event-loop stall during the burst from 838 ms to 36 ms. Exec throughput
is unchanged (about 1.3k/s on that machine).
- **Malformed input is `INVALID_ARGUMENT`, not `INTERNAL`:** a bare
`FROM` line, and fs-tools commands whose JSON isn't an object with an
object payload (gemini, on ray-project#66359).
- The image-seeding symlink finding (Bugbot) was fixed in ray-project#65992 before
it merged (`_resolve_in_root`); `image_utils.py` is no longer part of
this diff.
- **Second pass** (Bugbot on the update): importing the facade no longer
needs FastAPI (it takes the resolver from ray-project#65633's `http/resolver.py`),
so it needs only `grpclib` and `ray[default]`, as the docs now say.
Buffered `WriteFile` content is capped at `max_file_bytes`
(`RESOURCE_EXHAUSTED` past it), and named-create retries re-send the
idempotent `boot()`.

## Related issue number

Follows ray-project#65633 (merged).

## Checks

- `test_grpc_facade.py` drives the facade end to end over gRPC with the
vendored stubs, and `test_modal_client.py` with the unmodified Modal
SDK, both backed by the same fake resolver and runtime seams the REST
app tests use. They skip when `grpclib` (and, for the latter, `modal`)
is absent, so the sandbox core CI job, which installs neither, adds no
new dependency. Ran locally with grpclib 0.4.9 and modal 1.5.5: `pytest
--import-mode=importlib python/ray/experimental/sandbox/http/tests/` →
101 passed (21 wire tests, 3 Modal-client tests, and the 77-test HTTP
API suite).
- The facade module is never imported from `sandbox/__init__.py` or the
REST `app.py` import graph, so it stays inert unless explicitly run.
- `ruff check`, `ruff check --select I`, `black`, and `pydoclint` (the
pre-commit versions and flags) pass on the changed files.
- This PR was prepared with AI assistance. It is not a duplicate: it is
one step of the Ray Sandbox series (ray-project#65570 → ray-project#65992 → ray-project#65942 → ray-project#65633 →
ray-project#65839 → ray-project#66359), and no other open PR covers it (ray-project#66089, a KubeRay +
Modal SDK guide, builds on it).

Signed-off-by: xyuzh <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Issues that should be addressed in Ray Core go add ONLY when ready to merge, run all tests sandbox

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants