Skip to content

[cherry-pick][2.58.0] Ray Sandboxing with gVisor (experimental) (#64964) - #65397

Merged
elliot-barn merged 1 commit into
releases/2.58.0from
sai-miduthuri/cherry-pick-64964-2.58.0
Aug 11, 2026
Merged

elliot-barn merged 1 commit into
releases/2.58.0from
sai-miduthuri/cherry-pick-64964-2.58.0

Conversation

@sai-miduthuri

@sai-miduthuri sai-miduthuri commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR adds the first version of the experimental sandboxing library in Ray based on gVisor. See the REP for more details.

This PR was tested with the following example scripts:

Related issues

Link related issues: "Fixes #1234", "Closes #1234", or "Related to #1234".

Additional information

Optional: Add implementation details, API changes, usage examples, screenshots, etc.

## Description

This PR adds the first version of the experimental sandboxing library in
Ray based on gVisor. See the
[REP](https://github.com/ray-project/enhancements/blob/main/reps/2026-07-14-ray-sandboxing.md)
for more details.

This PR was tested with the following example scripts:
* https://gist.github.com/andrewsykim/7286c607b7523435303102bf8517d23b
* https://gist.github.com/andrewsykim/00d1cb20b63b821c725c71eaa231fb13
* https://gist.github.com/andrewsykim/3c82d1b97c02ee71f1cc27cbd2b0f1ed

## Related issues
> Link related issues: "Fixes #1234", "Closes #1234", or "Related to
#1234".

## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.

---------

Signed-off-by: Andrew Sy Kim <[email protected]>
@sai-miduthuri
sai-miduthuri requested review from a team as code owners August 11, 2026 21:06
@elliot-barn
elliot-barn merged commit 625a296 into releases/2.58.0 Aug 11, 2026
3 of 5 checks passed
@elliot-barn
elliot-barn deleted the sai-miduthuri/cherry-pick-64964-2.58.0 branch August 11, 2026 21:07

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces an experimental sandboxing feature (ray.experimental.sandbox) using gVisor (runsc) to run isolated container environments within Ray actors. It includes components for image pulling, OCI bundle preparation, a gVisor backend, and comprehensive tests. The review feedback highlights several critical areas for improvement, including potential race conditions from using threading.Timer in a background thread, potential zombie processes and file descriptor leaks during sandbox creation and deletion, permission conflicts in multi-user environments from hardcoded /tmp paths, performance overhead from uncached OCI spec generation, a potential IndexError in manifest parsing, and disk space inefficiencies from uncompressed image caching.

Comment on lines +76 to +81
if ttl_seconds is not None and ttl_seconds > 0:
import threading

self._ttl_timer = threading.Timer(ttl_seconds, self.delete)
self._ttl_timer.daemon = True
self._ttl_timer.start()

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

The use of threading.Timer to call self.delete() introduces a background thread that mutates the actor's state and performs file system/subprocess operations concurrently with other actor methods (like exec, write_file, etc.). Ray actors are single-threaded by default, and concurrent access to self.runtime and self.runtime._backend._sandbox_metadata can lead to race conditions, undefined behavior, or crashes. Consider using a thread lock to protect actor state, or refactoring the actor to be async and scheduling the TTL cleanup on the asyncio event loop using asyncio.create_task and asyncio.sleep.

Comment on lines +185 to +190
if proc and proc.poll() is None:
proc.terminate()
try:
proc.communicate(timeout=2)
except subprocess.TimeoutExpired:
proc.kill()

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

In delete_sandbox, if proc.communicate(timeout=2) times out and raises TimeoutExpired, proc.kill() is called, but the process is never reaped afterwards. This can leave a zombie process in the system. Please call proc.wait() or proc.communicate() after proc.kill() to ensure the process is properly reaped.

Suggested change
if proc and proc.poll() is None:
proc.terminate()
try:
proc.communicate(timeout=2)
except subprocess.TimeoutExpired:
proc.kill()
if proc and proc.poll() is None:
proc.terminate()
try:
proc.communicate(timeout=2)
except subprocess.TimeoutExpired:
proc.kill()
try:
proc.communicate(timeout=2)
except Exception:
pass

Comment on lines +102 to +113
stderr_file = open(stderr_log_path, "w+", encoding="utf-8")
proc = subprocess.Popen(
run_args,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=stderr_file,
)
start_time = time.time()
timeout = config.timeout_seconds
state_args = self._runsc_base_args(config) + ["state", sandbox_id]

try:

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

If subprocess.Popen or any other statement before the try block raises an exception, stderr_file is left open and leaked. The try block should start immediately after opening stderr_file to ensure it is always closed in the except block.

Suggested change
stderr_file = open(stderr_log_path, "w+", encoding="utf-8")
proc = subprocess.Popen(
run_args,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=stderr_file,
)
start_time = time.time()
timeout = config.timeout_seconds
state_args = self._runsc_base_args(config) + ["state", sandbox_id]
try:
stderr_file = open(stderr_log_path, "w+", encoding="utf-8")
try:
proc = subprocess.Popen(
run_args,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=stderr_file,
)
start_time = time.time()
timeout = config.timeout_seconds
state_args = self._runsc_base_args(config) + ["state", sandbox_id]

Comment on lines +27 to +32
# Directory where runsc keeps container state. Every runsc invocation for a
# sandbox must agree on this, otherwise the container cannot be looked up.
_RUNSC_ROOT = "/tmp/runsc"

# Directory to store sandbox states, container images and overlay filesystem.
_RAY_SANDBOX_DIR = "/tmp/ray/sandbox"

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

Hardcoding /tmp/runsc and /tmp/ray/sandbox can cause permission denied errors in multi-user environments (like shared Ray clusters or on-premise servers) if another user has already created these directories with restrictive permissions. Consider making these paths user-specific by appending the current username or UID.

import getpass

try:
    _username = getpass.getuser()
except Exception:
    _username = str(os.getuid()) if hasattr(os, "getuid") else "default"

# Directory where runsc keeps container state. Every runsc invocation for a
# sandbox must agree on this, otherwise the container cannot be looked up.
_RUNSC_ROOT = f"/tmp/runsc-{_username}"

# Directory to store sandbox states, container images and overlay filesystem.
_RAY_SANDBOX_DIR = f"/tmp/ray/sandbox-{_username}"

Comment on lines +21 to +22
DEFAULT_IMAGES_DIR = "/tmp/ray/sandbox/images"
_USER_AGENT = "ray-sandbox/1.0 (python-urllib)"

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

Hardcoding /tmp/ray/sandbox/images can cause permission conflicts in multi-user environments. Consider making this path user-specific by appending the current username or UID.

import getpass

try:
    _username = getpass.getuser()
except Exception:
    _username = str(os.getuid()) if hasattr(os, "getuid") else "default"

DEFAULT_IMAGES_DIR = f"/tmp/ray/sandbox-{_username}/images"

Comment on lines +20 to +30
def get_default_oci_spec() -> Dict[str, Any]:
"""Derive default OCI runtime specification by executing `runsc spec` in a temporary directory.

Returns:
Dictionary representation of the default OCI config.json generated by `runsc spec`.
"""
with tempfile.TemporaryDirectory() as temp_dir:
subprocess.run(["runsc", "spec"], cwd=temp_dir, check=True)
config_path = os.path.join(temp_dir, "config.json")
with open(config_path, "r", encoding="utf-8") as f:
return json.load(f)

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

Running runsc spec via a subprocess on every call to get_default_oci_spec is slow and inefficient. Since the default OCI spec is static, we should cache it in memory after the first run to avoid subprocess overhead on subsequent sandbox creations.

_DEFAULT_OCI_SPEC = None


def get_default_oci_spec() -> Dict[str, Any]:
    """Derive default OCI runtime specification by executing `runsc spec` in a temporary directory.

    Returns:
        Dictionary representation of the default OCI config.json generated by `runsc spec`.
    """
    global _DEFAULT_OCI_SPEC
    if _DEFAULT_OCI_SPEC is None:
        with tempfile.TemporaryDirectory() as temp_dir:
            subprocess.run(["runsc", "spec"], cwd=temp_dir, check=True)
            config_path = os.path.join(temp_dir, "config.json")
            with open(config_path, "r", encoding="utf-8") as f:
                _DEFAULT_OCI_SPEC = json.load(f)
    return copy.deepcopy(_DEFAULT_OCI_SPEC)

Comment on lines +396 to +397
if not chosen_digest:
chosen_digest = manifest_data["manifests"][0]["digest"]

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

If manifest_data["manifests"] is empty, accessing index 0 will raise an IndexError. We should check if the list is non-empty first, and raise a descriptive SandboxCreationError if no manifests are found.

                        if not chosen_digest:
                            if not manifest_data["manifests"]:
                                raise SandboxCreationError(
                                    f"No manifests found in manifest list for image '{image}'"
                                )
                            chosen_digest = manifest_data["manifests"][0]["digest"]

Comment on lines +452 to +453
with tarfile.open(tar_path, "w") as tar:
tar.add(tmp_extract_dir, arcname=".")

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

Writing the cached tarball as an uncompressed tar file can consume significant disk space for larger container images. Since tarfile.open supports transparent decompression with mode="r:*", we can write the cache using gzip compression ("w:gz") to save disk space without breaking extraction.

Suggested change
with tarfile.open(tar_path, "w") as tar:
tar.add(tmp_extract_dir, arcname=".")
with tarfile.open(tar_path, "w:gz") as tar:
tar.add(tmp_extract_dir, arcname=".")

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 5 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 3a56b9e. Configure here.

envs = filtered_envs
for k, v in env_dict.items():
envs.append(f"{k}={v}")
spec["process"]["env"] = envs

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Empty env wipes container PATH

High Severity

create_oci_spec always replaces process.env with the image env list, even when that list is empty. That drops the default PATH from the runsc spec baseline. Local tars without .image_config.json, or registry pulls where the config blob fetch only warned and continued, then start with no PATH, so the init process sleep cannot be resolved and sandbox creation fails.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3a56b9e. Configure here.

"rw" if dest == container_cwd else "ro",
],
}
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Default workdir is not writable

