Skip to content

[core][sandbox] Add a gRPC facade for external sandbox clients - #65839

Merged
pcmoritz merged 1 commit into
ray-project:masterfrom
xyuzh:sandbox-modal-facade
Sep 26, 2026
Merged

pcmoritz merged 1 commit into
ray-project:masterfrom
xyuzh:sandbox-modal-facade

Conversation

@xyuzh

@xyuzh xyuzh commented Sep 1, 2026 •

Copy link
Copy Markdown
Member

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 [core][sandbox] Add an experimental HTTP API service for Ray Sandbox #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 ([core][sandbox] Add an experimental HTTP API service for Ray Sandbox #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 [core][sandbox] Default network="public" egress to the public internet and enforce allowlists #66359).
  • The image-seeding symlink finding (Bugbot) was fixed in [core][sandbox] Cache images as EROFS root filesystems #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 [core][sandbox] Add an experimental HTTP API service for Ray Sandbox #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

@xyuzh
xyuzh requested review from a team as code owners September 1, 2026 15:44

@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 an experimental HTTP REST API service and a Modal-compatible gRPC facade for Ray Sandbox, allowing users to manage sandboxes, execute commands, and perform file operations from outside the Ray cluster. Key feedback includes addressing a bug in the gVisor backend's user resolution logic when a group or GID is specified, preventing potential indefinite hangs during runsc downloads by replacing urlretrieve with a timed-out urlopen call, and fixing a timeout calculation bug in the Modal compatibility layer's SandboxWait endpoint that causes it to exit prematurely when no timeout is specified.

@xyuzh
xyuzh force-pushed the sandbox-modal-facade branch from e72ac4b to 9354d62 Compare September 1, 2026 18:04
@xyuzh xyuzh changed the title [core][sandbox] Add a Modal-wire-compatible gRPC facade for Ray Sandbox [core][sandbox] Add a gRPC facade for external sandbox clients Sep 1, 2026
@ray-gardener ray-gardener Bot added the core Issues that should be addressed in Ray Core label Sep 1, 2026
@xyuzh
xyuzh requested a review from a team as a code owner September 1, 2026 22:38
@xyuzh xyuzh added the go add ONLY when ready to merge, run all tests label Sep 2, 2026

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

Docs-team style pass from Douglas Strodtman (Anyscale docs). Claude Code assisted; I read every comment below and stand behind each one.

Scope: prose style, grammar, and docs conventions only. Technical accuracy — the endpoint contracts, status codes, the resource and capability semantics, the image tags in the examples — is the ray-core and ray-serve maintainers' call, not mine, and I'm not asserting anything about it.

This reads cleanly: sentence-case headings throughout, consistent serial commas, such as over like, and the #networking-and-dns anchors all resolve against the heading in this file. Two small prose nits inline, both optional. No approval implied — core and serve owners are the gate here.

Comment thread doc/source/ray-core/sandboxes.md Resolved
Comment thread doc/source/ray-core/sandboxes.md Resolved
@xyuzh
xyuzh force-pushed the sandbox-modal-facade branch from e41087a to 531b5f7 Compare September 4, 2026 18:24

@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 commented Sep 9, 2026

Copy link
Copy Markdown
Member Author

Rebuilt on the rewritten #65633 head so this diff is facade-only again (13 files, all additions). Both Bugbot findings are fixed in the single signed commit: TaskExecStart is idempotent per exec id, and SandboxWait with timeout=0 polls without long-polling describe or waiting out the scheduling grace. Tests added for both.

@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-modal-facade branch from 73e5bff to 259c9a3 Compare September 9, 2026 22: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.

Stale Bugbot comment from a previous run.

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

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

Docs review from Douglas Strodtman on the Anyscale docs team, drafted with Claude Code assistance; I've read every comment and stand behind this.

Scope is style, grammar, and Ray docs conventions only. This is the gRPC facade layer stacked on #65633, so I reviewed only its incremental prose here; the shared HTTP API section is covered on #65633. The new "gRPC facade for third-party sandbox clients" section reads clean: sentence-case heading, angle-bracket placeholder in the run command, a complete-sentence list lead-in, and contractions throughout. No style findings. My two earlier suggestions were applied in af2d1c9 — thanks.

Everything technical, and the source approval ray-core owns, stays with the maintainers. No objection from the docs side to the new section.


network_type = definition.network_access.network_access_type
if network_type == api_pb2.NetworkAccess.ALLOWLIST:
logger.warning(

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.

It is very important that we give an error to the client in this case and block the creation of the sandbox. Otherwise the sandbox will not have as many restrictions as the user might think it has and bad things might happen.

A user of the client will generally not read any warning logs of the backend.

@xyuzh xyuzh Sep 15, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done in fc0f001: an ALLOWLIST network policy now fails SandboxCreate with INVALID_ARGUMENT ("network allowlists (cidr_allowlist) are not supported by the Ray Sandbox gRPC facade; use block_network=True for no network, or omit both for open egress"), so no sandbox is created with wider access than the client asked for. test_network_allowlist_is_refused checks the error and that no actor was created.


async def TaskSetNetworkAccess(self, stream: Any) -> None:
await stream.recv_message()
logger.warning(

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.

We should also give an error here

@xyuzh xyuzh Sep 15, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done in fc0f001: TaskSetNetworkAccess now raises UNIMPLEMENTED ("network policy is fixed when the sandbox is created") instead of acknowledging and ignoring the request. test_set_network_access_is_refused covers it.

class _ExecRecord:
"""One client exec id and how the facade services it."""

kind: str # "host" (a SandboxHost exec job) or "fs" (an emulated file op)

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.

host is a little misleading since it still executes in the sandbox, maybe sandbox or something else?

@xyuzh xyuzh Sep 15, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Renamed in fc0f001: the record kind is now "sandbox" (a command running in the sandbox, as a SandboxHost exec job) or "fs" (an emulated filesystem op), with sandbox_exec_id, _await_sandbox_exec, _exec_exit_code, and _exec_stream to match.

@xyuzh
xyuzh force-pushed the sandbox-modal-facade branch from f3d780e to 233fbb6 Compare September 25, 2026 02:36

@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 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 233fbb6. Configure here.

if request.eof and not record.stdin_closed:
record.stdin_closed = True
if record.fs_write:
await self._finish_write(record)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Capped write can become success

Medium Severity

A WriteFile that exceeds max_file_bytes marks the exec failed and raises RESOURCE_EXHAUSTED, but it never sets stdin_closed. A later EOF-only TaskExecStdinWrite (or stream end) still calls _finish_write, which writes an empty file and finish(0) overwrites the error. The client then sees a successful empty write.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 233fbb6. 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 looks good to me! One thing that is currently a little undesirable is the fact that the Modal facade is not just a proxy for the HTTP API but rather reaches into the actual implementation and needs to be connected to the Ray cluster. Designing things such that that's not necessary (in particular, this would mean to design the HTTP API such that it exposes all the needed functionality to implement the grpc API) would make some use cases easier, like users running their own gRPC proxies outside of the cluster.

@pcmoritz
pcmoritz merged commit ce7f78f into ray-project:master Sep 26, 2026
6 checks passed
pcmoritz added a commit that referenced this pull request Oct 6, 2026
## Description

The Ray Sandbox gRPC facade
(`ray.experimental.sandbox.http.grpc_facade`) served sandbox create,
exec, and file read/write to any client that could reach its port.
Unlike the REST app, it never read `RAY_SANDBOX_API_TOKEN`, so even an
operator who wanted to lock it down couldn't, and the documented
quickstart binds `--host 0.0.0.0`.

With this PR:

- **The token is required on every RPC.** When `RAY_SANDBOX_API_TOKEN`
is set, a call that doesn't present it fails with `UNAUTHENTICATED`
before its handler reads the request.
- A client presents the token the way the client SDK already sends
credentials: as its token secret (`x-modal-token-secret`, from
`MODAL_TOKEN_SECRET`), or as `authorization: Bearer <token>`, the REST
app's form, which `MODAL_OVERRIDE_HEADERS` can also send.
- `TaskGetCommandRouterAccess` hands out the token as the command
router's credential. The SDK then sends it as a bearer token on every
exec and file call, so an unmodified client only needs
`MODAL_TOKEN_SECRET` set.
- A bearer-only check wouldn't work with the SDK: its control-plane
calls carry the token secret, and its router calls carry only the
credential that `TaskGetCommandRouterAccess` returned.
- **The check is bound to the servicers, not to one server.**
`_TokenGate` wraps the handler table (`__mapping__`) that
`grpclib.server.Server` dispatches through. So every server built from
`build_servicers` is gated, including RPCs added later, such as #66359's
`TaskSetNetworkAccess`. Without a token the table is returned unchanged.
- **The CLI fails closed.** Without a token, `python -m
ray.experimental.sandbox.http.grpc_facade` refuses a non-loopback
`--host` unless `--allow-unauthenticated` is passed.
- Keeping the facade on a private network isn't enough on its own. The
facade's sandboxes get open egress by default and can reach any address
their node can, including the facade's. So a tokenless facade on a
network address would also serve the code running inside them.
- Loopback binds stay tokenless, since `--disable-host-loopback` keeps
sandboxes off the node's loopback.
- **Docs.** The gRPC section now covers:
  - the token;
- the trust model: one token controls every sandbox in the namespace, as
with the REST token, with no per-client isolation;
  - the TLS requirement;
- a fix for the stale network bullet: allowlists are refused, not
widened.
- **REST.** `require_bearer_token` compares bytes, so a non-ASCII
`Authorization` header gets a 401 instead of a `TypeError` and a 500.

**Behavior change:** a tokenless facade started with a non-loopback
`--host`, as the old quickstart did, now exits with an error that names
`RAY_SANDBOX_API_TOKEN` and `--allow-unauthenticated`.

**This PR also fixes the failing `:ray: core: sandbox tests` job** (for
example premerge build 74278 and microcheck build 55110).
- `test_image_utils.py::test_seeding_stays_inside_the_tree` linked the
fake image's `/tmp` to an absolute path under pytest's `tmp_path`, which
is itself under `/tmp` in CI.
- From the image's point of view that's a symlink loop.
`_resolve_in_root` correctly reports it as `ELOOP`, so nothing was
seeded.
- The test now gives `tmp` its own tree with a relative link. The
product code is unchanged.
- The test only passed on macOS because `tmp_path` lives under
`/private/var/folders` there.

## Related issues

Related to #65839 (the facade) and #65352 (sandboxing umbrella).

Not a duplicate: no open PR or issue covers facade authentication. I
searched open PRs and issues for `grpc_facade`, `RAY_SANDBOX_API_TOKEN`,
and sandbox authentication.

## Additional information

**Tests run.** Environment: macOS, Python 3.12, the ray 2.58 wheel with
this branch's sandbox package overlaid, grpclib 0.4.9.

| Command | Result |
| --- | --- |
| `pytest --import-mode=importlib
python/ray/experimental/sandbox/http/tests` | 130 passed, 8 skipped
(modal not installed, `TEST_SANDBOX` unset) |
| The same, with `RAY_SANDBOX_API_TOKEN=ambient` exported | 130 passed,
8 skipped |
| `uv run --with modal==1.5.5 pytest
.../http/tests/test_modal_client.py` | 6 passed |
| `uv run --with modal==1.5.1 pytest
.../http/tests/test_modal_client.py` | 5 passed, 1 skipped (1.5.1 can't
send custom headers) |
| The new auth tests against `origin/master`'s `grpc_facade.py` | 29
failed, as expected |
| `test_image_utils.py::test_seeding_stays_inside_the_tree`, with the
default `tmp_path` and with `tmp_path` under `/tmp` | Passed both ways
(the old test fails with `tmp_path` under `/tmp`) |
| `python -m ray.experimental.sandbox.http.grpc_facade --host 0.0.0.0`
without a token | Exit 2, before connecting to the cluster |
| Unauthenticated create path replayed against a local Ray cluster |
Anonymous and wrong-token `AppGetOrCreate`, `ImageGetOrCreate`, and
`SandboxCreate` return `UNAUTHENTICATED` and create no actor. With the
token, a `SandboxHost` actor is created and then terminated. |
| `pre-commit` (ruff, pydoclint, docstyle, import order), black 22.10.0,
API param coverage check | Pass |

`test_grpc_facade.py` and `test_modal_client.py` skip in CI because
grpclib and modal aren't in the CI image, so the auth tests above ran
locally only.

AI assistance was used to write this change.

Signed-off-by: xyuzh <[email protected]>
Co-authored-by: Philipp Moritz <[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]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…#66675)

## Description

The Ray Sandbox gRPC facade
(`ray.experimental.sandbox.http.grpc_facade`) served sandbox create,
exec, and file read/write to any client that could reach its port.
Unlike the REST app, it never read `RAY_SANDBOX_API_TOKEN`, so even an
operator who wanted to lock it down couldn't, and the documented
quickstart binds `--host 0.0.0.0`.

With this PR:

- **The token is required on every RPC.** When `RAY_SANDBOX_API_TOKEN`
is set, a call that doesn't present it fails with `UNAUTHENTICATED`
before its handler reads the request.
- A client presents the token the way the client SDK already sends
credentials: as its token secret (`x-modal-token-secret`, from
`MODAL_TOKEN_SECRET`), or as `authorization: Bearer <token>`, the REST
app's form, which `MODAL_OVERRIDE_HEADERS` can also send.
- `TaskGetCommandRouterAccess` hands out the token as the command
router's credential. The SDK then sends it as a bearer token on every
exec and file call, so an unmodified client only needs
`MODAL_TOKEN_SECRET` set.
- A bearer-only check wouldn't work with the SDK: its control-plane
calls carry the token secret, and its router calls carry only the
credential that `TaskGetCommandRouterAccess` returned.
- **The check is bound to the servicers, not to one server.**
`_TokenGate` wraps the handler table (`__mapping__`) that
`grpclib.server.Server` dispatches through. So every server built from
`build_servicers` is gated, including RPCs added later, such as ray-project#66359's
`TaskSetNetworkAccess`. Without a token the table is returned unchanged.
- **The CLI fails closed.** Without a token, `python -m
ray.experimental.sandbox.http.grpc_facade` refuses a non-loopback
`--host` unless `--allow-unauthenticated` is passed.
- Keeping the facade on a private network isn't enough on its own. The
facade's sandboxes get open egress by default and can reach any address
their node can, including the facade's. So a tokenless facade on a
network address would also serve the code running inside them.
- Loopback binds stay tokenless, since `--disable-host-loopback` keeps
sandboxes off the node's loopback.
- **Docs.** The gRPC section now covers:
  - the token;
- the trust model: one token controls every sandbox in the namespace, as
with the REST token, with no per-client isolation;
  - the TLS requirement;
- a fix for the stale network bullet: allowlists are refused, not
widened.
- **REST.** `require_bearer_token` compares bytes, so a non-ASCII
`Authorization` header gets a 401 instead of a `TypeError` and a 500.

**Behavior change:** a tokenless facade started with a non-loopback
`--host`, as the old quickstart did, now exits with an error that names
`RAY_SANDBOX_API_TOKEN` and `--allow-unauthenticated`.

**This PR also fixes the failing `:ray: core: sandbox tests` job** (for
example premerge build 74278 and microcheck build 55110).
- `test_image_utils.py::test_seeding_stays_inside_the_tree` linked the
fake image's `/tmp` to an absolute path under pytest's `tmp_path`, which
is itself under `/tmp` in CI.
- From the image's point of view that's a symlink loop.
`_resolve_in_root` correctly reports it as `ELOOP`, so nothing was
seeded.
- The test now gives `tmp` its own tree with a relative link. The
product code is unchanged.
- The test only passed on macOS because `tmp_path` lives under
`/private/var/folders` there.

## Related issues

Related to ray-project#65839 (the facade) and ray-project#65352 (sandboxing umbrella).

Not a duplicate: no open PR or issue covers facade authentication. I
searched open PRs and issues for `grpc_facade`, `RAY_SANDBOX_API_TOKEN`,
and sandbox authentication.

## Additional information

**Tests run.** Environment: macOS, Python 3.12, the ray 2.58 wheel with
this branch's sandbox package overlaid, grpclib 0.4.9.

| Command | Result |
| --- | --- |
| `pytest --import-mode=importlib
python/ray/experimental/sandbox/http/tests` | 130 passed, 8 skipped
(modal not installed, `TEST_SANDBOX` unset) |
| The same, with `RAY_SANDBOX_API_TOKEN=ambient` exported | 130 passed,
8 skipped |
| `uv run --with modal==1.5.5 pytest
.../http/tests/test_modal_client.py` | 6 passed |
| `uv run --with modal==1.5.1 pytest
.../http/tests/test_modal_client.py` | 5 passed, 1 skipped (1.5.1 can't
send custom headers) |
| The new auth tests against `origin/master`'s `grpc_facade.py` | 29
failed, as expected |
| `test_image_utils.py::test_seeding_stays_inside_the_tree`, with the
default `tmp_path` and with `tmp_path` under `/tmp` | Passed both ways
(the old test fails with `tmp_path` under `/tmp`) |
| `python -m ray.experimental.sandbox.http.grpc_facade --host 0.0.0.0`
without a token | Exit 2, before connecting to the cluster |
| Unauthenticated create path replayed against a local Ray cluster |
Anonymous and wrong-token `AppGetOrCreate`, `ImageGetOrCreate`, and
`SandboxCreate` return `UNAUTHENTICATED` and create no actor. With the
token, a `SandboxHost` actor is created and then terminated. |
| `pre-commit` (ruff, pydoclint, docstyle, import order), black 22.10.0,
API param coverage check | Pass |

`test_grpc_facade.py` and `test_modal_client.py` skip in CI because
grpclib and modal aren't in the CI image, so the auth tests above ran
locally only.

AI assistance was used to write this change.

Signed-off-by: xyuzh <[email protected]>
Co-authored-by: Philipp Moritz <[email protected]>
sai-miduthuri added a commit that referenced this pull request Oct 9, 2026
…C facade (#66675) (#66897)

Cherry-pick of #66675 (master commit
4f967ab) onto `releases/2.60.0`.

## Why

- **The gRPC facade ships without authentication on this branch.**
`releases/2.60.0` includes the sandbox gRPC facade (#65839) but not
#66675, which makes it require the API token. This pick brings the
branch's facade in line with master.
- **It fixes the `:ray: core: sandbox tests` job on this branch.** For
example, it fails in microcheck build 55893 for #66801.
`test_image_utils.py::test_seeding_stays_inside_the_tree` linked the
fake image's `/tmp` to an absolute path under pytest's `tmp_path`, which
is itself under `/tmp` in CI. #66675 fixes the test, and the product
code is unchanged. The branch already has #65815, which made the sandbox
tests actually run in CI instead of skipping.

## Cherry-pick details

Applied cleanly with `git cherry-pick -x`. The diff is byte-identical to
the master commit: the same 10 files, 726 insertions and 29 deletions,
with identical hunks, context lines and offsets.

No prerequisite commits are missing:

- No commit on master between the branch cut and #66675 touched
`python/ray/experimental/sandbox/` or
`doc/source/ray-core/sandboxes.md`. Neither did any commit on this
branch after the cut.
- After the pick, the whole `python/ray/experimental/sandbox/` package
and `doc/source/ray-core/sandboxes.md` are identical to master at
4f967ab.
- Outside the sandbox package, the picked code imports only
`ray.util.annotations`, which is identical on both branches.

Not a duplicate: no existing PR against `releases/2.60.0` references
#66675.

## Testing

`test_grpc_facade.py` and `test_modal_client.py` skip in CI because
`grpclib` and `modal` aren't in the CI image, so I ran them locally.

Environment: Linux, Python 3.10, `grpclib` 0.4.9 and `modal` 1.5.5 (the
versions #66675 used). Other test dependencies were pinned from
`python/requirements_compiled.txt`. Ray was the CI-built `ray-2.60.0`
wheel for this PR's parent commit (b7a4529), with the wheel's
`ray/experimental/sandbox/` replaced by this branch's copy.

| Command | Code under test | Result |
|---|---|---|
| `pytest .../http/tests/test_grpc_facade.py
.../http/tests/test_modal_client.py` | this PR | 58 passed (52 + 6), 0
skipped |
| `pytest .../http/tests` | this PR | 136 passed, 2 skipped
(`test_http_integration.py`, `TEST_SANDBOX` unset) |
| Same two files, the branch's tests before this pick |
`releases/2.60.0` | 24 passed |
| This PR's two test files | `releases/2.60.0` (before this pick) | 30
failed, 28 passed: every token/auth test fails, as expected |

`test_image_utils.py::test_seeding_stays_inside_the_tree` and the 2
skipped `test_http_integration.py` cases run in CI's `:ray: core:
sandbox tests` job, which sets `TEST_SANDBOX=1`.

AI assistance was used to prepare this cherry-pick.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: xyuzh <[email protected]>
Signed-off-by: Sai Miduthuri <[email protected]>
Co-authored-by: Xinyu Zhang <[email protected]>
Co-authored-by: Philipp Moritz <[email protected]>
pcmoritz pushed a commit that referenced this pull request Oct 12, 2026
## Description

Lets Ray Serve deploy the Modal-compatible gRPC facade (#65839), so a
Serve application, such as an Anyscale service, exposes the facade from
configuration alone. The facade itself becomes a standard `grpc`
servicer, which both its own server and Serve's gRPC proxy call:

- Each RPC is a method named after it that takes the request and the
call's context (as `grpc_context`, the name Serve passes it under) and
returns or yields its replies. The vendored service stubs are now
grpcio's (`*_pb2_grpc.py`, from the same pinned grpcio-tools), so the
facade no longer needs grpclib, and `python -m
ray.experimental.sandbox.http.grpc_facade` runs a `grpc.aio` server.
- `RaySandboxFacade` serves both services over one state. One decorator
checks the API token (#66675) before a handler runs and ends a failed
call with its status: through `abort()` on `grpc.aio`, and on Serve,
whose context has no `abort()`, by setting the status on the context and
raising.
- `grpc_facade.add_servicers_to_server`, for
`grpc_options.grpc_servicer_functions`, registers the client SDK's two
services under their wire names.
- `grpc_app.build_app` builds a one-replica deployment of the facade's
servicer. `build_app` refuses to build without `RAY_SANDBOX_API_TOKEN`,
and the replica refuses to start without the token in its own
environment, which can lack what `build_app` saw (as with `serve run`
outside the cluster). Serve's proxies listen on every node's address,
which sandboxes with network access can reach.
- Without a configured `advertise_url`, the facade gives each client
`https://` plus the host it dialed (`x-modal-host`) as its
command-router URL, which suits a TLS endpoint in front of the proxy.
- Docs: a "Serve the facade with Ray Serve" section in
`doc/source/core/sandboxes.md`, with the Anyscale service config, and
two notes about clients:
- Client SDK 1.6+ needs `MODAL_SANDBOX_V2=0`, because 1.6 made a newer
sandbox API its default and the facade doesn't serve it. The client SDK
tests set it too.
- The TLS endpoint in front of the facade must accept HTTP/2 without
ALPN, because the SDK's command-router connection offers none. Envoy
does; ingress-nginx doesn't. So on Anyscale, the service belongs on a
Kubernetes cloud that routes services through an Envoy Gateway.

## Related issues

Related to #65839 (the facade) and #66675 (its API token). #66821,
stacked on this one, makes the facade fast under bursts of sandboxes.

## Additional information

- Not a duplicate: no open PR serves the facade through Ray Serve. I
searched open PRs for `grpc_app`, "sandbox facade Serve" and "sandbox
gRPC facade".
- Tests:
- `pytest python/ray/experimental/sandbox/http/tests` on macOS with the
Ray 2.58.0 wheel (with Serve and the Modal SDK 1.6.1 installed) and this
branch's `ray.experimental.sandbox`: 157 passed, 2 skipped (the two
`TEST_SANDBOX=1` integration tests). This includes the unmodified SDK
against both the facade's `grpc.aio` server and a local Ray Serve gRPC
proxy: sandbox create, exec, a multi-message file-write stream, and a
rejected token.
- With CI's pins (grpcio 1.75.0, protobuf 5.27.5) and without grpclib,
Serve or modal installed: `test_grpc_facade.py`, `test_grpc_app.py` and
`test_modal_client.py` gave 70 passed, 9 skipped (the Serve and SDK
end-to-end tests). The facade's wire tests no longer need grpclib, so CI
now runs them instead of skipping them.
- `pre-commit run --files <changed files>` with pre-commit 3.5.0 (every
hook that applies, including both ruff hooks, pydoclint and black) and
the API parameter coverage check
(`ci/ray_ci/doc/cmd_check_api_param_coverage.py --base-ref origin/master
--blocking`) pass.
- End to end with the stock Modal SDK (1.6.1, no patch), before the
facade became a `grpc` servicer (the first revision served it through an
adapter in `grpc_app`): this app ran as an Anyscale staging service on a
Kubernetes cloud whose edge is Envoy Gateway.
- The SDK created sandboxes, ran commands in them (exit code, stdout,
stderr, line streaming, secrets, workdir), wrote and read files,
reattached, and terminated them.
- Uploads and downloads of up to 64 MiB passed, and so did reading a
command's output before `wait()` while it stayed silent for 720 s.
- A command-router call over TLS without ALPN reached the facade, and
calls without the token got UNAUTHENTICATED.
- Behind ingress-nginx, the same SDK creates sandboxes, but its
command-router calls fail, as the docs now say.
- The burst benchmarks in #66821 also ran this app as an Anyscale
service, on a 16-node EKS staging cluster behind ingress-nginx, with a
one-line ALPN fix applied to the client SDK.
- AI assistance (Claude Code) was used to prepare this change.

---------

Signed-off-by: xyuzh <[email protected]>
pcmoritz added a commit that referenced this pull request Oct 21, 2026
…t and enforce allowlists (#66359)

## Description

A `network="public"` sandbox could reach everything its pod reaches.
From a sandbox in a CoreWeave pod running a Ray head, GCS, the Ray
client server, the raylet, the object manager, the dashboard agent, the
Kubernetes API, the kubelet, and 169.254.169.254 all accepted
connections. Ray's ports take no token unless the cluster runs with
`RAY_AUTH_MODE=token`, and slirp4netns relays sandbox flows through the
pod's own sockets, so a pod NetworkPolicy can't single them out.

This PR filters every `public` sandbox's egress with an nftables ruleset
in its private network namespace, loaded after slirp4netns brings the
tap up and before runsc starts. A failed load fails the create.

- `cidr_allowlist` defaults to `["internet"]`, public addresses only.
Entries are addresses or networks with optional ports (`10.0.0.5:8000`,
`internet:443`).
- A denylist runs before any list: link-local (instance metadata),
loopback, Alibaba Cloud's and Azure's metadata endpoints, the Kubernetes
API Service, and `RAY_SANDBOX_EGRESS_DENY`. Ray doesn't track its nodes,
as pcmoritz suggested: `internet` leaves them out while their addresses
are internal, which the docs call a best effort, and an operator who
allows internal networks lists the nodes' network in
`RAY_SANDBOX_EGRESS_DENY`, which also covers nodes the autoscaler adds.
- `set_egress_allowlist`, on `SandboxRuntime` and on the actor that
`sandbox.create()` returns, replaces any public sandbox's ruleset in one
`nft -f`, entering its namespaces through fds checked against the ones
recorded at creation.
- With `dns` set, the create sends each resolver one UDP byte from
inside the sandbox and fails, naming the resolver, if the send fails. On
Cilium, which translates the cluster DNS Service IP before the filter
sees it, every lookup failed instead.
- The gRPC facade maps `block_network`, `outbound_cidr_allowlist`, and
`TaskSetNetworkAccess`; open access means `internet`.
- The REST API answers 403 to `network="host"`, `"sandbox"`, or
`rootless=false` unless `allowed_network_modes` / `allow_rootful` allow
them, and `build_app` requires `RAY_SANDBOX_API_TOKEN` unless
`allow_unauthenticated` is set.

Behavior changes: `public` needs `nft` on the node, no longer reaches
private networks without a list, and fails to create when a `dns`
resolver is unreachable. REST deployments need a token.

### Why nftables inside the sandbox netns is the right enforcement point

Inside the sandbox's private user + net namespace, the host-side launch
script has CAP_NET_ADMIN over that child network namespace (without
needing CAP_NET_ADMIN on the Kubernetes worker pod itself).

runsc runs inside that child netns with --network=host. That means
gVisor's hostinet creates real Linux kernel AF_INET/AF_INET6 sockets
inside the child netns, so every packet from the sandbox passes through
the Linux kernel's nf_tables output chain before reaching slirp4netns's
tap0.

**Why sandbox code cannot tamper with the rules (even with
CAP_NET_ADMIN):** gVisor's Sentry intercepts all syscalls inside the
sandbox. Even if the container process has CAP_NET_ADMIN or CAP_NET_RAW,
gVisor's hostinet (without --net-raw) never forwards AF_NETLINK
(NETLINK_NETFILTER / NETLINK_ROUTE) or AF_PACKET sockets to the host
kernel. Running nft flush ruleset or iptables -F inside the sandbox
talks only to gVisor's internal Sentry stub, never touching the host
kernel netns where the rules live.

### Results

TCP connects from a sandbox in a CoreWeave (Cilium) pod running a Ray
head, 5 s timeout, measured on dddd170:

| Destination | Default | `ALLOW_ALL_CIDRS` | +
`RAY_SANDBOX_EGRESS_DENY=<node>,<API server>` |
| --- | --- | --- | --- |
| GCS, Ray client server, raylet, object manager, dashboard | timeout |
open | timeout |
| 169.254.169.254:80 | timeout | timeout | timeout |
| Kubernetes API (Service and endpoint) | timeout | open | timeout |
| 1.1.1.1:443, DNS | open | open | open |

Allow-all reaches the Ray head's ports because Ray doesn't track its
nodes, and it reaches the API Service because Cilium rewrites it to the
API server's address at connect time; `RAY_SANDBOX_EGRESS_DENY` closes
both, and the docs say so. Root in a sandbox with `CAP_NET_ADMIN` and
`CAP_NET_RAW` ran `nft flush ruleset` and `iptables -F`: both failed
with "Protocol not supported", and GCS stayed closed.

How to review: `config.py`, `_internal/egress_guard.py`,
`backend/gvisor.py` (`_render_egress_ruleset`, the run command,
`set_egress_allowlist`, `_unreachable_resolver`), `http/host.py` and
`http/grpc_facade.py`, `http/schemas.py` and `http/app.py`, then the
docs. Skip the `_pb2.py` files.

## Related issues

Follows #65839. Found through SkyRL's SWE-bench Multimodal runs on Ray
Sandbox (skyrl-project/SkyRL#2467). #66782 and #67010 inherit the default.
#66471's restore path needs the same nft install.

## Additional information

- Not a duplicate: none of the 20 open sandbox PRs adds egress filtering
or a default deny.
- Tests on a CoreWeave pod (Cilium, runsc release-20261012.0, root),
rebased on master 7073066: `TEST_SANDBOX=1 pytest
tests/test_gvisor_backend.py tests/test_image_manager.py
tests/test_image_utils.py tests/test_sandbox_config.py
tests/test_sandbox_runtime.py tests/test_egress_guard.py -k "not netns
and not test_create_sandbox_helper"`: 167 passed, 1 skipped. `-k netns`:
22 passed. `test_create_sandbox_helper`: 1 passed.
`tests/test_sandbox.py`: 7 passed. `http/tests`: 167 passed, 10 skipped.
With the Modal SDK 1.5.5 installed on macOS, which CI doesn't have,
`http/tests`: 175 passed, 2 skipped (the gVisor integration tests). On
the pod, `dns=["10.16.0.10"]`, the cluster DNS Service, now fails the
create with "Operation not permitted" and still resolves with
`ALLOW_ALL_CIDRS`; the check adds about 14 ms to a create. pre-commit
passes. This round wasn't rerun as uid 1000.
- I used Claude Code to help write and test this change.

---------

Signed-off-by: xyuzh <[email protected]>
Co-authored-by: Philipp Moritz <[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]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Oct 23, 2026
…#66675)

## Description

The Ray Sandbox gRPC facade
(`ray.experimental.sandbox.http.grpc_facade`) served sandbox create,
exec, and file read/write to any client that could reach its port.
Unlike the REST app, it never read `RAY_SANDBOX_API_TOKEN`, so even an
operator who wanted to lock it down couldn't, and the documented
quickstart binds `--host 0.0.0.0`.

With this PR:

- **The token is required on every RPC.** When `RAY_SANDBOX_API_TOKEN`
is set, a call that doesn't present it fails with `UNAUTHENTICATED`
before its handler reads the request.
- A client presents the token the way the client SDK already sends
credentials: as its token secret (`x-modal-token-secret`, from
`MODAL_TOKEN_SECRET`), or as `authorization: Bearer <token>`, the REST
app's form, which `MODAL_OVERRIDE_HEADERS` can also send.
- `TaskGetCommandRouterAccess` hands out the token as the command
router's credential. The SDK then sends it as a bearer token on every
exec and file call, so an unmodified client only needs
`MODAL_TOKEN_SECRET` set.
- A bearer-only check wouldn't work with the SDK: its control-plane
calls carry the token secret, and its router calls carry only the
credential that `TaskGetCommandRouterAccess` returned.
- **The check is bound to the servicers, not to one server.**
`_TokenGate` wraps the handler table (`__mapping__`) that
`grpclib.server.Server` dispatches through. So every server built from
`build_servicers` is gated, including RPCs added later, such as ray-project#66359's
`TaskSetNetworkAccess`. Without a token the table is returned unchanged.
- **The CLI fails closed.** Without a token, `python -m
ray.experimental.sandbox.http.grpc_facade` refuses a non-loopback
`--host` unless `--allow-unauthenticated` is passed.
- Keeping the facade on a private network isn't enough on its own. The
facade's sandboxes get open egress by default and can reach any address
their node can, including the facade's. So a tokenless facade on a
network address would also serve the code running inside them.
- Loopback binds stay tokenless, since `--disable-host-loopback` keeps
sandboxes off the node's loopback.
- **Docs.** The gRPC section now covers:
  - the token;
- the trust model: one token controls every sandbox in the namespace, as
with the REST token, with no per-client isolation;
  - the TLS requirement;
- a fix for the stale network bullet: allowlists are refused, not
widened.
- **REST.** `require_bearer_token` compares bytes, so a non-ASCII
`Authorization` header gets a 401 instead of a `TypeError` and a 500.

**Behavior change:** a tokenless facade started with a non-loopback
`--host`, as the old quickstart did, now exits with an error that names
`RAY_SANDBOX_API_TOKEN` and `--allow-unauthenticated`.

**This PR also fixes the failing `:ray: core: sandbox tests` job** (for
example premerge build 74278 and microcheck build 55110).
- `test_image_utils.py::test_seeding_stays_inside_the_tree` linked the
fake image's `/tmp` to an absolute path under pytest's `tmp_path`, which
is itself under `/tmp` in CI.
- From the image's point of view that's a symlink loop.
`_resolve_in_root` correctly reports it as `ELOOP`, so nothing was
seeded.
- The test now gives `tmp` its own tree with a relative link. The
product code is unchanged.
- The test only passed on macOS because `tmp_path` lives under
`/private/var/folders` there.

## Related issues

Related to ray-project#65839 (the facade) and ray-project#65352 (sandboxing umbrella).

Not a duplicate: no open PR or issue covers facade authentication. I
searched open PRs and issues for `grpc_facade`, `RAY_SANDBOX_API_TOKEN`,
and sandbox authentication.

## Additional information

**Tests run.** Environment: macOS, Python 3.12, the ray 2.58 wheel with
this branch's sandbox package overlaid, grpclib 0.4.9.

| Command | Result |
| --- | --- |
| `pytest --import-mode=importlib
python/ray/experimental/sandbox/http/tests` | 130 passed, 8 skipped
(modal not installed, `TEST_SANDBOX` unset) |
| The same, with `RAY_SANDBOX_API_TOKEN=ambient` exported | 130 passed,
8 skipped |
| `uv run --with modal==1.5.5 pytest
.../http/tests/test_modal_client.py` | 6 passed |
| `uv run --with modal==1.5.1 pytest
.../http/tests/test_modal_client.py` | 5 passed, 1 skipped (1.5.1 can't
send custom headers) |
| The new auth tests against `origin/master`'s `grpc_facade.py` | 29
failed, as expected |
| `test_image_utils.py::test_seeding_stays_inside_the_tree`, with the
default `tmp_path` and with `tmp_path` under `/tmp` | Passed both ways
(the old test fails with `tmp_path` under `/tmp`) |
| `python -m ray.experimental.sandbox.http.grpc_facade --host 0.0.0.0`
without a token | Exit 2, before connecting to the cluster |
| Unauthenticated create path replayed against a local Ray cluster |
Anonymous and wrong-token `AppGetOrCreate`, `ImageGetOrCreate`, and
`SandboxCreate` return `UNAUTHENTICATED` and create no actor. With the
token, a `SandboxHost` actor is created and then terminated. |
| `pre-commit` (ruff, pydoclint, docstyle, import order), black 22.10.0,
API param coverage check | Pass |

`test_grpc_facade.py` and `test_modal_client.py` skip in CI because
grpclib and modal aren't in the CI image, so the auth tests above ran
locally only.

AI assistance was used to write this change.

Signed-off-by: xyuzh <[email protected]>
Co-authored-by: Philipp Moritz <[email protected]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Oct 23, 2026
## Description

Lets Ray Serve deploy the Modal-compatible gRPC facade (ray-project#65839), so a
Serve application, such as an Anyscale service, exposes the facade from
configuration alone. The facade itself becomes a standard `grpc`
servicer, which both its own server and Serve's gRPC proxy call:

- Each RPC is a method named after it that takes the request and the
call's context (as `grpc_context`, the name Serve passes it under) and
returns or yields its replies. The vendored service stubs are now
grpcio's (`*_pb2_grpc.py`, from the same pinned grpcio-tools), so the
facade no longer needs grpclib, and `python -m
ray.experimental.sandbox.http.grpc_facade` runs a `grpc.aio` server.
- `RaySandboxFacade` serves both services over one state. One decorator
checks the API token (ray-project#66675) before a handler runs and ends a failed
call with its status: through `abort()` on `grpc.aio`, and on Serve,
whose context has no `abort()`, by setting the status on the context and
raising.
- `grpc_facade.add_servicers_to_server`, for
`grpc_options.grpc_servicer_functions`, registers the client SDK's two
services under their wire names.
- `grpc_app.build_app` builds a one-replica deployment of the facade's
servicer. `build_app` refuses to build without `RAY_SANDBOX_API_TOKEN`,
and the replica refuses to start without the token in its own
environment, which can lack what `build_app` saw (as with `serve run`
outside the cluster). Serve's proxies listen on every node's address,
which sandboxes with network access can reach.
- Without a configured `advertise_url`, the facade gives each client
`https://` plus the host it dialed (`x-modal-host`) as its
command-router URL, which suits a TLS endpoint in front of the proxy.
- Docs: a "Serve the facade with Ray Serve" section in
`doc/source/core/sandboxes.md`, with the Anyscale service config, and
two notes about clients:
- Client SDK 1.6+ needs `MODAL_SANDBOX_V2=0`, because 1.6 made a newer
sandbox API its default and the facade doesn't serve it. The client SDK
tests set it too.
- The TLS endpoint in front of the facade must accept HTTP/2 without
ALPN, because the SDK's command-router connection offers none. Envoy
does; ingress-nginx doesn't. So on Anyscale, the service belongs on a
Kubernetes cloud that routes services through an Envoy Gateway.

## Related issues

Related to ray-project#65839 (the facade) and ray-project#66675 (its API token). ray-project#66821,
stacked on this one, makes the facade fast under bursts of sandboxes.

## Additional information

- Not a duplicate: no open PR serves the facade through Ray Serve. I
searched open PRs for `grpc_app`, "sandbox facade Serve" and "sandbox
gRPC facade".
- Tests:
- `pytest python/ray/experimental/sandbox/http/tests` on macOS with the
Ray 2.58.0 wheel (with Serve and the Modal SDK 1.6.1 installed) and this
branch's `ray.experimental.sandbox`: 157 passed, 2 skipped (the two
`TEST_SANDBOX=1` integration tests). This includes the unmodified SDK
against both the facade's `grpc.aio` server and a local Ray Serve gRPC
proxy: sandbox create, exec, a multi-message file-write stream, and a
rejected token.
- With CI's pins (grpcio 1.75.0, protobuf 5.27.5) and without grpclib,
Serve or modal installed: `test_grpc_facade.py`, `test_grpc_app.py` and
`test_modal_client.py` gave 70 passed, 9 skipped (the Serve and SDK
end-to-end tests). The facade's wire tests no longer need grpclib, so CI
now runs them instead of skipping them.
- `pre-commit run --files <changed files>` with pre-commit 3.5.0 (every
hook that applies, including both ruff hooks, pydoclint and black) and
the API parameter coverage check
(`ci/ray_ci/doc/cmd_check_api_param_coverage.py --base-ref origin/master
--blocking`) pass.
- End to end with the stock Modal SDK (1.6.1, no patch), before the
facade became a `grpc` servicer (the first revision served it through an
adapter in `grpc_app`): this app ran as an Anyscale staging service on a
Kubernetes cloud whose edge is Envoy Gateway.
- The SDK created sandboxes, ran commands in them (exit code, stdout,
stderr, line streaming, secrets, workdir), wrote and read files,
reattached, and terminated them.
- Uploads and downloads of up to 64 MiB passed, and so did reading a
command's output before `wait()` while it stayed silent for 720 s.
- A command-router call over TLS without ALPN reached the facade, and
calls without the token got UNAUTHENTICATED.
- Behind ingress-nginx, the same SDK creates sandboxes, but its
command-router calls fail, as the docs now say.
- The burst benchmarks in ray-project#66821 also ran this app as an Anyscale
service, on a 16-node EKS staging cluster behind ingress-nginx, with a
one-line ALPN fix applied to the client SDK.
- AI assistance (Claude Code) was used to prepare this change.

---------

Signed-off-by: xyuzh <[email protected]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 2, 2026
…t and enforce allowlists (ray-project#66359)

## Description

A `network="public"` sandbox could reach everything its pod reaches.
From a sandbox in a CoreWeave pod running a Ray head, GCS, the Ray
client server, the raylet, the object manager, the dashboard agent, the
Kubernetes API, the kubelet, and 169.254.169.254 all accepted
connections. Ray's ports take no token unless the cluster runs with
`RAY_AUTH_MODE=token`, and slirp4netns relays sandbox flows through the
pod's own sockets, so a pod NetworkPolicy can't single them out.

This PR filters every `public` sandbox's egress with an nftables ruleset
in its private network namespace, loaded after slirp4netns brings the
tap up and before runsc starts. A failed load fails the create.

- `cidr_allowlist` defaults to `["internet"]`, public addresses only.
Entries are addresses or networks with optional ports (`10.0.0.5:8000`,
`internet:443`).
- A denylist runs before any list: link-local (instance metadata),
loopback, Alibaba Cloud's and Azure's metadata endpoints, the Kubernetes
API Service, and `RAY_SANDBOX_EGRESS_DENY`. Ray doesn't track its nodes,
as pcmoritz suggested: `internet` leaves them out while their addresses
are internal, which the docs call a best effort, and an operator who
allows internal networks lists the nodes' network in
`RAY_SANDBOX_EGRESS_DENY`, which also covers nodes the autoscaler adds.
- `set_egress_allowlist`, on `SandboxRuntime` and on the actor that
`sandbox.create()` returns, replaces any public sandbox's ruleset in one
`nft -f`, entering its namespaces through fds checked against the ones
recorded at creation.
- With `dns` set, the create sends each resolver one UDP byte from
inside the sandbox and fails, naming the resolver, if the send fails. On
Cilium, which translates the cluster DNS Service IP before the filter
sees it, every lookup failed instead.
- The gRPC facade maps `block_network`, `outbound_cidr_allowlist`, and
`TaskSetNetworkAccess`; open access means `internet`.
- The REST API answers 403 to `network="host"`, `"sandbox"`, or
`rootless=false` unless `allowed_network_modes` / `allow_rootful` allow
them, and `build_app` requires `RAY_SANDBOX_API_TOKEN` unless
`allow_unauthenticated` is set.

Behavior changes: `public` needs `nft` on the node, no longer reaches
private networks without a list, and fails to create when a `dns`
resolver is unreachable. REST deployments need a token.

### Why nftables inside the sandbox netns is the right enforcement point

Inside the sandbox's private user + net namespace, the host-side launch
script has CAP_NET_ADMIN over that child network namespace (without
needing CAP_NET_ADMIN on the Kubernetes worker pod itself).

runsc runs inside that child netns with --network=host. That means
gVisor's hostinet creates real Linux kernel AF_INET/AF_INET6 sockets
inside the child netns, so every packet from the sandbox passes through
the Linux kernel's nf_tables output chain before reaching slirp4netns's
tap0.

**Why sandbox code cannot tamper with the rules (even with
CAP_NET_ADMIN):** gVisor's Sentry intercepts all syscalls inside the
sandbox. Even if the container process has CAP_NET_ADMIN or CAP_NET_RAW,
gVisor's hostinet (without --net-raw) never forwards AF_NETLINK
(NETLINK_NETFILTER / NETLINK_ROUTE) or AF_PACKET sockets to the host
kernel. Running nft flush ruleset or iptables -F inside the sandbox
talks only to gVisor's internal Sentry stub, never touching the host
kernel netns where the rules live.

### Results

TCP connects from a sandbox in a CoreWeave (Cilium) pod running a Ray
head, 5 s timeout, measured on dddd170:

| Destination | Default | `ALLOW_ALL_CIDRS` | +
`RAY_SANDBOX_EGRESS_DENY=<node>,<API server>` |
| --- | --- | --- | --- |
| GCS, Ray client server, raylet, object manager, dashboard | timeout |
open | timeout |
| 169.254.169.254:80 | timeout | timeout | timeout |
| Kubernetes API (Service and endpoint) | timeout | open | timeout |
| 1.1.1.1:443, DNS | open | open | open |

Allow-all reaches the Ray head's ports because Ray doesn't track its
nodes, and it reaches the API Service because Cilium rewrites it to the
API server's address at connect time; `RAY_SANDBOX_EGRESS_DENY` closes
both, and the docs say so. Root in a sandbox with `CAP_NET_ADMIN` and
`CAP_NET_RAW` ran `nft flush ruleset` and `iptables -F`: both failed
with "Protocol not supported", and GCS stayed closed.

How to review: `config.py`, `_internal/egress_guard.py`,
`backend/gvisor.py` (`_render_egress_ruleset`, the run command,
`set_egress_allowlist`, `_unreachable_resolver`), `http/host.py` and
`http/grpc_facade.py`, `http/schemas.py` and `http/app.py`, then the
docs. Skip the `_pb2.py` files.

## Related issues

Follows ray-project#65839. Found through SkyRL's SWE-bench Multimodal runs on Ray
Sandbox (skyrl-project/SkyRL#2467). ray-project#66782 and ray-project#67010 inherit the default.
ray-project#66471's restore path needs the same nft install.

## Additional information

- Not a duplicate: none of the 20 open sandbox PRs adds egress filtering
or a default deny.
- Tests on a CoreWeave pod (Cilium, runsc release-20261012.0, root),
rebased on master 7073066: `TEST_SANDBOX=1 pytest
tests/test_gvisor_backend.py tests/test_image_manager.py
tests/test_image_utils.py tests/test_sandbox_config.py
tests/test_sandbox_runtime.py tests/test_egress_guard.py -k "not netns
and not test_create_sandbox_helper"`: 167 passed, 1 skipped. `-k netns`:
22 passed. `test_create_sandbox_helper`: 1 passed.
`tests/test_sandbox.py`: 7 passed. `http/tests`: 167 passed, 10 skipped.
With the Modal SDK 1.5.5 installed on macOS, which CI doesn't have,
`http/tests`: 175 passed, 2 skipped (the gVisor integration tests). On
the pod, `dns=["10.16.0.10"]`, the cluster DNS Service, now fails the
create with "Operation not permitted" and still resolves with
`ALLOW_ALL_CIDRS`; the check adds about 14 ms to a create. pre-commit
passes. This round wasn't rerun as uid 1000.
- I used Claude Code to help write and test this change.

---------

Signed-off-by: xyuzh <[email protected]>
Co-authored-by: Philipp Moritz <[email protected]>
Signed-off-by: Pawel Beza <[email protected]>
Co-authored-by: Copilot <[email protected]>
Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
pcmoritz added a commit that referenced this pull request Nov 3, 2026
## Description

This PR adds GPU support to Ray Sandboxes by leveraging
[CDI](https://github.com/cncf-tags/container-device-interface)
(Container Device Interface) to inject GPU device nodes and their
supported user-mode driver files into a gVisor sandbox at runtime.

This PR builds on #66470, which adds the overlayfs rootfs that GPU
sandboxes boot from, and on #66469 and #66528 underneath it. Only the
last five commits are new here.

The change is implemented as follows.

- **Generic CDI framework**: We added a vendor-agnostic CDI module that
can be used to parse CDI specs and merge devices from them with a
standard OCI image spec. The implementation of this module is kept free
of any Ray imports so it stays a candidate for extraction into a
standalone library at some point in the future. As part of this,
the`AcceleratorManager` class gains two new optional methods,
`get_cdi_kind()`/`generate_cdi_spec()`. These methods are implemented by
an `AcceleratorManager` to both generate a spec with the full set of CDI
devices associated with the accelerator, as well as advertise what kind
of CDI devices are associated with it (e.g. `nvidia.com/gpu`).

- **NVIDIA specific implementation** : We extended the
`NvidiaGPUAcceleratorManager` to be CDI aware and implement the
`get_cdi_kind()`/`generate_cdi_spec()` methods mentioned above. At
present, we generate CDI devices by shelling out to `nvidia-ctk cdi
generate`, but the preferred long-term path is to build (or leverage) a
canonical python library for CDI maintained upstream. Since gVisor only
supports NVIDIA GPUs at the moment, the `GVisorSandboxBackend` gates GPU
passthrough to CDI kinds it actually supports (i.e. `nvidia.com/gpu`),
rejecting anything else rather than attempting unverified passthrough.

- **`num_gpus` and `gpu_ids`**: When creating a `Sandbox` actor, you can
now pass a `num_gpus` field in addition to the existing `cpu` and
`memory` fields (similar to what is possible when creating a
non-sandboxed actor). When doing so, the sandbox auto-inherits the full
Ray GPU assignment derived from `num_gpus` (with no way to limit it
further when calling `remote()` later on, unlike for cpus and memory).
When creating a sandbox via `SandboxRuntime.create()` (i.e. within a
pre-existing actor), there is no `num_gpus` field supported. Instead, we
allow passing a `gpu_ids` field as an explicit parameter to specify
which of the GPUs that have been granted to the surrounding actor should
be isolated inside the sandbox. This allows a single actor with multiple
GPUs to manage several sandboxes, each pinned to a different GPU.

- **Overlayfs rootfs for GPU sandboxes**: NVIDIA's CDI spec relies on
`createContainer` hooks that create library symlinks and update the
ldcache in the sandbox's rootfs, and runsc creates mount points there
for the driver files and device nodes. The default EROFS rootfs is
read-only and shared by every sandbox of an image, so any sandbox with
`gpu_ids` now runs on #66470's overlayfs rootfs. These writes land in
the sandbox's own upper layer, and the cached image stays untouched.

- **53 new unit tests and 9 real-GPU CI tests**: We added `test_cdi.py`
and `test_cdi_lib.py` under `ray/experimental/sandbox/tests/`, and
extended the existing suites there and under `ray/tests/accelerators/`.
The real-GPU tests run via two new Buildkite jobs (`core: sandbox gpu
tests`, 1 GPU; `core: sandbox multi gpu tests`, 4 GPUs).

Validated end-to-end on an NVIDIA L4 GPU and a machine with 4 NVIDIA
A100 GPUs.

We also tested on a machine with 4 NVIDIA GB200 GPUs (ARM64/Grace CPU).
All of the NVML-based tests passed, but the CUDA tests failed (because
gVisor does not yet fully support GB200). Once gVisor supports GB200 we
will need to revisit things to ensure that multi-node NVLink is properly
supported as well.

## AI assistance

Developed with Claude Code (Sonnet 5), including driving the hardware
validation above. I reviewed every changed line and take responsibility
for the change end-to-end.

## Related issues

No tracking issue. Sibling of other active sandbox work: image cache LRU
eviction (#65748), per-sandbox netns (#65820), HTTP API (#65633), gRPC
facade (#65839), multi-uid netns (#65823); none overlap with this
change.

## Duplicate check

Searched open/closed issues and PRs for `sandbox gpu`, `CDI`, `gvisor`,
`nvproxy`, `nvidia-ctk`, and `container device interface` — nothing
addresses GPU or CDI support for Ray Sandboxes.

## Testing

- `test_gvisor_gpu.py` (real `nvidia-ctk` generation, device injection,
`--nvproxy` boot, `nvidia-smi` inside the sandbox, and a real CUDA
kernel launch via NVIDIA's `vectorAdd` sample) — passes on a machine
with an NVIDIA L4 GPU and a machine with 4 A100 GPUs.

- `test_gvisor_multi_gpu.py` (all four tests, needing 4 GPUs) — only
relies on NVML to test. Passes on both a machine with 4 A100 GPUs and a
machine with 4 GB200 GPUs, each sandbox pinned to a distinct GPU.

- `python/ray/experimental/sandbox/tests/` (full directory, including
the above) — on the L4: 228 passed, 10 skipped. On the GB200 machine, as
root: 283 passed, 3 failed, 1 skipped. As the non-root user `ray`: 269
passed, 3 failed, 15 skipped. The failures are the known CUDA failure
(`test_sandbox_gpu_cuda_vectoradd_runs_a_real_kernel`, see above) and
`test_netns_egress_and_dns` and `test_netns_udp_flows_do_not_cross`,
which need public DNS that this machine's network doesn't provide. The
skipped tests need a worker that can mount in the host's user namespace,
which `ray` can't in this Docker test rig, or the CI sandbox job.

- `pre-commit run` — passed (`SKIP=vale`; its Go/cgo toolchain doesn't
build in this environment).

### Testing manually

Building the published `ray` image needs a wheel via `./build-wheel.sh`,
which needs Anyscale's internal `cr.ray.io`/Bazel-remote-cache access to
build in reasonable time. To avoid long build times, we instead overlay
this branch's changed `.py` files onto a stock published
`rayproject/ray:2.58.0` image, allowing us to test without a core
rebuild since nothing outside pure Python changed. These tests require a
machine with an NVIDIA GPU, Docker, and the
`nvidia-container-toolkit-base` package installed.

Dockerfile:
https://gist.github.com/klueska/9f1297a5d7f5a7b7cf9b31b3fb393feb

Save it locally, then build from a checkout of this branch (the repo
itself is the build context):

```bash
cd ray
curl -fsSL -o Dockerfile.sandbox-gpu-test https://gist.githubusercontent.com/klueska/9f1297a5d7f5a7b7cf9b31b3fb393feb/raw
docker build -t ray-cdi-gpu-test:latest -f Dockerfile.sandbox-gpu-test .
```

Run it. Each test runs twice, once as root and once as the non-root user
`ray`. `--device nvidia.com/gpu=all` for GPU access; `--privileged` is
needed for gVisor in this specific nested-Docker test rig. `--basetemp`
keeps pytest's temporary directories out of `/tmp`, which
`test_image_utils.py::test_seeding_stays_inside_the_tree` requires:

```bash
# Pure-logic CDI tests + real-nvidia-ctk accelerator tests, no gVisor/root needed:
docker run --rm --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_cdi.py \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_cdi_lib.py \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/tests/accelerators/test_nvidia_gpu.py

# The real end-to-end GPU sandbox test: exercises real nvidia-ctk generation, device injection,
# and gVisor --nvproxy passthrough. No host setup needed -- nvidia-persistenced can be running
# or not, both are handled.
# The two commands below run these tests as root and as the non-root user ray.
docker run --rm --privileged --user root --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_gpu.py
docker run --rm --privileged --user ray --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_gpu.py

# The four 4-GPU tests: three check that concurrent sandboxes each get a distinct GPU (separate
# Sandbox actors, SandboxRuntime.create, and one actor pinning each of its sandboxes via
# gpu_ids=...), and one checks that a single sandbox given 2 GPUs sees both.
# Needs a machine with 4 GPUs; `--device nvidia.com/gpu=all` must expose at least 4.
# The two commands below run these tests as root and as the non-root user ray.
docker run --rm --privileged --user root --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_multi_gpu.py
docker run --rm --privileged --user ray --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_multi_gpu.py

# Full sandbox suite (mocked-GPU config/scheduling tests + real-gVisor CPU and GPU tests):
# The two commands below run these tests as root and as the non-root user ray.
docker run --rm --privileged --user root --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/
docker run --rm --privileged --user ray --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/
```

---------

Signed-off-by: Kevin Klues <[email protected]>
Signed-off-by: Philipp Moritz <[email protected]>
Co-authored-by: Philipp Moritz <[email protected]>
dstrodtman added a commit that referenced this pull request Nov 4, 2026
## Description

This PR makes the `lint: API param coverage` step a required check by
removing `soft_fail: true`. The step was added in #64788 on 2026-08-11.
A comment in the step said to remove `soft_fail` "once the
false-positive rate is confirmed low." This PR measures that rate from
the step's CI history and fixes the four failure patterns the history
turned up.

While the step only warns, undocumented parameters still land on master.
#65633, #66602, and #66950 all merged with the check failing.

### Warn-phase metrics

These numbers come from every `premerge` build from 2026-08-11 to
2026-10-29, pulled from the Buildkite API.

| | Runs | PRs |
|---|--:|--:|
| Completed runs of the step | 3,453 | |
| Passed | 3,398 | |
| Failed | 55 | 23 |
| Canceled, which isn't a check outcome | 211 | |

Each failure falls into one of three groups:

| Failure type | PRs | Runs | Detail |
|---|--:|--:|---|
| Correct finding | 15 | 42 | A new parameter on a `@PublicAPI` callable
has no `Args:` entry. Two of these PRs, #65823 and #65839, were stacked
on #65633 before it merged and report its findings again. |
| False positive | 3 | 4 | #64399 flagged the `v` argument of a pydantic
`@field_validator`. #66255 flagged the private kwarg `_direct_http`.
#67258 flagged an option of the `ray start` Click command, which `help=`
documents. |
| Infrastructure | 5 | 9 | The step printed `could not determine
merge-base` and no findings. The branches of #65437 and #65809 forked
520 and 598 master commits before their builds. The step's `git fetch
--depth=500` makes the full CI clone shallow, so their merge-base wasn't
in the fetched history. |

That's 13 spurious failures out of 3,453 runs, about 0.4%, or 13 of 55
failures. Each one would block a PR once the step is required, so this
PR fixes all four patterns before removing `soft_fail`.

### Changes

- **`_`-prefixed parameters:** `api_param_coverage.py` skips parameters
whose names start with `_`. That's Ray's convention for private kwargs,
such as `ray.put(_owner=...)`, `tune.run(_remote=...)`, and
`Deployment.options(_internal=...)`. On master, 31 public callables have
such parameters.
- **Pydantic validators and Click commands:** The script skips callables
decorated with `field_validator`, `model_validator`, `validator`,
`root_validator`, `command`, or `group`. On master, this removes 59
callables from scope. All of them are Click commands, such as `ray
start` and `ray job submit`, or pydantic validators on Serve config
models. None of them is a Python API whose parameters a docstring
documents.
- **Property setters:** The script also skips callables decorated with
`@<name>.setter`. A setter's `value` is documented on the property's
getter, which is the docstring Sphinx renders, not in an `Args:` section
of its own.
- **Shallow-clone merge-base:** When `git merge-base` fails after the
depth-500 fetch, `ci/lint/lint.sh` runs `git fetch --unshallow` and
retries. A branch within 500 commits of the base never reaches that
path. The Python check still fails closed if the base can't be resolved
after that.
- **Step definition:** `.buildkite/lint.rayci.yml` drops `soft_fail:
true` and the warn-phase comment. The `--blocking` help text in
`cmd_check_api_param_coverage.py` no longer describes a warn phase.

## Related issues

Follow-up to #64788.

## Additional information

### Testing

- `pytest ci/ray_ci/doc/test_api_param_coverage.py`: 40 passed. That's
the 28 existing tests plus 12 new cases covering `_` params, each
validator spelling, Click command forms, and property setters. The test
comments name the real PR that motivated each one.
- **Replay against real PRs:** I ran the master and patched versions of
the check against the exact commit and base of every failing run in each
of the 18 PRs with findings. Master reproduces all 18 failures. The
patched check passes #64399, #66255, and #67258, and reports the same
findings as master on the other 15.
- **Merge-base fix:** In a local repo with 600 commits on `master` and a
branch forked at commit 50, `git fetch --depth=500` followed by `git
merge-base` fails, which reproduces the CI failure. With the new
`lint.sh` block, it resolves the correct fork commit. A branch forked 10
commits back resolves without the fallback.
- `pre-commit run` on the changed files passes, including ruff, black,
shellcheck, and docstyle.

### Duplicate check

`gh pr list --state open --search "param coverage"` and `--search
"api_param_coverage"` return no open PR that touches this check. The
script hasn't changed since #65391 on 2026-08-14.

### AI assistance

I used Claude Code to pull and classify the Buildkite history, draft the
changes, and run the replay. I reviewed every changed line and the
classification of every failing PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 9, 2026
…#65898)

## Description

This PR adds GPU support to Ray Sandboxes by leveraging
[CDI](https://github.com/cncf-tags/container-device-interface)
(Container Device Interface) to inject GPU device nodes and their
supported user-mode driver files into a gVisor sandbox at runtime.

This PR builds on ray-project#66470, which adds the overlayfs rootfs that GPU
sandboxes boot from, and on ray-project#66469 and ray-project#66528 underneath it. Only the
last five commits are new here.

The change is implemented as follows.

- **Generic CDI framework**: We added a vendor-agnostic CDI module that
can be used to parse CDI specs and merge devices from them with a
standard OCI image spec. The implementation of this module is kept free
of any Ray imports so it stays a candidate for extraction into a
standalone library at some point in the future. As part of this,
the`AcceleratorManager` class gains two new optional methods,
`get_cdi_kind()`/`generate_cdi_spec()`. These methods are implemented by
an `AcceleratorManager` to both generate a spec with the full set of CDI
devices associated with the accelerator, as well as advertise what kind
of CDI devices are associated with it (e.g. `nvidia.com/gpu`).

- **NVIDIA specific implementation** : We extended the
`NvidiaGPUAcceleratorManager` to be CDI aware and implement the
`get_cdi_kind()`/`generate_cdi_spec()` methods mentioned above. At
present, we generate CDI devices by shelling out to `nvidia-ctk cdi
generate`, but the preferred long-term path is to build (or leverage) a
canonical python library for CDI maintained upstream. Since gVisor only
supports NVIDIA GPUs at the moment, the `GVisorSandboxBackend` gates GPU
passthrough to CDI kinds it actually supports (i.e. `nvidia.com/gpu`),
rejecting anything else rather than attempting unverified passthrough.

- **`num_gpus` and `gpu_ids`**: When creating a `Sandbox` actor, you can
now pass a `num_gpus` field in addition to the existing `cpu` and
`memory` fields (similar to what is possible when creating a
non-sandboxed actor). When doing so, the sandbox auto-inherits the full
Ray GPU assignment derived from `num_gpus` (with no way to limit it
further when calling `remote()` later on, unlike for cpus and memory).
When creating a sandbox via `SandboxRuntime.create()` (i.e. within a
pre-existing actor), there is no `num_gpus` field supported. Instead, we
allow passing a `gpu_ids` field as an explicit parameter to specify
which of the GPUs that have been granted to the surrounding actor should
be isolated inside the sandbox. This allows a single actor with multiple
GPUs to manage several sandboxes, each pinned to a different GPU.

- **Overlayfs rootfs for GPU sandboxes**: NVIDIA's CDI spec relies on
`createContainer` hooks that create library symlinks and update the
ldcache in the sandbox's rootfs, and runsc creates mount points there
for the driver files and device nodes. The default EROFS rootfs is
read-only and shared by every sandbox of an image, so any sandbox with
`gpu_ids` now runs on ray-project#66470's overlayfs rootfs. These writes land in
the sandbox's own upper layer, and the cached image stays untouched.

- **53 new unit tests and 9 real-GPU CI tests**: We added `test_cdi.py`
and `test_cdi_lib.py` under `ray/experimental/sandbox/tests/`, and
extended the existing suites there and under `ray/tests/accelerators/`.
The real-GPU tests run via two new Buildkite jobs (`core: sandbox gpu
tests`, 1 GPU; `core: sandbox multi gpu tests`, 4 GPUs).

Validated end-to-end on an NVIDIA L4 GPU and a machine with 4 NVIDIA
A100 GPUs.

We also tested on a machine with 4 NVIDIA GB200 GPUs (ARM64/Grace CPU).
All of the NVML-based tests passed, but the CUDA tests failed (because
gVisor does not yet fully support GB200). Once gVisor supports GB200 we
will need to revisit things to ensure that multi-node NVLink is properly
supported as well.

## AI assistance

Developed with Claude Code (Sonnet 5), including driving the hardware
validation above. I reviewed every changed line and take responsibility
for the change end-to-end.

## Related issues

No tracking issue. Sibling of other active sandbox work: image cache LRU
eviction (ray-project#65748), per-sandbox netns (ray-project#65820), HTTP API (ray-project#65633), gRPC
facade (ray-project#65839), multi-uid netns (ray-project#65823); none overlap with this
change.

## Duplicate check

Searched open/closed issues and PRs for `sandbox gpu`, `CDI`, `gvisor`,
`nvproxy`, `nvidia-ctk`, and `container device interface` — nothing
addresses GPU or CDI support for Ray Sandboxes.

## Testing

- `test_gvisor_gpu.py` (real `nvidia-ctk` generation, device injection,
`--nvproxy` boot, `nvidia-smi` inside the sandbox, and a real CUDA
kernel launch via NVIDIA's `vectorAdd` sample) — passes on a machine
with an NVIDIA L4 GPU and a machine with 4 A100 GPUs.

- `test_gvisor_multi_gpu.py` (all four tests, needing 4 GPUs) — only
relies on NVML to test. Passes on both a machine with 4 A100 GPUs and a
machine with 4 GB200 GPUs, each sandbox pinned to a distinct GPU.

- `python/ray/experimental/sandbox/tests/` (full directory, including
the above) — on the L4: 228 passed, 10 skipped. On the GB200 machine, as
root: 283 passed, 3 failed, 1 skipped. As the non-root user `ray`: 269
passed, 3 failed, 15 skipped. The failures are the known CUDA failure
(`test_sandbox_gpu_cuda_vectoradd_runs_a_real_kernel`, see above) and
`test_netns_egress_and_dns` and `test_netns_udp_flows_do_not_cross`,
which need public DNS that this machine's network doesn't provide. The
skipped tests need a worker that can mount in the host's user namespace,
which `ray` can't in this Docker test rig, or the CI sandbox job.

- `pre-commit run` — passed (`SKIP=vale`; its Go/cgo toolchain doesn't
build in this environment).

### Testing manually

Building the published `ray` image needs a wheel via `./build-wheel.sh`,
which needs Anyscale's internal `cr.ray.io`/Bazel-remote-cache access to
build in reasonable time. To avoid long build times, we instead overlay
this branch's changed `.py` files onto a stock published
`rayproject/ray:2.58.0` image, allowing us to test without a core
rebuild since nothing outside pure Python changed. These tests require a
machine with an NVIDIA GPU, Docker, and the
`nvidia-container-toolkit-base` package installed.

Dockerfile:
https://gist.github.com/klueska/9f1297a5d7f5a7b7cf9b31b3fb393feb

Save it locally, then build from a checkout of this branch (the repo
itself is the build context):

```bash
cd ray
curl -fsSL -o Dockerfile.sandbox-gpu-test https://gist.githubusercontent.com/klueska/9f1297a5d7f5a7b7cf9b31b3fb393feb/raw
docker build -t ray-cdi-gpu-test:latest -f Dockerfile.sandbox-gpu-test .
```

Run it. Each test runs twice, once as root and once as the non-root user
`ray`. `--device nvidia.com/gpu=all` for GPU access; `--privileged` is
needed for gVisor in this specific nested-Docker test rig. `--basetemp`
keeps pytest's temporary directories out of `/tmp`, which
`test_image_utils.py::test_seeding_stays_inside_the_tree` requires:

```bash
# Pure-logic CDI tests + real-nvidia-ctk accelerator tests, no gVisor/root needed:
docker run --rm --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_cdi.py \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_cdi_lib.py \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/tests/accelerators/test_nvidia_gpu.py

# The real end-to-end GPU sandbox test: exercises real nvidia-ctk generation, device injection,
# and gVisor --nvproxy passthrough. No host setup needed -- nvidia-persistenced can be running
# or not, both are handled.
# The two commands below run these tests as root and as the non-root user ray.
docker run --rm --privileged --user root --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_gpu.py
docker run --rm --privileged --user ray --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_gpu.py

# The four 4-GPU tests: three check that concurrent sandboxes each get a distinct GPU (separate
# Sandbox actors, SandboxRuntime.create, and one actor pinning each of its sandboxes via
# gpu_ids=...), and one checks that a single sandbox given 2 GPUs sees both.
# Needs a machine with 4 GPUs; `--device nvidia.com/gpu=all` must expose at least 4.
# The two commands below run these tests as root and as the non-root user ray.
docker run --rm --privileged --user root --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_multi_gpu.py
docker run --rm --privileged --user ray --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/test_gvisor_multi_gpu.py

# Full sandbox suite (mocked-GPU config/scheduling tests + real-gVisor CPU and GPU tests):
# The two commands below run these tests as root and as the non-root user ray.
docker run --rm --privileged --user root --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/
docker run --rm --privileged --user ray --device nvidia.com/gpu=all ray-cdi-gpu-test:latest \
  python3 -m pytest --basetemp=/home/ray/pytest-tmp -v \
  /home/ray/anaconda3/lib/python3.10/site-packages/ray/experimental/sandbox/tests/
```

---------

Signed-off-by: Kevin Klues <[email protected]>
Signed-off-by: Philipp Moritz <[email protected]>
Co-authored-by: Philipp Moritz <[email protected]>
Signed-off-by: Pawel Beza <[email protected]>
Cherry-picked-from: c46d1e6
Co-authored-by: Copilot <[email protected]>
Copilot-Session: 0baa3cf-af4e-472e-ad89-8f02c6e8be11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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