Repository navigation
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a more efficient 'node' hosting mode for Ray Sandboxes, running a single SandboxNodeHost actor per node to host multiple sandboxes and utilizing placement groups for resource reservation. It also adds a direct TCP communication channel (HostChannel) between API replicas and node hosts to bypass Ray's task dispatch overhead, and enables serving the gRPC facade via Ray Serve. The code review feedback identifies a critical missing import of the copy module in image_manager.py that will cause runtime failures. Additionally, it highlights a high-severity security risk in using pickle for serialization over the network, potential garbage collection issues with untracked asyncio background tasks in SandboxNodeHost, and robustness concerns when serializing raw exceptions over the host channel.
7972225 to
a3c6925
Compare
a3c6925 to
17c0b97
Compare
17c0b97 to
5273e13
Compare
5273e13 to
cdc1f7a
Compare
cdc1f7a to
13ca843
Compare
13ca843 to
6ce8915
Compare
6ce8915 to
6c51ccf
Compare
6c51ccf to
2a42e30
Compare
7b5697a to
28b0376
Compare
28b0376 to
a378e28
Compare
389cab7 to
d38d551
Compare
d38d551 to
698d984
Compare
698d984 to
8d46a2b
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
There are 5 total unresolved issues (including 4 from previous reviews).
Reviewed by Cursor Bugbot for commit 8d46a2b. Configure here.
8d46a2b to
0842eae
Compare
Read the Docs build 4551504 hung in the Sphinx step and was terminated for inactivity; the same commits built on ray-project#66821. This commit changes no files. Signed-off-by: xyuzh <[email protected]>
## Description Lets Ray Serve deploy the Modal-compatible gRPC facade (#65839), so a Serve application, such as an Anyscale service, exposes the facade from configuration alone. The facade itself becomes a standard `grpc` servicer, which both its own server and Serve's gRPC proxy call: - Each RPC is a method named after it that takes the request and the call's context (as `grpc_context`, the name Serve passes it under) and returns or yields its replies. The vendored service stubs are now grpcio's (`*_pb2_grpc.py`, from the same pinned grpcio-tools), so the facade no longer needs grpclib, and `python -m ray.experimental.sandbox.http.grpc_facade` runs a `grpc.aio` server. - `RaySandboxFacade` serves both services over one state. One decorator checks the API token (#66675) before a handler runs and ends a failed call with its status: through `abort()` on `grpc.aio`, and on Serve, whose context has no `abort()`, by setting the status on the context and raising. - `grpc_facade.add_servicers_to_server`, for `grpc_options.grpc_servicer_functions`, registers the client SDK's two services under their wire names. - `grpc_app.build_app` builds a one-replica deployment of the facade's servicer. `build_app` refuses to build without `RAY_SANDBOX_API_TOKEN`, and the replica refuses to start without the token in its own environment, which can lack what `build_app` saw (as with `serve run` outside the cluster). Serve's proxies listen on every node's address, which sandboxes with network access can reach. - Without a configured `advertise_url`, the facade gives each client `https://` plus the host it dialed (`x-modal-host`) as its command-router URL, which suits a TLS endpoint in front of the proxy. - Docs: a "Serve the facade with Ray Serve" section in `doc/source/core/sandboxes.md`, with the Anyscale service config, and two notes about clients: - Client SDK 1.6+ needs `MODAL_SANDBOX_V2=0`, because 1.6 made a newer sandbox API its default and the facade doesn't serve it. The client SDK tests set it too. - The TLS endpoint in front of the facade must accept HTTP/2 without ALPN, because the SDK's command-router connection offers none. Envoy does; ingress-nginx doesn't. So on Anyscale, the service belongs on a Kubernetes cloud that routes services through an Envoy Gateway. ## Related issues Related to #65839 (the facade) and #66675 (its API token). #66821, stacked on this one, makes the facade fast under bursts of sandboxes. ## Additional information - Not a duplicate: no open PR serves the facade through Ray Serve. I searched open PRs for `grpc_app`, "sandbox facade Serve" and "sandbox gRPC facade". - Tests: - `pytest python/ray/experimental/sandbox/http/tests` on macOS with the Ray 2.58.0 wheel (with Serve and the Modal SDK 1.6.1 installed) and this branch's `ray.experimental.sandbox`: 157 passed, 2 skipped (the two `TEST_SANDBOX=1` integration tests). This includes the unmodified SDK against both the facade's `grpc.aio` server and a local Ray Serve gRPC proxy: sandbox create, exec, a multi-message file-write stream, and a rejected token. - With CI's pins (grpcio 1.75.0, protobuf 5.27.5) and without grpclib, Serve or modal installed: `test_grpc_facade.py`, `test_grpc_app.py` and `test_modal_client.py` gave 70 passed, 9 skipped (the Serve and SDK end-to-end tests). The facade's wire tests no longer need grpclib, so CI now runs them instead of skipping them. - `pre-commit run --files <changed files>` with pre-commit 3.5.0 (every hook that applies, including both ruff hooks, pydoclint and black) and the API parameter coverage check (`ci/ray_ci/doc/cmd_check_api_param_coverage.py --base-ref origin/master --blocking`) pass. - End to end with the stock Modal SDK (1.6.1, no patch), before the facade became a `grpc` servicer (the first revision served it through an adapter in `grpc_app`): this app ran as an Anyscale staging service on a Kubernetes cloud whose edge is Envoy Gateway. - The SDK created sandboxes, ran commands in them (exit code, stdout, stderr, line streaming, secrets, workdir), wrote and read files, reattached, and terminated them. - Uploads and downloads of up to 64 MiB passed, and so did reading a command's output before `wait()` while it stayed silent for 720 s. - A command-router call over TLS without ALPN reached the facade, and calls without the token got UNAUTHENTICATED. - Behind ingress-nginx, the same SDK creates sandboxes, but its command-router calls fail, as the docs now say. - The burst benchmarks in #66821 also ran this app as an Anyscale service, on a 16-node EKS staging cluster behind ingress-nginx, with a one-line ALPN fix applied to the client SDK. - AI assistance (Claude Code) was used to prepare this change. --------- Signed-off-by: xyuzh <[email protected]>
A burst of sandboxes through the facade was bound by one Ray worker process
per sandbox, by the facade's in-memory exec state, and by Ray's per-task
dispatch into a busy actor. This adds opt-in hosting for bursts and speeds
up the gVisor backend's hot paths:
- runsc: a create waits on `runsc run --pid-file` (a stat every 10 ms)
and asks `runsc state` only once the file exists, instead of a
`runsc state` process every 0.1 s; GOMAXPROCS=2 for CLI calls, as
gVisor's containerd shim sets; `runsc spec` cached per binary; the image
cache scans for eviction only on a miss and takes a shared lock on a hit.
- SandboxRuntime(warm_pool=[...]): sandboxes kept booted per profile (the
create() arguments of one boot configuration plus a size); a create that
matches takes one at once and its env applies to every command;
wait_for_warm_pool() and close().
- host_mode="node": one SandboxNodeHost actor per node hosts that node's
SandboxHost objects, so a create starts no worker process. Sandbox ids
name their node, so any replica finds a sandbox without a registry, and
a call follows a host that restarted. A sandbox its node's host doesn't
have answers NOT_FOUND, as a sandbox actor that no longer exists does.
- reservation_slab_cpus: sandboxes that request only CPUs share placement
groups ("slabs") that a host grows, bounded by its node's free CPU, and
releases when idle. Slabs are not detached, so Ray removes them with
their host.
- warm_pool: hosts keep pre-booted sandboxes per profile, optionally with
their CPUs reserved; a matching facade create adopts one, and its env
goes on every exec. Refills boot one at a time while the host's
sandboxes are busy running commands, and a pool whose boot failed boots
no replacements for 30 s.
- The facade keeps no state: execs live on the sandbox's host, keyed by the
client's exec id (the router protos now carry task_id), so the Serve app
runs any number of replicas (num_replicas).
- host_channel: replicas call node hosts over one TCP connection each,
served on the host's event loop and authenticated by a token from a Ray
call, and fall back to Ray actor calls.
- network="public" sandboxes get a gofer network namespace of their own
(--gofer-network-namespace=new), so they work on nodes that ran
network="none" ones first, and their start waits for the namespace
holder and slirp4netns in 10 ms steps (were 0.1 s).
- test_netns_egress_and_dns accepts any HTTP status from example.com: its
CDN answered CI's busybox wget with 403, though DNS and egress worked.
On 16 x 30-CPU nodes behind an Anyscale service, 1,900 sandboxes go from
create to their first exec in about 1.0 s at t99 with warm pools, and
1,900 sandboxes run about 10,000 execs/s. On one 14-CPU node,
SandboxRuntime creates in the shape of the burst gist boot faster than on
Ray 2.58 in every configuration measured (48 at once: 104/s vs 93/s; 96 at
once: 94/s vs 61-72/s), and take 1,400-2,400/s from a warm pool.
Signed-off-by: xyuzh <[email protected]>
0842eae to
9726668
Compare
|
Closing this in favor of smaller PRs, one optimization each, each measured on its own against master:
Node hosts, shared placement groups, node-host warm pools and the direct host channel follow as stacked PRs after #67078 merges. |
…output leniently (#66986) ## Description On timeout, `exec_command` killed only the `runsc exec` client, then waited without a timeout for the output pipes, which the command kept open in the sandbox: `exec("sleep 30; echo done", timeout=1)` returned after 30 s. Separately, one byte of output that isn't UTF-8 failed the whole exec (`'utf-8' codec can't decode byte 0xff`), losing the exit code and output. This PR changes `backend/gvisor.py`: - On timeout, `_kill_exec` lists the sandbox's processes with `runsc trace procfs` and kills by PID everything in the command's session plus its descendants (the command's PID comes from `runsc exec -internal-pid-file`). It lists before killing anything, so a `setsid` child is still found through its parent, and lists again until nothing is left, at most 5 times, because a process can fork between a listing and its kill. - Output is read as bytes and decoded with U+FFFD for invalid UTF-8. Why sessions: `runsc exec` makes the command a session leader, and its processes stay in the session unless they call `setsid()`, even after their parent exits or they change process group (GNU `timeout` does). Only `runsc trace procfs` reports sessions; the PGID column of `runsc ps` and `runsc kill --pgid` are new (April 2026) and cover one group. Behavior changes: - A timed-out exec returns at its timeout and leaves nothing running, except a daemon that called `setsid` and whose parent exited. The docs say so next to the exec example. - Line endings come back as printed. `text=True` used to turn `\r` and `\r\n` into `\n`. ## Related issues None filed. Found running SkyRL's Harbor environment on Ray Sandbox (skyrl-project/SkyRL#2467), where a stuck command held its trial for the agent's full 5,400 s timeout. ## Additional information - Not a duplicate: open PRs that touch the gVisor backend (#66932, #67022, #66821, #66471, #66470, #65898) don't change exec timeouts or output decoding. #66932 wraps `runsc exec` in its cgroup launcher, so whichever lands second needs a small merge in `exec_command`. - Tests: a parser unit test and five gVisor tests. The plain timeout and UTF-8 tests fail on master; the background-job and fork-loop tests fail on this PR's first commit (d4fafd8), and the `setsid`-child test fails if the command is killed before the listing. - Tested on a CoreWeave pod (runsc release-20261012.0), rebased on master afd4ccf: `TEST_SANDBOX=1 pytest tests/test_gvisor_backend.py tests/test_image_manager.py tests/test_image_utils.py tests/test_sandbox_config.py tests/test_sandbox_runtime.py -k "not netns"`: 117 passed, 1 skipped (`test_create_sandbox_helper` ran on its own and passed); `-k netns`: 13 passed. pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]>
## Description Lets Ray Serve deploy the Modal-compatible gRPC facade (ray-project#65839), so a Serve application, such as an Anyscale service, exposes the facade from configuration alone. The facade itself becomes a standard `grpc` servicer, which both its own server and Serve's gRPC proxy call: - Each RPC is a method named after it that takes the request and the call's context (as `grpc_context`, the name Serve passes it under) and returns or yields its replies. The vendored service stubs are now grpcio's (`*_pb2_grpc.py`, from the same pinned grpcio-tools), so the facade no longer needs grpclib, and `python -m ray.experimental.sandbox.http.grpc_facade` runs a `grpc.aio` server. - `RaySandboxFacade` serves both services over one state. One decorator checks the API token (ray-project#66675) before a handler runs and ends a failed call with its status: through `abort()` on `grpc.aio`, and on Serve, whose context has no `abort()`, by setting the status on the context and raising. - `grpc_facade.add_servicers_to_server`, for `grpc_options.grpc_servicer_functions`, registers the client SDK's two services under their wire names. - `grpc_app.build_app` builds a one-replica deployment of the facade's servicer. `build_app` refuses to build without `RAY_SANDBOX_API_TOKEN`, and the replica refuses to start without the token in its own environment, which can lack what `build_app` saw (as with `serve run` outside the cluster). Serve's proxies listen on every node's address, which sandboxes with network access can reach. - Without a configured `advertise_url`, the facade gives each client `https://` plus the host it dialed (`x-modal-host`) as its command-router URL, which suits a TLS endpoint in front of the proxy. - Docs: a "Serve the facade with Ray Serve" section in `doc/source/core/sandboxes.md`, with the Anyscale service config, and two notes about clients: - Client SDK 1.6+ needs `MODAL_SANDBOX_V2=0`, because 1.6 made a newer sandbox API its default and the facade doesn't serve it. The client SDK tests set it too. - The TLS endpoint in front of the facade must accept HTTP/2 without ALPN, because the SDK's command-router connection offers none. Envoy does; ingress-nginx doesn't. So on Anyscale, the service belongs on a Kubernetes cloud that routes services through an Envoy Gateway. ## Related issues Related to ray-project#65839 (the facade) and ray-project#66675 (its API token). ray-project#66821, stacked on this one, makes the facade fast under bursts of sandboxes. ## Additional information - Not a duplicate: no open PR serves the facade through Ray Serve. I searched open PRs for `grpc_app`, "sandbox facade Serve" and "sandbox gRPC facade". - Tests: - `pytest python/ray/experimental/sandbox/http/tests` on macOS with the Ray 2.58.0 wheel (with Serve and the Modal SDK 1.6.1 installed) and this branch's `ray.experimental.sandbox`: 157 passed, 2 skipped (the two `TEST_SANDBOX=1` integration tests). This includes the unmodified SDK against both the facade's `grpc.aio` server and a local Ray Serve gRPC proxy: sandbox create, exec, a multi-message file-write stream, and a rejected token. - With CI's pins (grpcio 1.75.0, protobuf 5.27.5) and without grpclib, Serve or modal installed: `test_grpc_facade.py`, `test_grpc_app.py` and `test_modal_client.py` gave 70 passed, 9 skipped (the Serve and SDK end-to-end tests). The facade's wire tests no longer need grpclib, so CI now runs them instead of skipping them. - `pre-commit run --files <changed files>` with pre-commit 3.5.0 (every hook that applies, including both ruff hooks, pydoclint and black) and the API parameter coverage check (`ci/ray_ci/doc/cmd_check_api_param_coverage.py --base-ref origin/master --blocking`) pass. - End to end with the stock Modal SDK (1.6.1, no patch), before the facade became a `grpc` servicer (the first revision served it through an adapter in `grpc_app`): this app ran as an Anyscale staging service on a Kubernetes cloud whose edge is Envoy Gateway. - The SDK created sandboxes, ran commands in them (exit code, stdout, stderr, line streaming, secrets, workdir), wrote and read files, reattached, and terminated them. - Uploads and downloads of up to 64 MiB passed, and so did reading a command's output before `wait()` while it stayed silent for 720 s. - A command-router call over TLS without ALPN reached the facade, and calls without the token got UNAUTHENTICATED. - Behind ingress-nginx, the same SDK creates sandboxes, but its command-router calls fail, as the docs now say. - The burst benchmarks in ray-project#66821 also ran this app as an Anyscale service, on a 16-node EKS staging cluster behind ingress-nginx, with a one-line ALPN fix applied to the client SDK. - AI assistance (Claude Code) was used to prepare this change. --------- Signed-off-by: xyuzh <[email protected]>
…7078) ## Description The gRPC facade keeps every exec (a command, or an emulated file read or write) in an in-memory table, so its Serve application runs exactly one replica, and every exec-plane call goes through that replica's event loop: 1,328 execs/s for 200 sandboxes in the run below. This PR moves exec state to each sandbox's `SandboxHost`, so any replica can serve any call and the application accepts `num_replicas`. Read `host.py` first: - Execs are keyed by the client's exec id, so a retried start (the SDK retries UNAVAILABLE) joins the first one from any replica, and a command never runs twice. - File reads and writes are host jobs: `fs_read` keeps the content, and `stdin_write` buffers a write's stdin on the host (capped by `max_file_bytes`) until EOF. A repeated last chunk isn't appended twice. - In `grpc_facade.py`, router calls find the sandbox by the request's `task_id`, which the SDK always sends (the vendored proto now declares it), and try the resolver's handle cache before a worker thread. A finished exec now stays readable while its sandbox's exec history keeps it (`max_exec_history`, 256 by default) instead of for the facade's 120 s. Measured on 2026-10-14 against base 00a3adb: unmodified Modal SDK 1.6.1 clients against `grpc_app:build_app` on Serve, four 30-CPU sandbox workers on a CoreWeave cluster, real gVisor sandboxes. Medians of 3-6 runs; no sandbox failed. | | creates (N=400), ready/s at t99 | execs/s, 200 sandboxes x 30 | | --- | --- | --- | | master (1 replica) | 102 | 1,328 | | This PR, 1 replica | 111 | 1,557 | | This PR, 4 replicas | 111 | 2,756 | Creates don't change: they're bound by starting a Ray worker per sandbox. ## Related issues Split out of #66821. Node hosts, shared placement groups (slabs), node-host warm pools and a direct host channel (B2-B5 of the split) follow as separate PRs stacked on this one. ## Additional information - Not a duplicate: no open PR other than #66821 changes the facade's exec state or replica count (I searched for "sandbox facade replicas" and "sandbox exec state"). - Tests: `test_any_replica_serves_any_exec_call` runs two facades on one sandbox: a start retried on the other one runs once, and stdin, stdout and wait work across them. It fails on master, where the retry runs the command again. Six host tests cover exec keys, stdin chunks and caps, failing file jobs and terminate. - Tested rebased on master a82c56e (before #66932 merged; macOS unit tests and CI cover the rebase onto it). On macOS with the Ray 2.58.0 wheel, `ray[serve]` and Modal SDK 1.5.5: `pytest python/ray/experimental/sandbox/http/tests` 182 passed (master: 176), plus `test_full_sandbox_lifecycle`, which needs gVisor. In a privileged CoreWeave pod with real gVisor (runsc release-20261012.0, `TEST_SANDBOX=1`): the HTTP tests 173 passed, 10 skipped (master: 167 passed, 10 skipped; the skips need modal). pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]>
…output leniently (ray-project#66986) ## Description On timeout, `exec_command` killed only the `runsc exec` client, then waited without a timeout for the output pipes, which the command kept open in the sandbox: `exec("sleep 30; echo done", timeout=1)` returned after 30 s. Separately, one byte of output that isn't UTF-8 failed the whole exec (`'utf-8' codec can't decode byte 0xff`), losing the exit code and output. This PR changes `backend/gvisor.py`: - On timeout, `_kill_exec` lists the sandbox's processes with `runsc trace procfs` and kills by PID everything in the command's session plus its descendants (the command's PID comes from `runsc exec -internal-pid-file`). It lists before killing anything, so a `setsid` child is still found through its parent, and lists again until nothing is left, at most 5 times, because a process can fork between a listing and its kill. - Output is read as bytes and decoded with U+FFFD for invalid UTF-8. Why sessions: `runsc exec` makes the command a session leader, and its processes stay in the session unless they call `setsid()`, even after their parent exits or they change process group (GNU `timeout` does). Only `runsc trace procfs` reports sessions; the PGID column of `runsc ps` and `runsc kill --pgid` are new (April 2026) and cover one group. Behavior changes: - A timed-out exec returns at its timeout and leaves nothing running, except a daemon that called `setsid` and whose parent exited. The docs say so next to the exec example. - Line endings come back as printed. `text=True` used to turn `\r` and `\r\n` into `\n`. ## Related issues None filed. Found running SkyRL's Harbor environment on Ray Sandbox (skyrl-project/SkyRL#2467), where a stuck command held its trial for the agent's full 5,400 s timeout. ## Additional information - Not a duplicate: open PRs that touch the gVisor backend (ray-project#66932, ray-project#67022, ray-project#66821, ray-project#66471, ray-project#66470, ray-project#65898) don't change exec timeouts or output decoding. ray-project#66932 wraps `runsc exec` in its cgroup launcher, so whichever lands second needs a small merge in `exec_command`. - Tests: a parser unit test and five gVisor tests. The plain timeout and UTF-8 tests fail on master; the background-job and fork-loop tests fail on this PR's first commit (d4fafd8), and the `setsid`-child test fails if the command is killed before the listing. - Tested on a CoreWeave pod (runsc release-20261012.0), rebased on master afd4ccf: `TEST_SANDBOX=1 pytest tests/test_gvisor_backend.py tests/test_image_manager.py tests/test_image_utils.py tests/test_sandbox_config.py tests/test_sandbox_runtime.py -k "not netns"`: 117 passed, 1 skipped (`test_create_sandbox_helper` ran on its own and passed); `-k netns`: 13 passed. pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
…y-project#67078) ## Description The gRPC facade keeps every exec (a command, or an emulated file read or write) in an in-memory table, so its Serve application runs exactly one replica, and every exec-plane call goes through that replica's event loop: 1,328 execs/s for 200 sandboxes in the run below. This PR moves exec state to each sandbox's `SandboxHost`, so any replica can serve any call and the application accepts `num_replicas`. Read `host.py` first: - Execs are keyed by the client's exec id, so a retried start (the SDK retries UNAVAILABLE) joins the first one from any replica, and a command never runs twice. - File reads and writes are host jobs: `fs_read` keeps the content, and `stdin_write` buffers a write's stdin on the host (capped by `max_file_bytes`) until EOF. A repeated last chunk isn't appended twice. - In `grpc_facade.py`, router calls find the sandbox by the request's `task_id`, which the SDK always sends (the vendored proto now declares it), and try the resolver's handle cache before a worker thread. A finished exec now stays readable while its sandbox's exec history keeps it (`max_exec_history`, 256 by default) instead of for the facade's 120 s. Measured on 2026-10-14 against base 00a3adb: unmodified Modal SDK 1.6.1 clients against `grpc_app:build_app` on Serve, four 30-CPU sandbox workers on a CoreWeave cluster, real gVisor sandboxes. Medians of 3-6 runs; no sandbox failed. | | creates (N=400), ready/s at t99 | execs/s, 200 sandboxes x 30 | | --- | --- | --- | | master (1 replica) | 102 | 1,328 | | This PR, 1 replica | 111 | 1,557 | | This PR, 4 replicas | 111 | 2,756 | Creates don't change: they're bound by starting a Ray worker per sandbox. ## Related issues Split out of ray-project#66821. Node hosts, shared placement groups (slabs), node-host warm pools and a direct host channel (B2-B5 of the split) follow as separate PRs stacked on this one. ## Additional information - Not a duplicate: no open PR other than ray-project#66821 changes the facade's exec state or replica count (I searched for "sandbox facade replicas" and "sandbox exec state"). - Tests: `test_any_replica_serves_any_exec_call` runs two facades on one sandbox: a start retried on the other one runs once, and stdin, stdout and wait work across them. It fails on master, where the retry runs the command again. Six host tests cover exec keys, stdin chunks and caps, failing file jobs and terminate. - Tested rebased on master a82c56e (before ray-project#66932 merged; macOS unit tests and CI cover the rebase onto it). On macOS with the Ray 2.58.0 wheel, `ray[serve]` and Modal SDK 1.5.5: `pytest python/ray/experimental/sandbox/http/tests` 182 passed (master: 176), plus `test_full_sandbox_lifecycle`, which needs gVisor. In a privileged CoreWeave pod with real gVisor (runsc release-20261012.0, `TEST_SANDBOX=1`): the HTTP tests 173 passed, 10 skipped (master: 167 passed, 10 skipped; the skips need modal). pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
## Description A gVisor sandbox create polls `runsc state` every 0.1 s until the container runs. Each poll is a Go process, so a create returns up to 0.1 s after its 30-40 ms boot, and a burst of creates spends CPU on polling. `network="public"` sandboxes also wait in 0.1 s steps for the namespace holder and slirp4netns. This PR changes the waits in `backend/gvisor.py`: - `runsc run --pid-file <bundle>/sandbox.pid` writes the file once the container exists. The start loop stats it every 10 ms and calls `runsc state` only after that, every 50 ms. - The public wrapper checks for the holder and slirp4netns every 10 ms instead of 0.1 s, still for up to 10 s. Measured on 2026-10-14 against base 00a3adb, on a CoreWeave node pinned to 16 cores, creating `python:3.12-slim` sandboxes from a cached image; medians of 5 alternating runs per side. Every create succeeded, and CPU per create fell by up to 29%. | | master | this PR | | --- | --- | --- | | One create, `network="none"` (p50) | 114 ms | 41 ms | | One create, `network="host"` (p50) | 115 ms | 31 ms | | One create, `network="public"` (p50) | 324 ms | 71 ms | | 96 creates at once, `none` | 98/s | 116/s | | 96 creates at once, `public` | 48/s | 70/s | ## Related issues Split out of #66821. ## Additional information - Not a duplicate: no open PR changes how a create waits (I searched for "runsc state", "pid-file" and "sandbox boot"). #66471's restore path has its own copy of the 0.1 s loop. #67075 edits the same `runsc state` call; whichever lands second needs a one-line merge. - Tests: `test_restore_in_place_waits_for_a_new_pid_file` checks that a restore in place doesn't start from the stopped launch's pid file, and #67688's `test_backend_applies_oom_priority_to_start_exec_and_file_io` now writes the pid file its fake launch stands in for. The run-command tests now expect `--pid-file` and fail on master; every test that boots a sandbox goes through the new wait. `test_create_times_out_when_runsc_state_hangs` checks that a `runsc state` call that never returns can't hold a create past its deadline. - Tested at a04985a (master a83e55e merged in), in a privileged container (aarch64, runsc release-20261026.0, erofs-utils 1.9.4): `TEST_SANDBOX=1 pytest tests/test_{gvisor_backend,checkpoint_restore,image_manager,image_utils,sandbox_runtime,overlayfs,sandbox_config,cgroup,resource_limits}.py`: 474 passed, 25 skipped, and the same two GPU tests fail as on master (473 passed), since that container's Ray predates `get_cdi_kind`. As on master that hour, `test_netns_owner_interrupt_leaves_its_sandbox_running` failed because example.com answered the sandbox's `wget` with 403. pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Co-authored-by: Philipp Moritz <[email protected]>
## Description Every runsc CLI call the gVisor backend makes (`run`, `state`, `exec`, `kill`, `delete`, `spec`) is a Go process, and Go sizes its runtime to every CPU it can see. On a 64-core node without a CPU limit, 64 concurrent `runsc exec` calls cost 0.023 CPU-s each. gVisor's containerd shim runs runsc with `GOMAXPROCS=2` for this reason. This PR runs those calls with `GOMAXPROCS=2` too (`runsc_env()` in `backend/gvisor.py`), unless the worker's environment sets it. runsc doesn't pass the variable on to the sandbox or the gofer, so `nproc` in a sandbox still reports every CPU. Measured on 2026-10-14 against base 00a3adb, on a 64-core CoreWeave node: 64 sandboxes each ran 20 `true` execs back to back, all at once; medians of 5 alternating runs per side. | CPUs runsc sees | master | this PR | | --- | --- | --- | | 64 (no CPU limit) | 1,855 execs/s, 0.0226 CPU-s each | 2,436 execs/s, 0.0129 CPU-s each | | 16 (`taskset`) | 907 execs/s, 0.0162 CPU-s each | 990 execs/s, 0.0146 CPU-s each | In pods with CPU limits, Go already sizes itself to the limit and the gain is small: 2-4% more execs and creates through the gRPC facade on four 30-CPU pods, with `GOMAXPROCS=2` set in the Ray workers' environment (runsc inherits it). ## Related issues Split out of #66821. ## Additional information - Not a duplicate: no open PR sets `GOMAXPROCS` for runsc (I searched for "sandbox GOMAXPROCS" and "runsc spec"). #66932 and #67022 add runsc calls, which should pass `env=runsc_env()` if this lands first. #67074 and #67076 edit the same `runsc state` and `runsc spec` calls; one-line merges. - Tests: `test_runsc_env_caps_gomaxprocs_unless_set` checks the default and an override; `test_runsc_run_starts_with_gomaxprocs` boots a sandbox and reads its `runsc run`'s environment. Both fail on master. `test_gpu_checks_run_runsc_with_runsc_env` covers the two GPU checks' runsc calls that came in with #65898. - Tested at 3cfe602, with master 6c61f9a (which has #67074) merged in, in a privileged container (aarch64, runsc release-20261026.0, erofs-utils 1.9.4): `TEST_SANDBOX=1 pytest tests/test_{gvisor_backend,checkpoint_restore,image_manager,image_utils,sandbox_runtime,overlayfs,sandbox_config,cgroup,resource_limits}.py`: 480 passed, 25 skipped, and the same two GPU tests fail as on master (473 passed), since that container's Ray predates `get_cdi_kind`. pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Co-authored-by: Philipp Moritz <[email protected]>

Description
Bursts of sandboxes through the gRPC facade were bound by one Ray worker process per sandbox, by the facade's in-memory exec state, and by Ray's per-task dispatch into a busy actor. Callers of
SandboxRuntimeitself, such as the burst gist's actors, waited on arunsc stateprocess every 0.1 s for each boot. Master at this PR's base was 20-30% slower than Ray 2.58 on that path. This PR adds opt-in hosting for bursts (all off by default), adds warm pools toSandboxRuntime, and speeds up the gVisor backend's hot paths. On 16 x86 nodes,SandboxRuntimecreates now beat 2.58 by about 15-20%, and a warm pool serves about 20,000/s (see Results):runsc run --pid-file(astatevery 10 ms) and runsrunsc stateonly once the file exists. Before, arunsc stateprocess ran every 0.1 s, so each create waited up to 0.1 s past its boot, and the polling cost CPU that a burst of boots needs. Also:GOMAXPROCS=2for CLI calls, as gVisor's containerd shim sets;runsc speccached per binary; the image cache scans for eviction only on a miss and takes a shared lock on a hit.SandboxRuntime(warm_pool=[...]): for actors that useSandboxRuntimedirectly. Each profile is thecreate()arguments of one boot configuration plus asize, and the runtime keeps that many sandboxes booted per profile. A matching create takes one at once, itsenvapplies to every command, and its TTL starts at the create.wait_for_warm_pool()andclose()are new too. Profiles can come from the worker's own configuration, so each cluster can be seeded with its own.host_mode="node": oneSandboxNodeHostactor per node hosts that node'sSandboxHostobjects, so a create starts no worker process. Sandbox ids name their node, so any replica finds a sandbox without a registry, and a call follows a host that restarted. A sandbox its node's host doesn't have answers NOT_FOUND, as a sandbox actor that no longer exists does. Hosts are detached, so their sandboxes outlive a redeploy, and each new deployment's settings apply to them on first use.reservation_slab_cpus: sandboxes that request only CPUs share placement groups ("slabs") that a host grows, bounded by its node's free CPU, and releases when idle. Slabs aren't detached, so Ray removes them with their host however it exits, including with its node.warm_pool: hosts keep pre-booted sandboxes per profile, optionally with their CPUs reserved in slabs; a matching facade create adopts one, and its env goes on every exec. Refills boot one at a time while the host's sandboxes are busy running commands, and a pool whose boot failed boots no replacements for 30 s.task_id), so the Serve app runs any number of replicas (num_replicas).host_channel: replicas call node hosts over one TCP connection each, served on the host's event loop, and fall back to Ray actor calls. A connection must first send a token that callers get through a Ray call, compared before anything else is read, and calls and replies are msgpack, never pickle. Under load, Ray's per-task dispatch queued calls to a busy asyncio actor for ~100 ms, even from an idle caller, while the host's event loop stayed responsive.network="public"sandboxes get a gofer network namespace of their own (--gofer-network-namespace=new), so they work on nodes that rannetwork="none"ones first. Their start also waits for the namespace holder and slirp4netns in 10 ms steps instead of 0.1 s.test_netns_egress_and_dnsaccepts any HTTP status from example.com, since any answer shows DNS and egress work: its CDN answered CI's busyboxwgetwith 403 (microcheck build 55854).doc/source/core/sandboxes.md, which notes that these settings apply to the gRPC facade only (the REST API keeps one actor per sandbox); the facade's state and replica notes are updated.Results
Setup: an Anyscale service on staging EKS, head 30 CPUs, 16 x 30-CPU sandbox nodes and 2 client nodes; the Modal SDK 1.6.1, with the one-line ALPN fix that this cluster's ingress-nginx endpoint needs (see #66820's docs), creates 1,900 sandboxes at 0.25 CPU (
python:3.12-slim,network="none") and runsexec("true")in each. "Ready" is the first exec done; rates are at t99 (0.99 N / t99).xychart-beta title "Sandboxes ready per second at t99: 1900 sandboxes on 16 nodes" x-axis ["Python API (reference)", "Node hosts", "Slabs", "Warm pools", "Host channel", "Throttled refills"] y-axis "ready per s" 0 --> 2162 bar [226, 487, 815, 1690, 1840, 1880]xychart-beta title "Exec throughput: 1900 sandboxes running execs back to back" x-axis ["Before host channel", "Host channel", "Throttled refills"] y-axis "execs per s" 0 --> 11500 bar [4678, 7999, 10000]xychart-beta title "Sandboxes ready per second: 400 sandboxes on 4 nodes" x-axis ["Baseline", "runsc", "Node hosts", "Long poll", "HAProxy ingress", "Stateless x8"] y-axis "ready per s" 0 --> 454 bar [55, 57, 91, 93, 157, 395]ray.experimental.sandbox.create+exec.remote, one actor per sandbox) reaches 226/s, andSandboxRuntimein pre-started actors 720/s.RAY_SERVE_ENABLE_HA_PROXY=1), not code in this PR.SandboxRuntimedirectly (the burst gist's path)These numbers come from one 14-CPU node: a local privileged container, aarch64, runsc release-20261005.0, cgroups ignored. Each run creates sandboxes concurrently with the burst gist's arguments:
python:3.12-slim,cpu=0.25,workdir="/workspace",readonly=True. Each cell is the median of 9 runs, and every create succeeded.network="none", 48 at oncenetwork="host", 48 at oncenetwork="public", 24 at onceAt scale on x86, in the customer's "one actor per worker" shape: 16 sandbox nodes with 30 CPUs each, one actor per node, all bursting at once, gist-shaped creates, Anyscale staging cluster. 94 per node is the customer's 125 per 40 CPUs, scaled to 30 CPUs. Rates are the steady runs (the 2nd and 3rd of 3); every create succeeded.
nonenonehostpublicnone21,000-21,800/s,host18,300-18,500/s,public44,600-47,700/s; p50 4-7 mspublicmode was host networking. Here eachpublicsandbox gets a private network namespace at the same speed.Measured and not kept: changing the replica count (8, 12, 16) or Serve's throughput settings; two node hosts per node (worse tails); running
runsc execfrom the host's event loop (fork_execandos.posix_spawnhold the GIL, and uvloop's subprocess spawn forks, taking 13.6 ms in a node-host-sized process).Removed in review, as possible follow-ups: boot readiness from runsc's state file, which replaced one
runsc stateprocess per 0.1 s poll while a sandbox boots; several node hosts per node (node_host_shards, off by default); and the task id handed out while gVisor is still starting, withSandboxGetTaskIdlong-polling for it and the host holding early execs until boot finished (the "Long poll" step above). At 1,900 sandboxes the early task id gave no latency gain, because the client's RPC chain after create dominates. The runs above had the state-file readiness and the early task id in place.Remaining limits: cold creates are bound by gVisor boot CPU (~44 boots/s per 30-CPU node). Behind this cluster's Anyscale endpoint (ingress-nginx on EKS), every sandbox's command-router TLS connection costs ~135 ms under a burst (about 1 in 1,000 takes ~5 s), and about one response in 100-200k is lost there, so the client retries after 60 s. Neither happens with clients connected to HAProxy directly. These runs predate the Envoy Gateway endpoint that #66820 now documents, where the stock SDK works without the fix; the burst numbers weren't re-measured there. They also predate #66820's latest revision, in which Serve calls the facade's servicer directly instead of through an adapter in
grpc_app; this PR's burst code is the same, rebased onto it.Related issues
Builds on #66820, now merged into master. Related to #65839. Found along the way: #66815 (Ray Serve can split a replica's port with another process), fixed in #66816.
Additional information
test_netns_egress_and_dnseither; I searched for the test name and for "sandbox example.com".68174559b27after [core][sandbox] Serve the gRPC facade with Ray Serve #66820 merged. Only the burst-performance commit remains, andgit range-diffconfirms its patch is unchanged. Fresh validation on macOS with the Ray 2.58.0 wheel and this worktree's sandbox sources:pytest python/ray/experimental/sandbox/http/tests -q --disable-warnings --maxfail=1gave 191 passed, 2 skipped;pytest --noconftest python/ray/experimental/sandbox/tests/test_sandbox_runtime.py python/ray/experimental/sandbox/tests/test_sandbox_config.py -q --disable-warnings --maxfail=1gave 17 passed.--noconftestruns these fake-runtime/config tests without the Linux-only sandbox fixture. Applicable pre-commit hooks and the blocking API parameter coverage check againstorigin/masteralso pass.pytest python/ray/experimental/sandbox/http/testson macOS with the Ray 2.58.0 wheel (with Serve and the Modal SDK 1.6.1 installed) and this branch'sray.experimental.sandbox: 191 passed, 2 skipped. New tests:test_host_channel.py,test_node_host.py, and additions totest_grpc_facade.py,test_grpc_app.pyandtest_sandbox_host.py. With CI's pins (grpcio 1.75.0, protobuf 5.27.5, jinja2 3.1.6) and without grpclib or modal: 182 passed, 11 skipped.SandboxNodeHostactor (fake runtime) served create, describe, exec, a file write with a repeated chunk, and terminate over the host channel with the Ray path disabled. Killing the host then removed its slab placement group.TEST_SANDBOX=1, in a privilegedrayproject/ray:nightly-py312container (aarch64, runsc release-20261005.0, erofs-utils 1.9.4, slirp4netns 1.3.5):test_image_manager.py,test_gvisor_backend.py,test_sandbox_runtime.py,test_sandbox.py,test_sandbox_config.pyandtest_image_utils.pygave 111 passed, 1 skipped, including a real warm-pool test and thepublicnetwork tests. The skip is the existing read-only-root-with-workdir case.test_sandbox_runtime.pycovers the warm pool with a fake backend.pre-commit run --files <changed files>with pre-commit 3.5.0 (every hook that applies, including both ruff hooks, pydoclint and black) and the API parameter coverage check (ci/ray_ci/doc/cmd_check_api_param_coverage.py --base-ref origin/master --blocking) pass.