Skip to content

[core][sandbox] Add an experimental HTTP API service for Ray Sandbox - #65633

Merged
pcmoritz merged 1 commit into
ray-project:masterfrom
xyuzh:sandbox-http-api
Sep 24, 2026
Merged

pcmoritz merged 1 commit into
ray-project:masterfrom
xyuzh:sandbox-http-api

Conversation

@xyuzh

@xyuzh xyuzh commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

Why are these changes needed?

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

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

Design

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

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

E2E validation

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

Update (2026-09-24)

Rebased onto master and addressed the latest review:

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

Related issue number

Follow-up to #65570.

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

Checks

@xyuzh
xyuzh requested review from a team as code owners August 20, 2026 22:37

@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 implements an experimental REST API service for Ray Sandbox, featuring a FastAPI application, a detached SandboxHost actor for background execution, Pydantic schemas, and a comprehensive test suite. The review feedback provides valuable recommendations to improve robustness and performance: handling dead actors gracefully during idempotent creation, caching the runsc binary to prevent disk space leaks, querying sandbox descriptions concurrently using asyncio.gather, wrapping the TTL watchdog shutdown in a try-finally block to guarantee actor self-destruction, and catching SandboxError during file writes to return a client-friendly HTTP 400 instead of an HTTP 500.

@ray-gardener ray-gardener Bot added docs An issue or change related to documentation core Issues that should be addressed in Ray Core labels Aug 21, 2026
@xyuzh
xyuzh force-pushed the sandbox-http-api branch 2 times, most recently from 3569f56 to da92929 Compare August 27, 2026 18:12

@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 review from Douglas Strodtman (Anyscale documentation team), style and grammar only. Claude Code assisted with the mechanics; I read every line and stand behind it.

The prose in the new HTTP API service section is in good shape after your last pass: soft-wrapped, no em dashes, the semicolons and the mid-sentence colon split into sentences, and the bullets read cleanly as a definition list. Approving on the docs side.

Two optional nits below, both stray semicolons in the endpoints table that the rest of the table already splits. Not blocking.

Scope note: this approval covers the prose in doc/source/ray-core/sandboxes.md. The Python and the API design belong to ray-project/ray-core, which still owns the code paths here.

Comment thread doc/source/ray-core/sandboxes.md Resolved
Comment thread doc/source/ray-core/sandboxes.md Resolved

## HTTP API service

Ray Sandbox ships an experimental REST API service so you can manage sandboxes from outside the Ray cluster with nothing but an HTTP client and a bearer token. The service is a FastAPI app on Ray Serve (`ray.experimental.sandbox.http`). Each sandbox is held by a named, detached actor, so the service itself is stateless and its replicas can scale or restart without losing sandboxes.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I believe named detached actors are currently not as scalable as normal actors (e.g. each actor creation has to wait for a roundtrip to the GCS to make sure the names are unique), it would be great to check with @edoakes or @MengjinYan about that and what we should do (it it is indeed a problem)

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.

Fair point, and worth measuring. Where the cost lands today: one named-actor creation per sandbox (a GCS round-trip on top of an image pull and a runsc boot, so tens of milliseconds against seconds), and a name lookup per request from a replica, which is the part that would show up first under load. If it does, the fix stays inside the service: a small controller actor owning an id-to-handle table, or a per-replica handle cache, behind the same REST contract, so no client sees a change. I would rather land the contract with the simple registry and switch the lookup path once a load test gives numbers. Happy to loop in @edoakes and @MengjinYan on the named-actor scaling question; leaving this thread open for your call.

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.

Measured now, on Ray 2.58 locally and on Anyscale staging (one 128-vCPU node, sandboxes created through the #65839 facade by the Modal SDK):

  • The expensive part of a create wasn't the name round trip: the resolver built a fresh ray.remote(SandboxHost) for every sandbox, which re-exported the class each time. That was 9.15 ms per create on the replica's event loop; one cached ActorClass brings it to 0.76 ms, and skipping get_if_exists for fresh random ids saves another ~0.15 ms. Fixed in 9c34aa1, which also moves every resolver call (create, lookup, kill, list) into a worker thread so a GCS round trip never blocks the event loop.
  • Lookups: after the first one, the core worker's named-actor cache serves ray.get_actor locally (0.17 ms, all Python handle construction), and the resolver now caches handles of the sandboxes it creates under fresh ids.
  • GCS held up at the scale I could test: 576 sandboxes plus 3,000 bare named detached actors (3,279 names) on one node, get_actor for a fresh name flat at ~1.3 ms, list_named_actors 10 ms, ~0.25 MB of GCS memory per actor, GCS under 8% CPU during creation.

What I couldn't test is past the published 40k-actor envelope, and one actor per sandbox is also a dedicated Python worker (~71 MiB of a sandbox's ~104 MiB). Both point at a per-node manager actor that owns many sandboxes, which keeps the REST contract; I'd do that as a follow-up with @edoakes / @MengjinYan. Leaving this open for your call.


## HTTP API service

Ray Sandbox ships an experimental REST API service so you can manage sandboxes from outside the Ray cluster with nothing but an HTTP client and a bearer token. The service is a FastAPI app on Ray Serve (`ray.experimental.sandbox.http`). Each sandbox is held by a named, detached actor, so the service itself is stateless and its replicas can scale or restart without losing sandboxes.

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.

Why make sandboxes detached actors instead of replicas? We can treat sandboxes as multiplex ids in serve to do multiplex aware routing, but we can certainly have each serve replica own multiple sandbox actors that can be suspended resumed etc. i think this will be a more scalable system.

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.

The reason for detached actors is failure isolation plus stateless replicas: a sandbox outlives the replica that created it, so Serve can scale replicas up and down or restart them without touching running sandboxes, and any replica can serve any sandbox with no routing state. Replica-owned sandbox actors would tie each sandbox's lifetime to its replica and need multiplex-aware routing so every request lands on the owner. The suspend/resume angle is a good one and the current design does not rule it out: a controller actor owning the sandbox actors, rather than each replica, would give the same lifecycle control while keeping replicas stateless. I would like to revisit with load data rather than change the architecture in this PR; leaving the thread open.

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.

Following up with the load numbers I said I'd bring: on Anyscale staging an idle sandbox costs ~104 MiB PSS, and ~71 MiB of it is the dedicated Python worker behind its detached actor (the gVisor Sentry is 16 MiB). 576 mostly idle SandboxHost workers also used ~14 cores between them. One node still ran 1,000 sandboxes without failures, but you're right that one actor per sandbox is the part to change. I'd move ownership to a per-node manager actor that hosts many sandbox runtimes: replicas stay stateless and any replica can reach any sandbox, and suspend/resume gets a single owner. I'd do that as a follow-up so this PR's contract stays put. Happy to discuss the shape here.