High Severity

When no workdir is set and the image has no WorkingDir, the backend falls back to /, but bind-mount setup explicitly skips destination /. With default readonly=True, the rootfs stays read-only and no writable mount is added, so the documented “only writable path” is not writable and write_file / write execs fail for common images like busybox.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3a56b9e. Configure here.


self._ttl_timer = threading.Timer(ttl_seconds, self.delete)
self._ttl_timer.daemon = True
self._ttl_timer.start()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

TTL timer races actor methods

Medium Severity

The default TTL starts a threading.Timer that calls self.delete directly on a background thread. That bypasses Ray actor method serialization (max_concurrency defaults to 1), so teardown can run concurrently with exec, write_file, or other actor calls and race on backend metadata and the gVisor process.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3a56b9e. Configure here.

stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=stderr_file,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Failed create leaks sandbox dirs

Medium Severity

Directory setup under /tmp/ray/sandbox/... happens before OCI bundle prep and Popen, but cleanup only runs in the later wait-loop except. If prepare_oci_bundle, opening the stderr log, or starting runsc fails, the new root_dir (and possibly an open stderr handle) is left behind.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3a56b9e. Configure here.

meta = self._sandbox_metadata.get(sandbox_id)
if meta and os.path.exists(meta["root_dir"]):
return SandboxStatus.RUNNING
return SandboxStatus.TERMINATED

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Status ignores crashed containers

Medium Severity

get_status returns RUNNING whenever metadata exists and root_dir is present. It never checks the stored runsc process or runsc state, so a sandbox whose init process has exited still reports RUNNING until an explicit delete.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3a56b9e. Configure here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants