Skip to content

[core][sandbox] Stop a sandbox with its owner, and reclaim what it leaves - #67022

Merged
pcmoritz merged 6 commits into
ray-project:masterfrom
xyuzh:sandbox-owner-lifetime
Oct 20, 2026
Merged

pcmoritz merged 6 commits into
ray-project:masterfrom
xyuzh:sandbox-owner-lifetime

Conversation

@xyuzh

@xyuzh xyuzh commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

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 [core][sandbox] Reap network="public" helpers instead of leaving zombies #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 flocked, 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

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a robust sandbox ownership and reclamation mechanism to prevent resource leaks when Ray workers exit or crash. It implements file-locking via 'fcntl' on an '.owner' file to track active sandboxes, allowing subsequent sandbox creations to periodically reclaim unowned bundles, delete leftover runsc states, and release cached images. Additionally, it refactors public network sandboxes to use 'setpriv --pdeathsig' to ensure helper processes are cleaned up, preventing zombie processes. Feedback on these changes suggests immediately removing the local sandbox directory on initialization failure to avoid permanent disk leaks if the owner file is not yet created, and reducing the reclamation subprocess timeout from 10 to 3 seconds to prevent synchronous creation timeouts when 'runsc' is wedged.

Comment on lines 187 to 194
except Exception as err:
self._image_manager.release_image(config.image, sandbox_id)
# The next reclaim deletes the bundle.
if owner_file:
owner_file.close()
raise SandboxCreationError(
f"Failed to initialize local sandbox directory '{root_dir}': {err}"
) from err

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

If _own_bundle fails or is not called, the .owner file is never created. Because the reclaim logic (_reclaim_if_unowned) ignores directories without a .owner file to avoid deleting bundles currently being created, this directory will be leaked permanently on disk. Even if .owner was successfully created, it is much safer and cleaner to immediately clean up the root_dir on failure rather than leaving it for a future reclaim cycle.

Suggested change
except Exception as err:
self._image_manager.release_image(config.image, sandbox_id)
# The next reclaim deletes the bundle.
if owner_file:
owner_file.close()
raise SandboxCreationError(
f"Failed to initialize local sandbox directory '{root_dir}': {err}"
) from err
except Exception as err:
self._image_manager.release_image(config.image, sandbox_id)
if owner_file:
owner_file.close()
shutil.rmtree(root_dir, ignore_errors=True)
raise SandboxCreationError(
f"Failed to initialize local sandbox directory '{root_dir}': {err}"
) from err

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 9576d41: both early failure paths in create_sandbox now rmtree the bundle before they release the image pin and close the owner file, so a create that fails before the owner file exists leaves nothing behind. test_failed_create_leaves_no_bundle covers a failed pull and an owner file that can't be written (ENOSPC).

Comment on lines +745 to +750
try:
subprocess.run(
[*runsc_args, *action], capture_output=True, timeout=10
)
except (OSError, subprocess.TimeoutExpired):
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Since _maybe_reclaim_unowned_bundles runs synchronously during create_sandbox, any delay in reclaiming unowned bundles directly blocks the creation of new sandboxes. If runsc is wedged, a 10-second timeout per action (kill and delete) can block the thread for up to 20 seconds per orphaned sandbox, easily triggering a timeout for the new sandbox creation. Reducing this timeout to a shorter duration (e.g., 3 seconds) is much safer and prevents cascading timeouts.

Suggested change
try:
subprocess.run(
[*runsc_args, *action], capture_output=True, timeout=10
)
except (OSError, subprocess.TimeoutExpired):
pass
try:
subprocess.run(
[*runsc_args, *action], capture_output=True, timeout=3
)
except (OSError, subprocess.TimeoutExpired):
pass

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 differently in 9576d41: the reclaim pass now runs in a daemon thread, still at most once a minute per process, so a create never waits for it (test_reclaim_runs_in_the_background). I kept the 10 s runsc timeouts, the same as _delete_container_state's, so a slow but healthy runsc still gets a dead owner's state deleted.

@ray-gardener ray-gardener Bot added docs An issue or change related to documentation core Issues that should be addressed in Ray Core labels Oct 14, 2026
@xyuzh
xyuzh force-pushed the sandbox-owner-lifetime branch from 0337803 to fa3b33a Compare October 15, 2026 15:14
pcmoritz pushed a commit that referenced this pull request Oct 16, 2026
…ies (#66987)

## Description

A `network="public"` sandbox's launch shell starts a namespace holder
(`unshare` and its `sleep`) and `slirp4netns`, then exec'd runsc, which
became their parent and never waits for them. A stopped sandbox's
helpers were orphaned to the pod's init, and Anyscale's init, like many
container entrypoints, doesn't reap orphans. So every `public` sandbox
left three zombies under PID 1 until the pod restarted. SkyRL's
SWE-bench Multimodal runs left about 300 per node.

Changes in `backend/gvisor.py`:

- The shell stays the parent. It runs runsc in the background and waits
for it, and an exit trap kills the holder's `sleep` (so `unshare` reaps
it) and `slirp4netns`, then waits for both.
- Teardown (`_terminate_tree`) gives the shell 2 s to exit on its own.
It kills the process group only if the shell is still running, before
reaping it, so the signal can't reach a group that reused the pid.
- The holder, `slirp4netns` and runsc run under `setpriv --pdeathsig
KILL`, so they die with the shell, which is what Ray kills when the
owning worker exits.
- `create_sandbox` checks for `setpriv` up front. The docs ask for
util-linux 2.33 or later, which added `--pdeathsig`.