xyuzh added a commit to xyuzh/harbor that referenced this pull request Aug 31, 2026
A new -e ray-sandbox environment that talks to a deployed
ray.experimental.sandbox.http service (ray-project/ray#65633) over plain
HTTPS with a bearer token — no ray dependency, no cluster connectivity,
zero new Harbor dependencies (httpx and tenacity are core deps):

    export RAY_SANDBOX_API_URL=https://<service-url>
    export RAY_SANDBOX_API_KEY=<service bearer token>
    harbor run -t <task> -e ray-sandbox

Sandboxes run the task's prebuilt image under gVisor on the service's
Ray cluster. Creation and execution are submit-and-poll so every HTTP
request stays short regardless of image pull or command duration; the
client retries narrowly (connection errors and 502/503/504 on idempotent
calls only, Modal-style) and creation is idempotent via client_token.
The task's network policy is authoritative: no-network maps to the
service's none mode and a wider --ek network= override is rejected at
construction; mode values themselves are validated by the service.
pcmoritz pushed a commit that referenced this pull request Sep 23, 2026
…sor backend (#65942)

## Description

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

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

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

## Related issues

Split from #65820 per review.

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

## Additional information

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

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

Signed-off-by: xyuzh <[email protected]>
@pcmoritz pcmoritz added the go add ONLY when ready to merge, run all tests label Sep 23, 2026
@pcmoritz
pcmoritz requested a review from a team as a code owner September 23, 2026 19:49
def __init__(
self,
sandbox_id: str,
spec: Dict[str, Any],

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 consider typing this (and settings) a little better, e.g. a typed dict or similar, so it is clear what it can contain.

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 9c34aa1: spec is a SandboxSpec TypedDict (image required, every other key optional and defaulting like SandboxConfig), settings is a HostSettings TypedDict, and the REST app and the gRPC facade annotate the dicts they build with them.

self._max_output_bytes = int(settings.get("max_output_bytes", 10 * 1024**2))
self._max_exec_history = int(settings.get("max_exec_history", 256))
self._runtime_factory = runtime_factory
self._runtime: Optional[Any] = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we properly type this with SandboxRuntime?

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 9c34aa1: runtime_factory is Optional[Callable[[], SandboxRuntime]] and _runtime is Optional[SandboxRuntime], imported under TYPE_CHECKING so importing host.py still doesn't pull in the runtime.

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

There are two more nits I pointed out, and one slightly larger issue that opus found which I think is there:

A DELETE during boot can leave an orphaned container. In host.py, boot() runs as an untracked background task.

If terminate() or the TTL fires while boot is in pulling or starting, _shutdown() (L263) sees _instance_id is None and deletes nothing.
It then marks the sandbox terminated and schedules a self-kill for 5s later.
Meanwhile, runtime.create finishes, sets _instance_id, and flips the status back to running (L192–219).
The self-kill ray.kills the actor process, but the runsc sandbox isn't a child that dies with it, so the container is orphaned.

@xyuzh

xyuzh commented Sep 24, 2026

Copy link
Copy Markdown
Member Author

Thanks for the review. The DELETE-during-boot orphan you flagged is fixed in 9c34aa1. _shutdown now marks the host terminating first: a boot still in the pull stops before creating anything, and a boot inside runtime.create is waited for, so its new instance is deleted before the host can exit. The boot also never flips a terminated host back to running. The TTL takes the same path. New tests cover a terminate during start and during pull, a TTL during start, and a boot after terminate; the start-race ones fail on the previous host.py. Both typing nits are in the same commit, and the description lists the rest of this update.

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

"message": (
f"sandbox {self._sandbox_id} is {self._status}, not running"
),
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Exec and file ops race shutdown

Medium Severity

start_exec, write_file, and read_file only reject work when _status is not running, and they never consult _terminating. _shutdown yields on delete before it flips status to terminated, so a concurrent Ray async-actor call can still accept an exec or file transfer on a sandbox that is already being torn down, returning success instead of conflict.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 9c34aa1. Configure here.

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.

Fixed in 6303552: start_exec, write_file, and read_file (and #66359's set_network_access) go through _not_running_error(), which refuses work once _terminating is set, not only when the status isn't running. A test holds terminate() inside the delete and checks each call gets conflict ("terminating") and that no exec reaches the runtime.

# derives a cpu quota from the hosting actor's assigned CPUs
# when no explicit limit is set.
cpu=float(cpu_limit) if cpu_limit is not None else 0.0,
memory=f"{memory_limit_mb}Mi" if memory_limit_mb is not None else 0,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

CPU quota not actually derived

Medium Severity

When cpu_limit is omitted, SandboxHost passes cpu=0.0 into SandboxRuntime.create. That means no cgroup CPU quota. The nearby comment and ResourceSpec claim Ray still derives a quota from the hosting actor's assigned CPUs, but that inference lives only on the upstream Sandbox actor, which this host does not use. Default and request-only-CPU sandboxes therefore run uncapped.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 9c34aa1. Configure here.

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.

Right, that inference lives only in the upstream Sandbox actor. The behavior itself is intended: a request sizes the hosting actor's reservation and only cpu_limit becomes a cgroup cap, the same request/limit split the client SDKs use. So 6303552 corrects the comment and the ResourceSpec docstring rather than the behavior.

if existing is not None:
try:
info = await _describe_or_pending(sandbox_id, existing)
return JSONResponse(status_code=200, content=info)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Idempotent create skips boot

Medium Severity

A client_token retry that finds an existing actor returns 200 from describe and never calls boot(). boot() is the only place the TTL watchdog starts, and it is documented as idempotent specifically so retried creates can safely invoke it. If the original replica died after registering the actor but before boot.remote(), or the actor never scheduled, retries leave the sandbox stuck in pending with no TTL reclaim.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 9c34aa1. Configure here.

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.

Fixed in 6303552: a client_token retry that finds a live actor sends boot() again. It's idempotent, so a first boot call that never reached the actor no longer leaves the sandbox pending without its TTL. A test drops the first boot and checks the retry brings the sandbox to running. The facade's named creates do the same in #65839.

Exposes ray.experimental.sandbox over a versioned REST API (/api/v1)
served by Ray Serve, so sandboxes can be managed from outside the Ray
cluster with nothing but an HTTP client and a bearer token — e.g. as an
Anyscale service, or by agent-evaluation frameworks like Harbor.

Design:
- Each sandbox is a named, detached SandboxHost actor; the actors are
  the registry, so the Serve app is stateless and replicas can scale or
  restart without losing sandboxes.
- Creation and execution are async submit + poll (with optional
  long-poll wait_seconds <= 30s) because image pulls and agent commands
  outlive HTTP requests and load-balancer limits.
- The TTL reclaims both the sandbox and its hosting actor (the core
  runtime's TTL is deliberately disabled here so there is one owner).
- Capabilities, network modes, DNS, shell, and workdir semantics are the
  core SandboxConfig's (ray-project#65570); the API validates network against
  VALID_NETWORK_MODES and defaults capabilities to
  DOCKER_DEFAULT_CAPABILITIES, patching nothing.
- fastapi is only needed by this subpackage (ray[serve]); the base
  sandbox package never imports it.

Testing: 54 unit tests run with no cluster and no runsc (fake runtime +
fake actor resolver + FastAPI TestClient), including an OpenAPI contract
snapshot; a runsc-gated integration test covers the real path. Validated
end to end as a local 'serve run' and as an Anyscale service, driving
real gVisor sandboxes.

Signed-off-by: xyuzh <[email protected]>

@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 6303552. Configure here.

if self._creating:
await self._create_settled.wait()
await self._delete_sandbox_instance()
self._set_status("terminated")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Delete retry kills mid-teardown

High Severity

_shutdown is not exclusive. A second terminate (DELETE retry, a second replica, or DELETE overlapping the TTL) sees _instance_id already cleared and returns at once, so the HTTP layer ray.kills the actor while the first runtime.delete is still running in a worker thread. That is the same hard-kill-during-teardown path the timeout branch exists to avoid, and it can leave the gVisor container behind.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6303552. Configure here.

@pcmoritz
pcmoritz merged commit db0a114 into ray-project:master Sep 24, 2026
6 checks passed
pcmoritz pushed a commit that referenced this pull request Sep 26, 2026
## Why are these changes needed?

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

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

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

Design:

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

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

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

Review fixes from the 2026-09-15 pass:

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

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

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

## Related issue number

Follows #65633 (merged).

## Checks

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

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

## Description

`network="public"` sandboxes currently run with runsc `--network=host`
in the Ray worker's own network namespace: every sandbox on a node
shares one port space, so concurrent workloads that bind a fixed port
collide and can reach each other's listeners. The concrete failure is
terminal-bench's QEMU tasks (`qemu-startup`, `qemu-alpine-ssh`), which
start QEMU with `hostfwd=tcp::2222-:22` and then SSH to `localhost:2222`
from inside the same sandbox. Under co-tenancy the second bind gets
`EADDRINUSE`, and a verifier can connect to a *different* sandbox's
guest.

This PR gives each `public` sandbox a private user+network namespace
pair bridged by pasta (passt) user-mode networking, the rootless-Podman
topology:

- a tiny holder process (`unshare --user --map-root-user --net`) pins
the namespaces for the sandbox's lifetime;
- `pasta` attaches from the pod side (`--netns/--userns
/proc/$PID/ns/*`) and runs in the **foreground** inside the sandbox's
process group, so teardown's `killpg` takes it with the rest of the
tree. `-t/-u/-T/-U none --no-map-gw` make it egress-only: in-sandbox
binds are never republished on the pod, pod-local services are
unreachable from the sandbox loopback, and there is no inbound path;
- `runsc run` executes inside via `nsenter` as mapped root. `--rootless`
is dropped because nesting a second userns breaks the gofer's `/proc`
magic-link derefs; since rootless mode is also what tolerated cgroup
permission failures, the wrapper forces `--ignore-cgroups` for rootless
configs. runsc still gets `--network=host`, but "host" is now private to
the sandbox. Mount and pid namespaces stay shared, so the bundle and
control sockets under `--root` keep working for pod-side
`state`/`exec`/`kill`/`delete`.

### What `public` does and does not isolate

`public` isolates sandboxes from each other and from the node's own
services. It does **not** isolate them from the network the node sits
on: pasta relays every outbound connection through the pod's own sockets
and has no destination filter, so a `public` sandbox can reach other Ray
nodes (including the head node's GCS and dashboard ports), other pods,
and any internal service the node can reach. The docs now say this
explicitly and keep `none` as the recommendation for untrusted code.
Closing that gap needs egress policy outside pasta: a node-level
netfilter rule set (which needs `CAP_NET_ADMIN` in the pod netns), or a
second, intermediate user+network namespace we own and can firewall with
nftables before handing traffic to the pod-side pasta. That is a
follow-up, not part of this PR.

### Why not `pasta [flags] runsc ...`

pasta can spawn a command in namespaces it creates itself, which would
collapse the holder, pidfile, and nsenter into one wrapper. Prototyped
in a privileged container (non-root, pasta from source, `pasta <flags>
--foreground -- runsc ... run ...`): the command runs as uid 0 with a
fixed `0 <uid> 1` map inside new user, net, **pid, mount, ipc, and uts**
namespaces. runsc boots fine, but the pod side loses control of it:
`runsc exec` fails with `waiting on pid 2: sandbox is not running`
because the state file records the inner pid, and `runsc state` silently
reports `running` whenever some unrelated pod process happens to have
that pid. Every control call would have to be wrapped in `nsenter -U -n
-p -m -t <child>` (that does work), and the single-uid map rules out the
multi-uid mapping ray-project#65823 needs. The holder + attach shape keeps pid and
mount namespaces shared for exactly that reason; with pasta in the
foreground it costs one extra `sleep` process.

Requires `pasta` and `nsenter` on nodes for `public` sandboxes. Docs
updated (requirements, mode table with a warning admonition, install
snippets, troubleshooting). Per-exec `user` and `write_file(append=)`
moved to ray-project#65942 per review.

## Related issues

Related to ray-project#65633. Per-exec user support split into ray-project#65942.

## Additional information

Tested with `TEST_SANDBOX=1` in a privileged
`rayproject/ray:nightly-py312` container on arm64 as the non-root `ray`
user, with pasta built from source: two concurrent `public` sandboxes
both bind `0.0.0.0:2222` and each reaches its own listener on
`127.0.0.1:2222`; the worker namespace shows nothing on 2222; no address
names one sandbox from another; egress and generated-resolv.conf DNS
work; `delete_sandbox` and the create-failure path leave no pasta
process behind (the tests diff the set of running pasta pids). The exact
pasta flag list, the `--foreground`/pidfile gate, and the forced
`--ignore-cgroups` are pinned by argv-level unit tests that run without
runsc or pasta.

```
TEST_SANDBOX=1 pytest ray/experimental/sandbox/tests/test_gvisor_backend.py -k "netns or build_run_command or requires_pasta"
10 passed
```

---------

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

## Description

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

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

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

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

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

## Related issues

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

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

## Additional information

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

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

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

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

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

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

## Description

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

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

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

## Related issues

Split from ray-project#65820 per review.

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

## Additional information

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

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

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

## Why are these changes needed?

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

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

## Design

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

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

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

## E2E validation

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

## Update (2026-09-24)

Rebased onto master and addressed the latest review:

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

## Related issue number

Follow-up to ray-project#65570.

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

## Checks

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

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

## Why are these changes needed?

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

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

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

Design:

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

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

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

Review fixes from the 2026-09-15 pass:

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

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

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

## Related issue number

Follows ray-project#65633 (merged).

## Checks

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

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

## Description

`network="public"` sandboxes currently run with runsc `--network=host`
in the Ray worker's own network namespace: every sandbox on a node
shares one port space, so concurrent workloads that bind a fixed port
collide and can reach each other's listeners. The concrete failure is
terminal-bench's QEMU tasks (`qemu-startup`, `qemu-alpine-ssh`), which
start QEMU with `hostfwd=tcp::2222-:22` and then SSH to `localhost:2222`
from inside the same sandbox. Under co-tenancy the second bind gets
`EADDRINUSE`, and a verifier can connect to a *different* sandbox's
guest.

This PR gives each `public` sandbox a private user+network namespace
pair bridged by pasta (passt) user-mode networking, the rootless-Podman
topology:

- a tiny holder process (`unshare --user --map-root-user --net`) pins
the namespaces for the sandbox's lifetime;
- `pasta` attaches from the pod side (`--netns/--userns
/proc/$PID/ns/*`) and runs in the **foreground** inside the sandbox's
process group, so teardown's `killpg` takes it with the rest of the
tree. `-t/-u/-T/-U none --no-map-gw` make it egress-only: in-sandbox
binds are never republished on the pod, pod-local services are
unreachable from the sandbox loopback, and there is no inbound path;
- `runsc run` executes inside via `nsenter` as mapped root. `--rootless`
is dropped because nesting a second userns breaks the gofer's `/proc`
magic-link derefs; since rootless mode is also what tolerated cgroup
permission failures, the wrapper forces `--ignore-cgroups` for rootless
configs. runsc still gets `--network=host`, but "host" is now private to
the sandbox. Mount and pid namespaces stay shared, so the bundle and
control sockets under `--root` keep working for pod-side
`state`/`exec`/`kill`/`delete`.

### What `public` does and does not isolate

`public` isolates sandboxes from each other and from the node's own
services. It does **not** isolate them from the network the node sits
on: pasta relays every outbound connection through the pod's own sockets
and has no destination filter, so a `public` sandbox can reach other Ray
nodes (including the head node's GCS and dashboard ports), other pods,
and any internal service the node can reach. The docs now say this
explicitly and keep `none` as the recommendation for untrusted code.
Closing that gap needs egress policy outside pasta: a node-level
netfilter rule set (which needs `CAP_NET_ADMIN` in the pod netns), or a
second, intermediate user+network namespace we own and can firewall with
nftables before handing traffic to the pod-side pasta. That is a
follow-up, not part of this PR.

### Why not `pasta [flags] runsc ...`

pasta can spawn a command in namespaces it creates itself, which would
collapse the holder, pidfile, and nsenter into one wrapper. Prototyped
in a privileged container (non-root, pasta from source, `pasta <flags>
--foreground -- runsc ... run ...`): the command runs as uid 0 with a
fixed `0 <uid> 1` map inside new user, net, **pid, mount, ipc, and uts**
namespaces. runsc boots fine, but the pod side loses control of it:
`runsc exec` fails with `waiting on pid 2: sandbox is not running`
because the state file records the inner pid, and `runsc state` silently
reports `running` whenever some unrelated pod process happens to have
that pid. Every control call would have to be wrapped in `nsenter -U -n
-p -m -t <child>` (that does work), and the single-uid map rules out the
multi-uid mapping ray-project#65823 needs. The holder + attach shape keeps pid and
mount namespaces shared for exactly that reason; with pasta in the
foreground it costs one extra `sleep` process.

Requires `pasta` and `nsenter` on nodes for `public` sandboxes. Docs
updated (requirements, mode table with a warning admonition, install
snippets, troubleshooting). Per-exec `user` and `write_file(append=)`
moved to ray-project#65942 per review.

## Related issues

Related to ray-project#65633. Per-exec user support split into ray-project#65942.

## Additional information

Tested with `TEST_SANDBOX=1` in a privileged
`rayproject/ray:nightly-py312` container on arm64 as the non-root `ray`
user, with pasta built from source: two concurrent `public` sandboxes
both bind `0.0.0.0:2222` and each reaches its own listener on
`127.0.0.1:2222`; the worker namespace shows nothing on 2222; no address
names one sandbox from another; egress and generated-resolv.conf DNS
work; `delete_sandbox` and the create-failure path leave no pasta
process behind (the tests diff the set of running pasta pids). The exact
pasta flag list, the `--foreground`/pidfile gate, and the forced
`--ignore-cgroups` are pinned by argv-level unit tests that run without
runsc or pasta.

```
TEST_SANDBOX=1 pytest ray/experimental/sandbox/tests/test_gvisor_backend.py -k "netns or build_run_command or requires_pasta"
10 passed
```

---------

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

## Description

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

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

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

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

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

## Related issues

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

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

## Additional information

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

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

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

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

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

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

## Description

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

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

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

## Related issues

Split from ray-project#65820 per review.

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

## Additional information

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

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

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

## Why are these changes needed?

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

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

## Design

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

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

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

## E2E validation

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

## Update (2026-09-24)

Rebased onto master and addressed the latest review:

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

## Related issue number

Follow-up to ray-project#65570.

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

## Checks

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

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

## Why are these changes needed?

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

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

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

Design:

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

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

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

Review fixes from the 2026-09-15 pass:

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

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

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

## Related issue number

Follows ray-project#65633 (merged).

## Checks

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

Signed-off-by: xyuzh <[email protected]>
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 docs An issue or change related to documentation go add ONLY when ready to merge, run all tests sandbox

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants