Repository navigation
[core][sandbox] Enforce CPU and memory limits with host cgroups - #66932
Conversation
Released Ray replaces an explicit zero CPU limit with the actor's CPU reservation, written as an OCI quota that rootless runsc doesn't enforce. ray-project/ray#66932 makes zero mean no limit and derives an enforced limit only from None, which is why this passes zero. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: xyuzh <[email protected]>
678e2bf to
1a2c3c1
Compare
There was a problem hiding this comment.
Code Review
This pull request introduces robust resource enforcement and CPU isolation (shared vs. exclusive physical cores) for Ray sandboxes using Linux cgroups v2. It adds a node-local cgroup manager, a dedicated launcher to safely join cgroups, and integrates these controls across the gVisor backend, HTTP API, and gRPC facade. The review feedback highlights several critical opportunities to improve robustness, including handling potential exceptions during cgroup reconciliation and release to prevent resource leaks, securing file descriptors against leaks if wrapping fails, safely parsing process statistics from /proc, and avoiding a potential AttributeError when validating integer CPU limits in the gRPC facade.
| if invalid_partition or ( | ||
| _process_identity(record["owner_pid"]) != record["owner_starttime"] | ||
| ): | ||
| _remove(record_path, record) |
There was a problem hiding this comment.
If _remove raises an exception (e.g., due to a stuck or uninterruptible D-state process preventing cgroup removal), it will propagate and fail the entire _reconcile process. This can block all subsequent sandbox allocations on the node. Wrapping the cleanup in a try...except block ensures that other independent sandboxes can still be allocated and reconciled.
| if invalid_partition or ( | |
| _process_identity(record["owner_pid"]) != record["owner_starttime"] | |
| ): | |
| _remove(record_path, record) | |
| if invalid_partition or ( | |
| _process_identity(record["owner_pid"]) != record["owner_starttime"] | |
| ): | |
| try: | |
| _remove(record_path, record) | |
| except Exception as err: | |
| logger.error("Failed to remove orphaned sandbox %s: %s", record_path, err) |
There was a problem hiding this comment.
Fixed in 0a8e4a2. _reconcile now catches (OSError, RuntimeError) per lease, logs a warning and continues. The lease file stays, so its cores remain reserved until a later pass (the reaper or the next allocation) removes it. The guard also covers the owner check, so an unreadable /proc/<pid>/stat keeps that one lease instead of failing the whole pass.
Test: test_unremovable_orphan_keeps_its_cores_without_blocking_others.
| def release(self) -> None: | ||
| with _locked(self.state_dir): | ||
| record_path = self.state_dir / f"{self.path.name}.json" | ||
| if record_path.exists(): | ||
| _remove(record_path, json.loads(record_path.read_text())) |
There was a problem hiding this comment.
If release raises an exception (e.g., if _remove fails because the cgroup is still populated), it will propagate and abort the sandbox deletion process in delete_sandbox, leaking the sandbox directory and container image. It can also mask the original exception during creation failure. Wrapping the cleanup in a try...except block to log a warning ensures robust cleanup.
| def release(self) -> None: | |
| with _locked(self.state_dir): | |
| record_path = self.state_dir / f"{self.path.name}.json" | |
| if record_path.exists(): | |
| _remove(record_path, json.loads(record_path.read_text())) | |
| def release(self) -> None: | |
| try: | |
| with _locked(self.state_dir): | |
| record_path = self.state_dir / f"{self.path.name}.json" | |
| if record_path.exists(): | |
| _remove(record_path, json.loads(record_path.read_text())) | |
| except Exception as err: | |
| logger.warning("Failed to release sandbox cgroup %s: %s", self.path, err) |
There was a problem hiding this comment.
Partly adopted in 0a8e4a2, but release() still raises. A failed release means a process may still be in the cgroup. delete_sandbox relies on the exception to keep its metadata so that a retry can finish, and the lease file stays so its cores aren't handed out. Instead:
create_sandboxlogs a failed release and raises the original creation error. It still releases the image and removes the directory.delete_sandboxreleases the cgroup in atry/finally, so the stderr log, the directory and the image pin are freed even when release fails. It then re-raises with the metadata still in place. Callers such asSandboxHostdon't retry a failed delete, and the reaper reclaims only cgroups, so those used to leak.
Tests: test_failed_create_reports_its_error_when_release_also_fails, test_failed_cgroup_release_still_frees_files_and_image.
There was a problem hiding this comment.
| def _write(path: Path, value: str) -> None: | ||
| # Never create a missing controller file on a regular filesystem. | ||
| # cgroup.kill is write-only, including for the delegated owner. | ||
| with os.fdopen(os.open(path, os.O_WRONLY), "w") as stream: | ||
| stream.write(value) |
There was a problem hiding this comment.
If os.fdopen fails to wrap the file descriptor returned by os.open, the file descriptor will be leaked. To prevent resource leaks, open the file descriptor first and ensure it is closed in an except block if wrapping fails.
| def _write(path: Path, value: str) -> None: | |
| # Never create a missing controller file on a regular filesystem. | |
| # cgroup.kill is write-only, including for the delegated owner. | |
| with os.fdopen(os.open(path, os.O_WRONLY), "w") as stream: | |
| stream.write(value) | |
| def _write(path: Path, value: str) -> None: | |
| # Never create a missing controller file on a regular filesystem. | |
| # cgroup.kill is write-only, including for the delegated owner. | |
| fd = os.open(path, os.O_WRONLY) | |
| try: | |
| with os.fdopen(fd, "w") as stream: | |
| stream.write(value) | |
| except Exception: | |
| os.close(fd) | |
| raise |
There was a problem hiding this comment.
Fixed differently in 0a8e4a2. The suggested except Exception: os.close(fd) closes the descriptor a second time whenever the write fails, because leaving the with block has already closed it. The real error (for example EINVAL from cpu.max) becomes EBADF. In a multithreaded worker, the second close can also hit a descriptor that another thread opened in between.
_write now calls os.write inside try: ... finally: os.close(fd). Nothing wraps the descriptor, so the leak window is gone, and it's closed exactly once.
| def _process_identity(pid: int) -> Optional[str]: | ||
| try: | ||
| # starttime distinguishes a live owner from a reused PID. Zombies | ||
| # cannot own sandboxes even though their /proc entries still exist. | ||
| fields = _read(Path(f"/proc/{pid}/stat")).rsplit(")", 1)[1].split() | ||
| return None if fields[0] == "Z" else fields[19] | ||
| except FileNotFoundError: | ||
| return None |
There was a problem hiding this comment.
Reading /proc/{pid}/stat can raise PermissionError (e.g., under hardened kernels or container environments with hidepid enabled), which is an OSError but not a FileNotFoundError. Additionally, if the file is malformed or has fewer fields than expected, fields[19] will raise an IndexError. Catching (OSError, IndexError) makes this function much more robust.
| def _process_identity(pid: int) -> Optional[str]: | |
| try: | |
| # starttime distinguishes a live owner from a reused PID. Zombies | |
| # cannot own sandboxes even though their /proc entries still exist. | |
| fields = _read(Path(f"/proc/{pid}/stat")).rsplit(")", 1)[1].split() | |
| return None if fields[0] == "Z" else fields[19] | |
| except FileNotFoundError: | |
| return None | |
| def _process_identity(pid: int) -> Optional[str]: | |
| try: | |
| # starttime distinguishes a live owner from a reused PID. Zombies | |
| # cannot own sandboxes even though their /proc entries still exist. | |
| fields = _read(Path(f"/proc/{pid}/stat")).rsplit(")", 1)[1].split() | |
| return None if fields[0] == "Z" else fields[19] | |
| except (OSError, IndexError): | |
| return None |
There was a problem hiding this comment.
Partly adopted in 0a8e4a2. _process_identity now also catches ProcessLookupError. If the process is reaped after open(), reading /proc/<pid>/stat fails with ESRCH, which proves the owner is dead.
It doesn't map every OSError or IndexError to None. None makes _reconcile kill the lease's cgroup, so only errors that prove the process is gone should produce it; a transient EMFILE could otherwise kill a live sandbox. Other errors, such as EPERM under hidepid=1, now leave that one lease in place through the new per-lease guard in _reconcile instead of failing the pass. /proc/<pid>/stat is kernel ABI, so fields[19] doesn't need a guard.
Test: test_process_identity_treats_only_a_vanished_process_as_dead.
| if settings.cpu_isolation == "exclusive" and ( | ||
| cpu_limit is None or not cpu_limit.is_integer() | ||
| ): |
There was a problem hiding this comment.
If cpu_limit is an int rather than a float, calling cpu_limit.is_integer() will raise an AttributeError because int objects do not have this method. Using cpu_limit % 1 != 0 is safe for both int and float types and avoids potential runtime crashes.
| if settings.cpu_isolation == "exclusive" and ( | |
| cpu_limit is None or not cpu_limit.is_integer() | |
| ): | |
| if settings.cpu_isolation == "exclusive" and ( | |
| cpu_limit is None or cpu_limit % 1 != 0 | |
| ): |
There was a problem hiding this comment.
No change needed. cpu_limit can't be an int here. It's resources.milli_cpu_max / 1000.0 (milli_cpu_max is a uint32), or None when that's 0, and true division always returns a float. The HTTP API's ResourceSpec.cpu_limit is safe too, because pydantic coerces 2 to 2.0 for a float field.
|
Unless there is a good reason, I think we should reuse gvisors built in cgroups support for this instead of implementing it ourselves. |
|
I tried that first. runsc's cgroup setup doesn't work inside a delegated subtree, which is what a pod or an unprivileged worker gets:
On a CoreWeave pod (runsc release-20261005.0), with
What reusing runsc would buy is guest sizing: runsc sizes the sandbox from its own cgroup, so a 1-CPU, 512 MiB sandbox sees If runsc enabled only the controllers it needs, and only where they're missing, Ray could hand it the cgroup it creates and drop its own |
2fc1ef5 to
9ac3776
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 9ac3776. Configure here.
…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]>
…aves (#67022) ## Description When the Ray worker that owns a sandbox crashed or was OOM-killed, the sandbox kept running with nobody to delete it: its launch process had a session of its own, out of reach of the raylet's process-group cleanup, and its TTL died with the actor. However the owner died, its runsc state, bundle (with the overlay's backing file) and image-cache pin stayed on the node, and the pin kept the image from being evicted. In `backend/gvisor.py`: - The launch process stays in its owner's process group (no `start_new_session`), so when the raylet kills a dead worker's group, the sandbox goes too: runsc's sandbox through runsc's parent-death signal, a `public` sandbox's helpers through #66987's `setpriv --pdeathsig`. Teardown kills only the launch process. - Every launch command starts with `trap '' INT QUIT`, so a Ctrl-C in the creator's terminal, or a Jupyter kernel interrupt, still leaves its sandboxes running, as on master. A SIGQUIT (Ctrl-\\) still stops them, since runsc is a Go program and installs its own handler. - Each bundle holds an `.owner` file that the owning backend keeps `flock`ed, and the kernel drops the lock when the owner dies. `create_sandbox` starts a background pass, at most once a minute per process, that reclaims every bundle whose lock is free: it kills a sandbox still running there, runs `runsc delete -force`, releases the image pin and removes the bundle, owner file last. The file is locked before it gets its name, so a bundle being created is never taken, and it holds flags rather than a command line, so a planted file can't make the reclaim run anything. Start with `_own_bundle` and `_reclaim_if_unowned`. - A create that fails before its sandbox starts deletes its bundle at once. A sandbox now stops with the worker that created it. One created outside a Ray worker, such as by a driver script, outlives its creator until a later reclaim pass stops it, and `sandboxes.md` says so. Sandbox processes 3 s and 15 s after its owner's worker is SIGKILLed, without `delete`: | | #66987 | This PR | | --- | --- | --- | | `network="none"` | 3 and 3 | 0 and 0 | | `network="public"` | 5 and 5 | 0 and 0 | | runsc state, bundle and image pin after the next create | Still there | Gone | ## Related issues None filed. Found with SkyRL's Harbor environment for Ray Sandbox (skyrl-project/SkyRL#2467). Its SWE-bench Multimodal report notes both leaks. ## Additional information - Not a duplicate: no open PR ties a sandbox to its owner or reclaims a dead owner's files (I searched "sandbox orphan", "owner", "crash", "leak", "reclaim", "process group" and "TTL"). My #66932 also deletes dead owners' files for sandboxes with limits, and #66469 also deletes a failed create's bundle; whichever lands second drops its copy. #66471 and #66470 add launch paths that still use `start_new_session`. - Builds on #66987, which is merged. - Tests: four gVisor tests kill an owner with its group (as the raylet does) or alone (as a driver can die), for `none` and `public`, and check that the sandbox stops and the reclaim deletes its files and pin. Two more (`test_owner_interrupt_leaves_its_sandbox_running` and its `netns` twin) send the owner's group SIGINT, then SIGTERM: the sandbox must keep running, network included, and then stop. Six unit tests cover which bundles a reclaim takes, what it runs, the order it deletes in, failed creates, the background pass and teardown. All fail on #66987. - Tested in a CoreWeave pod (Ubuntu 22.04, runsc release-20261012.0, Ray nightly), rebased on master afd4ccf, with `TEST_SANDBOX=1 pytest --import-mode=importlib` in `python/ray/experimental/sandbox/tests`, on `test_gvisor_backend.py test_image_manager.py test_image_utils.py test_sandbox_config.py test_sandbox_runtime.py`: `-k netns`: 16 passed; `-k "not netns"`: 120 passed, 1 skipped (`test_create_sandbox_helper` deselected; it passes on its own). pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Philipp Moritz <[email protected]> Co-authored-by: Philipp Moritz <[email protected]>
|
A few comments on this, high level it looks good, but there are some small improvements we should make before merging it:
|
Sandboxes wrote CPU and memory limits into the OCI spec, but rootless runsc and --ignore-cgroups never enforced them: a 1-CPU sandbox could use every core on the node, and a 512 MiB sandbox could allocate 1.5 GiB. Allocate a host cgroup v2 budget for each limited sandbox from a subtree the node delegates through RAY_SANDBOX_CGROUP_PATH. runsc, its network helpers, and every exec, file write, and file read join that cgroup before they start, and a sandbox with a CPU limit runs on max(2, ceil(cpu)) CPUs so that nproc matches its budget. An OOM kill becomes the sandbox's termination reason. A positive limit now fails before the image pull on a node without a delegated subtree. An explicit cpu=0 means unlimited instead of falling back to the actor's assigned CPUs. Signed-off-by: xyuzh <[email protected]>
create_sandbox's handler already released the cgroup and the image pin and removed the bundle of a create that failed, and _start_sandbox repeated the image release in three of its exception paths and the bundle removal in another. _start_sandbox now cleans up only what it starts: the launch process, runsc's state and the stderr log. create_sandbox makes the bundle and its owner file, and its handler closes that file too. The DNS check runs after _start_sandbox returns, once delete_sandbox owns the sandbox's cleanup. Signed-off-by: xyuzh <[email protected]>
…roject#67022 This PR tracked its own ownership: a lease per sandbox with the owner's PID, start time and boot ID, a per-node reaper that polled the leases every second, and its own cleanup of a dead owner's runsc state, bundle and image pin. ray-project#67022 now does the ownership and the cleanup with each bundle's locked .owner file, so build on that instead: - The reclaim pass also kills and removes the sandbox's cgroup. The path is RAY_SANDBOX_CGROUP_PATH/<sandbox id>, never one read from the file. - A sandbox's CPUs go in its owner file. They're picked under a node-wide lock, /tmp/ray/sandbox/cpus.lock, and only bundles whose owner holds the lock count, so a dead owner's CPUs are free at once. - When a cgroup can't be removed, delete_sandbox and a failed create leave the bundle, owner file included, to a later reclaim pass. - The limits are checked before the create touches the node. The reaper, the leases, RAY_SANDBOX_CGROUP_STATE_DIR and image_use_marker are gone. A Ray worker's sandboxes stop with the worker (ray-project#67022), which frees their CPU and memory, and the next reclaim pass removes the empty cgroup. Signed-off-by: xyuzh <[email protected]>
The kernel stores memory.max in whole pages, rounded down, so a limit that isn't a page multiple, such as memory="1GB", read back smaller than what was written. The create's check then failed after runsc had already started. Ray now writes the rounded value, which is the limit the kernel enforces anyway. Signed-off-by: xyuzh <[email protected]>
9ac3776 to
100351a
Compare
xyuzh
left a comment
There was a problem hiding this comment.
Done, all three, on top of a rebase onto master. The first commit is the rebased version of what you reviewed, and each follow-up covers one item, so you can read them on their own:
- #66528 is merged, so this PR no longer touches
--gofer-network-namespace. Therunsc flagsprobe and its test are gone (71cd523). - 3a614a9 reuses #67022's owner files. The leases, the PID/start-time/boot-ID checks,
_clean_up_orphan()and the reaper are gone._reclaim_if_unownednow also kills and removes the sandbox's cgroup atRAY_SANDBOX_CGROUP_PATH/<sandbox id>, never at a path read from the file. A sandbox's CPUs go into its owner file, picked under a node-wide lock, and only bundles whose owner still holds the lock count. If a cgroup can't be removed,delete_sandboxand a failed create leave the bundle to a later pass. - I didn't keep a periodic monitor. A Ray worker's sandboxes stop with the worker (#67022), so their CPU and memory are free right away, and the next pass removes the empty cgroup with the rest of the bundle. A standalone
SandboxRuntime's sandbox keeps running until a pass, as #67022 documents, and its limits still hold meanwhile.test_reclaim_removes_a_dead_owners_cgroupchecks both cases on a real cgroup. - 4eb8655 leaves
_start_sandboxto clean up only what it starts: the launch process, runsc's state and the stderr log.create_sandboxmakes the bundle and owner file, and its handler deletes the cgroup, image pin and bundle. Theprepare_oci_bundle()try/except is gone, andtest_failed_create_leaves_no_bundlegained a case for it.
100351a also fixes Bugbot's memory.max finding. Test runs are in the description.
| def release(self) -> None: | ||
| with _locked(self.state_dir): | ||
| record_path = self.state_dir / f"{self.path.name}.json" | ||
| if record_path.exists(): | ||
| _remove(record_path, json.loads(record_path.read_text())) |
There was a problem hiding this comment.
| def _process_identity(pid: int) -> Optional[str]: | ||
| try: | ||
| # starttime distinguishes a live owner from a reused PID. Zombies | ||
| # cannot own sandboxes even though their /proc entries still exist. | ||
| fields = _read(Path(f"/proc/{pid}/stat")).rsplit(")", 1)[1].split() | ||
| return None if fields[0] == "Z" else fields[19] | ||
| except FileNotFoundError: | ||
| return None |
test_netns_sandbox_actor_changes_its_egress_allowlist fails on CI for every sandbox PR since ray-project#66528 stopped CI from skipping network="public" tests. CI has no slirp4netns, so ensure_slirp4netns downloads one and adds it to the test process's PATH, but an earlier test in the file has already started Ray's workers with the old PATH, and the actor can't find it. The actor now gets the test's PATH through its runtime_env. Signed-off-by: xyuzh <[email protected]>
|
@pcmoritz @andrewsykim One change after your approvals: a46daec fixes |
|
Thanks for fixing this! |
Callers that drive SandboxRuntime directly, such as actors that create sandboxes in bursts, pay a gVisor boot on every create. `SandboxRuntime(warm_pool=[...])` takes profiles, each the create() arguments of one boot configuration plus a pool `size`, and keeps that many sandboxes booted per profile, a few boots at a time. A create whose boot-time arguments match a profile takes a booted sandbox at once and a replacement boots in the background. The create's `env` goes on every command the sandbox runs, and its TTL starts at the create. `wait_for_warm_pool()` waits for full pools, and `close()` deletes the sandboxes the pool still holds. A profile whose boot fails boots no replacements for 30 s, and two profiles that boot the same sandboxes are refused. The pool never hands out a sandbox that died while it waited, because the gVisor backend's `get_status` reports one whose launch process exited (ray-project#66932). 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
…aves (ray-project#67022) ## Description When the Ray worker that owns a sandbox crashed or was OOM-killed, the sandbox kept running with nobody to delete it: its launch process had a session of its own, out of reach of the raylet's process-group cleanup, and its TTL died with the actor. However the owner died, its runsc state, bundle (with the overlay's backing file) and image-cache pin stayed on the node, and the pin kept the image from being evicted. In `backend/gvisor.py`: - The launch process stays in its owner's process group (no `start_new_session`), so when the raylet kills a dead worker's group, the sandbox goes too: runsc's sandbox through runsc's parent-death signal, a `public` sandbox's helpers through ray-project#66987's `setpriv --pdeathsig`. Teardown kills only the launch process. - Every launch command starts with `trap '' INT QUIT`, so a Ctrl-C in the creator's terminal, or a Jupyter kernel interrupt, still leaves its sandboxes running, as on master. A SIGQUIT (Ctrl-\\) still stops them, since runsc is a Go program and installs its own handler. - Each bundle holds an `.owner` file that the owning backend keeps `flock`ed, and the kernel drops the lock when the owner dies. `create_sandbox` starts a background pass, at most once a minute per process, that reclaims every bundle whose lock is free: it kills a sandbox still running there, runs `runsc delete -force`, releases the image pin and removes the bundle, owner file last. The file is locked before it gets its name, so a bundle being created is never taken, and it holds flags rather than a command line, so a planted file can't make the reclaim run anything. Start with `_own_bundle` and `_reclaim_if_unowned`. - A create that fails before its sandbox starts deletes its bundle at once. A sandbox now stops with the worker that created it. One created outside a Ray worker, such as by a driver script, outlives its creator until a later reclaim pass stops it, and `sandboxes.md` says so. Sandbox processes 3 s and 15 s after its owner's worker is SIGKILLed, without `delete`: | | ray-project#66987 | This PR | | --- | --- | --- | | `network="none"` | 3 and 3 | 0 and 0 | | `network="public"` | 5 and 5 | 0 and 0 | | runsc state, bundle and image pin after the next create | Still there | Gone | ## Related issues None filed. Found with SkyRL's Harbor environment for Ray Sandbox (skyrl-project/SkyRL#2467). Its SWE-bench Multimodal report notes both leaks. ## Additional information - Not a duplicate: no open PR ties a sandbox to its owner or reclaims a dead owner's files (I searched "sandbox orphan", "owner", "crash", "leak", "reclaim", "process group" and "TTL"). My ray-project#66932 also deletes dead owners' files for sandboxes with limits, and ray-project#66469 also deletes a failed create's bundle; whichever lands second drops its copy. ray-project#66471 and ray-project#66470 add launch paths that still use `start_new_session`. - Builds on ray-project#66987, which is merged. - Tests: four gVisor tests kill an owner with its group (as the raylet does) or alone (as a driver can die), for `none` and `public`, and check that the sandbox stops and the reclaim deletes its files and pin. Two more (`test_owner_interrupt_leaves_its_sandbox_running` and its `netns` twin) send the owner's group SIGINT, then SIGTERM: the sandbox must keep running, network included, and then stop. Six unit tests cover which bundles a reclaim takes, what it runs, the order it deletes in, failed creates, the background pass and teardown. All fail on ray-project#66987. - Tested in a CoreWeave pod (Ubuntu 22.04, runsc release-20261012.0, Ray nightly), rebased on master afd4ccf, with `TEST_SANDBOX=1 pytest --import-mode=importlib` in `python/ray/experimental/sandbox/tests`, on `test_gvisor_backend.py test_image_manager.py test_image_utils.py test_sandbox_config.py test_sandbox_runtime.py`: `-k netns`: 16 passed; `-k "not netns"`: 120 passed, 1 skipped (`test_create_sandbox_helper` deselected; it passes on its own). pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Philipp Moritz <[email protected]> Co-authored-by: Philipp Moritz <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
…project#66932) ## Description Sandbox CPU and memory limits aren't enforced today. Ray writes them into the OCI spec, but `network="public"` runs runsc with `--ignore-cgroups`, and rootless runsc skips cgroup errors. On master, four busy processes in a `cpu=1` sandbox finish about as fast as one, and a `memory="512Mi"` sandbox can allocate 1.5 GiB. This PR gives each limited sandbox a cgroup v2 that Ray creates in a subtree the node delegates (`RAY_SANDBOX_CGROUP_PATH`): - Ray writes `cpu.max`, `memory.max`, `memory.swap.max=0` and `memory.oom.group=1`. runsc, its network helpers, and every exec and file operation start through a small launcher that joins the cgroup first. runsc keeps `--ignore-cgroups`, because its own setup writes into every ancestor's `cgroup.subtree_control` (see the review discussion). - A sandbox with a CPU limit runs on `max(2, ceil(cpu))` CPUs, so `nproc` matches its budget. Ray picks them under a node-wide file lock and records them in the sandbox's owner file from ray-project#67022, so sandboxes created at the same time spread out. - Cleanup reuses ray-project#67022. A sandbox stops with the worker that owns it, and the reclaim pass that deletes a dead owner's bundle also kills and removes the sandbox's cgroup. - An OOM kill stops the sandbox, not its worker, and becomes the sandbox's termination reason. Exclusive CPU cores (`cpu_isolation="exclusive"`) follow in a separate PR stacked on this one, so this PR adds no API parameter. Behavior changes: - A positive `cpu` or `memory` on a node without a delegated subtree now fails before the image pull instead of being ignored. Sandboxes without limits are unaffected. - `cpu=0` means no limit. The `Sandbox` actor derives a limit from its assigned CPUs only for `cpu=None`. - A create error that isn't a `SandboxError` now becomes a `SandboxCreationError`, and a failed launch no longer leaves its bundle behind. - Known gap: `MemTotal` inside the sandbox still shows the node's memory, because runsc sizes memory only from a cgroup it set up. How to review: `_internal/cgroup.py` and `cgroup_launcher.py`, then `create_sandbox`, `_start_sandbox`, `delete_sandbox` and `_reclaim_if_unowned` in `backend/gvisor.py`, the plumbing in `runtime.py`, `sandbox.py` and `http/host.py`, then the tests. ## Related issues Related to ray-project#65352 (why CI needs `--ignore-cgroups`). ray-project#65751 asks for limits on container workers, which this PR doesn't touch. ## Additional information - Not a duplicate: no open PR enforces sandbox limits (searched "sandbox cgroup", "resource limits", "cpu limit", "memory limit", "gvisor cgroup"). It builds on ray-project#66528 and ray-project#67022, which are merged. - Tests: `test_cgroup.py` uses fake cgroup files. `test_resource_limits.py` checks real enforcement, OOM and a dead owner's cleanup, and CI skips it because CI has no delegated subtree. - Tested on a CoreWeave pod (rayproject/ray:nightly-py312, runsc release-20261012.0, root with `SYS_ADMIN`), `TEST_SANDBOX=1 pytest test_gvisor_backend.py test_image_manager.py test_image_utils.py test_sandbox_config.py test_sandbox_runtime.py test_cgroup.py test_resource_limits.py test_egress_guard.py -k "not netns"`, with `test_create_sandbox_helper` deselected: - Without `RAY_SANDBOX_CGROUP_PATH`, as in CI: 189 passed, 11 skipped. `-k netns`: 21 passed. `test_sandbox.py`: 7 passed, 1 skipped. `http/tests/test_http_integration.py`: 2 passed. - With a delegated pool: 199 passed, 1 skipped. `-k netns`: 21 passed. `test_sandbox.py`: 7 passed, 1 skipped. `test_resource_limits.py` on its own: 10 passed. Four processes that created `cpu=1` sandboxes at once got four disjoint CPU pairs. - macOS: `test_cgroup.py` 19 passed, 1 skipped. `http/tests` 168 passed, 10 skipped, plus `test_full_sandbox_lifecycle`, which needs gVisor. pre-commit and the API parameter coverage check pass. - 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 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]>
…uts, pass limits only where enforced Three issues from running SWE-bench Multimodal trials on Ray sandboxes: - The HarborSandbox actor ran one call at a time, so a second exec waited behind the first (19 s in one trial). It now runs up to max_concurrency calls (default 8) at once. - ttl_seconds defaulted to 3600 s, shorter than the agent and verifier timeouts (5400 s for SWE-bench), so long trials could lose their sandbox. The default is now 86400 s. The sandbox also stops when its actor dies once Ray has ray-project/ray#67022. - Ray enforces a sandbox's cpu and memory through a cgroup v2 subtree that the node delegates (RAY_SANDBOX_CGROUP_PATH), and with ray-project/ray#66932 it refuses them on a node without one. The actor now passes them as limits only on such nodes, unless enforce_limits says otherwise; the actor's Ray reservation applies everywhere. The run script no longer pins a 3600 s TTL and says to run the trainer on the cluster, and the smoke test checks that two commands run at once. Signed-off-by: xyuzh <[email protected]>

Description
Sandbox CPU and memory limits aren't enforced today. Ray writes them into the OCI spec, but
network="public"runs runsc with--ignore-cgroups, and rootless runsc skips cgroup errors. On master, four busy processes in acpu=1sandbox finish about as fast as one, and amemory="512Mi"sandbox can allocate 1.5 GiB.This PR gives each limited sandbox a cgroup v2 that Ray creates in a subtree the node delegates (
RAY_SANDBOX_CGROUP_PATH):cpu.max,memory.max,memory.swap.max=0andmemory.oom.group=1. runsc, its network helpers, and every exec and file operation start through a small launcher that joins the cgroup first. runsc keeps--ignore-cgroups, because its own setup writes into every ancestor'scgroup.subtree_control(see the review discussion).max(2, ceil(cpu))CPUs, sonprocmatches its budget. Ray picks them under a node-wide file lock and records them in the sandbox's owner file from [core][sandbox] Stop a sandbox with its owner, and reclaim what it leaves #67022, so sandboxes created at the same time spread out.Exclusive CPU cores (
cpu_isolation="exclusive") follow in a separate PR stacked on this one, so this PR adds no API parameter.Behavior changes:
cpuormemoryon a node without a delegated subtree now fails before the image pull instead of being ignored. Sandboxes without limits are unaffected.cpu=0means no limit. TheSandboxactor derives a limit from its assigned CPUs only forcpu=None.SandboxErrornow becomes aSandboxCreationError, and a failed launch no longer leaves its bundle behind.MemTotalinside the sandbox still shows the node's memory, because runsc sizes memory only from a cgroup it set up.How to review:
_internal/cgroup.pyandcgroup_launcher.py, thencreate_sandbox,_start_sandbox,delete_sandboxand_reclaim_if_unownedinbackend/gvisor.py, the plumbing inruntime.py,sandbox.pyandhttp/host.py, then the tests.Related issues
Related to #65352 (why CI needs
--ignore-cgroups). #65751 asks for limits on container workers, which this PR doesn't touch.Additional information
test_cgroup.pyuses fake cgroup files.test_resource_limits.pychecks real enforcement, OOM and a dead owner's cleanup, and CI skips it because CI has no delegated subtree.SYS_ADMIN),TEST_SANDBOX=1 pytest test_gvisor_backend.py test_image_manager.py test_image_utils.py test_sandbox_config.py test_sandbox_runtime.py test_cgroup.py test_resource_limits.py test_egress_guard.py -k "not netns", withtest_create_sandbox_helperdeselected:RAY_SANDBOX_CGROUP_PATH, as in CI: 189 passed, 11 skipped.-k netns: 21 passed.test_sandbox.py: 7 passed, 1 skipped.http/tests/test_http_integration.py: 2 passed.-k netns: 21 passed.test_sandbox.py: 7 passed, 1 skipped.test_resource_limits.pyon its own: 10 passed. Four processes that createdcpu=1sandboxes at once got four disjoint CPU pairs.test_cgroup.py19 passed, 1 skipped.http/tests168 passed, 10 skipped, plustest_full_sandbox_lifecycle, which needs gVisor. pre-commit and the API parameter coverage check pass.