On an Anyscale node whose PID 1 doesn't reap orphans:

| | master | This PR |
| --- | --- | --- |
| New zombies after 5 `public` sandboxes are created and deleted | 16 |
0 |
| 15 s after `ray.kill` of a `public` sandbox's owner, without `delete`
| Holder still running | Nothing running |

#67022, stacked on this PR, reclaims the runsc state and bundle that a
killed owner leaves.

## Related issues

None filed. Found with SkyRL's Harbor environment for Ray Sandbox
(skyrl-project/SkyRL#2467).

## Additional information

- Not a duplicate: no open PR changes how these helpers are reaped (I
searched "sandbox zombie", "slirp4netns zombie" and "sandbox reap").
#66470, #65898 and #66471 also edit the end of the `public` launch
script, so whichever lands later needs the same change.
- Tests: `test_netns_teardown_leaves_no_zombies` and
`test_netns_launch_shell_death_stops_the_sandbox` make the test process
a child subreaper, so a helper the backend fails to reap becomes the
test's own zombie. Both fail on master.
`test_terminate_tree_kills_the_group_only_before_reaping_it` needs no
gVisor and fails on the first commit.
- Tested in a CoreWeave pod (Ubuntu 22.04, runsc release-20261005.0, Ray
nightly) with `TEST_SANDBOX=1 pytest --import-mode=importlib` in
`python/ray/experimental/sandbox/tests`: `test_gvisor_backend.py -k
netns`: 11 passed; `test_gvisor_backend.py test_image_manager.py
test_image_utils.py test_sandbox_config.py test_sandbox_runtime.py -k
"not netns"`: 89 passed, 1 skipped (`test_create_sandbox_helper`
deselected, since it starts its own Ray). pre-commit passes.
- I used Claude Code to help write and test this change.

---------

Signed-off-by: xyuzh <[email protected]>
@xyuzh
xyuzh force-pushed the sandbox-owner-lifetime branch from fa3b33a to df44915 Compare October 16, 2026 23:33
@pcmoritz
pcmoritz enabled auto-merge (squash) October 19, 2026 18:21
@github-actions github-actions Bot added the go add ONLY when ready to merge, run all tests label Oct 19, 2026
xyuzh added 5 commits October 19, 2026 14:49
…aves

A sandbox's launch process ran in a session of its own. When the Ray
worker that owned the sandbox crashed, the raylet's per-worker process
group cleanup never reached it, so the sandbox kept running with no one
to delete it, and its TTL died with the actor. Its runsc state, bundle
(with the writable overlay) and image pin stayed on the node for good.

The launch process now stays in its owner's process group, so the
raylet stops it with the worker; teardown kills only the launch process,
whose children die with it through their parent-death signals. Each
bundle holds an owner file that the owning backend keeps locked. The
kernel drops the lock when the owner dies, and the next create on the
node (at most once a minute per process) reclaims every bundle whose
lock is free: it kills a sandbox that is still running, deletes runsc's
state and the bundle, and releases the image pin. The owner file
records flags, not a command line, so reclaiming never runs a command
read from disk. A create that fails before its sandbox starts gives up
its bundle, so the next reclaim deletes it.

Signed-off-by: xyuzh <[email protected]>
…'s bundle at once

Review follow-ups:
- A create that failed before its owner file existed, say on a full
  disk, left a bundle that no reclaim would ever take. A failed create
  now deletes its bundle right away, as ray-project#66469 also does.
- A reclaim pass ran inside create_sandbox, so many dead owners, or a
  wedged runsc with its 10 s timeouts, delayed the create. The pass now
  runs in a daemon thread, still at most once a minute per process.

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

The docs said the next sandbox created on the node cleans up after a
sandbox whose owner died. A process runs that pass at most once a
minute, so a create soon after its last pass doesn't start one.

Signed-off-by: xyuzh <[email protected]>
The launch process now shares its owner's process group, so a Ctrl-C in
a driver's terminal, or a Jupyter kernel interrupt, which signals the
kernel's whole group, reached it too. A network="none" sandbox died with
runsc. A public one lost its network: the launch shell ran its exit trap
and killed slirp4netns, while runsc, a background job, ignored the
SIGINT and kept the sandbox up.

Every launch command now starts with `trap '' INT QUIT`. For the other
modes, a minimal shell sets it and execs runsc. An ignored signal stays
ignored across exec, and runsc keeps SIGINT ignored, so a sandbox again
stops only with its owner (SIGTERM, then SIGKILL, to the owner's group)
or on delete, as when it had a session of its own. Go installs its own
SIGQUIT handler, so a SIGQUIT still ends runsc, and its sandbox, cleanly.

Signed-off-by: xyuzh <[email protected]>
A reclaim pass removed a dead owner's bundle with one rmtree, in
directory order. The pass runs in a daemon thread, so it can be cut
short with the process that runs it, and once the owner file was gone,
no later pass would find what was left, possibly the overlay's backing
file. The pass now deletes everything else and releases the image pin
first, and the owner file and directory last.

Signed-off-by: xyuzh <[email protected]>
@xyuzh
xyuzh force-pushed the sandbox-owner-lifetime branch from df44915 to 0a45c30 Compare October 19, 2026 21:56
@github-actions
github-actions Bot disabled auto-merge October 19, 2026 21:56
pcmoritz pushed a commit that referenced this pull request Oct 20, 2026
…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]>
@pcmoritz
pcmoritz enabled auto-merge (squash) October 20, 2026 08:41
@pcmoritz
pcmoritz merged commit 05d07da into ray-project:master Oct 20, 2026
7 checks passed
xyuzh added a commit to xyuzh/ray that referenced this pull request Oct 20, 2026
…s ruleset

ray-project#67022 made every create that fails before its sandbox starts delete its
bundle and close its owner file. The egress ruleset's failure path, which
ray-project#67022 didn't know about, only released the image, so the bundle stayed on
the node, locked by the worker, until the worker exited.

Signed-off-by: xyuzh <[email protected]>
xyuzh added a commit to xyuzh/ray that referenced this pull request Oct 22, 2026
…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]>
pcmoritz pushed a commit that referenced this pull request Oct 22, 2026
## 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 #67022, so sandboxes
created at the same time spread out.
- Cleanup reuses #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 #65352 (why CI needs `--ignore-cgroups`). #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 #66528 and #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]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 2, 2026
…ies (ray-project#66987)

## Description

A `network="public"` sandbox's launch shell starts a namespace holder
(`unshare` and its `sleep`) and `slirp4netns`, then exec'd runsc, which
became their parent and never waits for them. A stopped sandbox's
helpers were orphaned to the pod's init, and Anyscale's init, like many
container entrypoints, doesn't reap orphans. So every `public` sandbox
left three zombies under PID 1 until the pod restarted. SkyRL's
SWE-bench Multimodal runs left about 300 per node.

Changes in `backend/gvisor.py`:

- The shell stays the parent. It runs runsc in the background and waits
for it, and an exit trap kills the holder's `sleep` (so `unshare` reaps
it) and `slirp4netns`, then waits for both.
- Teardown (`_terminate_tree`) gives the shell 2 s to exit on its own.
It kills the process group only if the shell is still running, before
reaping it, so the signal can't reach a group that reused the pid.
- The holder, `slirp4netns` and runsc run under `setpriv --pdeathsig
KILL`, so they die with the shell, which is what Ray kills when the
owning worker exits.
- `create_sandbox` checks for `setpriv` up front. The docs ask for
util-linux 2.33 or later, which added `--pdeathsig`.

On an Anyscale node whose PID 1 doesn't reap orphans:

| | master | This PR |
| --- | --- | --- |
| New zombies after 5 `public` sandboxes are created and deleted | 16 |
0 |
| 15 s after `ray.kill` of a `public` sandbox's owner, without `delete`
| Holder still running | Nothing running |

ray-project#67022, stacked on this PR, reclaims the runsc state and bundle that a
killed owner leaves.

## Related issues

None filed. Found with SkyRL's Harbor environment for Ray Sandbox
(skyrl-project/SkyRL#2467).

## Additional information

- Not a duplicate: no open PR changes how these helpers are reaped (I
searched "sandbox zombie", "slirp4netns zombie" and "sandbox reap").
ray-project#66470, ray-project#65898 and ray-project#66471 also edit the end of the `public` launch
script, so whichever lands later needs the same change.
- Tests: `test_netns_teardown_leaves_no_zombies` and
`test_netns_launch_shell_death_stops_the_sandbox` make the test process
a child subreaper, so a helper the backend fails to reap becomes the
test's own zombie. Both fail on master.
`test_terminate_tree_kills_the_group_only_before_reaping_it` needs no
gVisor and fails on the first commit.
- Tested in a CoreWeave pod (Ubuntu 22.04, runsc release-20261005.0, Ray
nightly) with `TEST_SANDBOX=1 pytest --import-mode=importlib` in
`python/ray/experimental/sandbox/tests`: `test_gvisor_backend.py -k
netns`: 11 passed; `test_gvisor_backend.py test_image_manager.py
test_image_utils.py test_sandbox_config.py test_sandbox_runtime.py -k
"not netns"`: 89 passed, 1 skipped (`test_create_sandbox_helper`
deselected, since it starts its own Ray). 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
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 2, 2026
…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
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 2, 2026
…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
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 2, 2026
…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
pcmoritz added a commit that referenced this pull request Nov 9, 2026
## 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]>
xinyuangui2 pushed a commit to xinyuangui2/SkyRL that referenced this pull request Nov 13, 2026
…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]>
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.

2 participants