Repository navigation
[cherry-pick][2.58.0] Ray Sandboxing with gVisor (experimental) (#64964) - #65397
Conversation
## 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]>
There was a problem hiding this comment.
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.
| 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() |
There was a problem hiding this comment.
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.
| if proc and proc.poll() is None: | ||
| proc.terminate() | ||
| try: | ||
| proc.communicate(timeout=2) | ||
| except subprocess.TimeoutExpired: | ||
| proc.kill() |
There was a problem hiding this comment.
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.
| 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 |
| 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: |
There was a problem hiding this comment.
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.
| 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] |
| # 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" |
There was a problem hiding this comment.
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}"| DEFAULT_IMAGES_DIR = "/tmp/ray/sandbox/images" | ||
| _USER_AGENT = "ray-sandbox/1.0 (python-urllib)" |
There was a problem hiding this comment.
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"| 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) |
There was a problem hiding this comment.
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)| if not chosen_digest: | ||
| chosen_digest = manifest_data["manifests"][0]["digest"] |
There was a problem hiding this comment.
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"]| with tarfile.open(tar_path, "w") as tar: | ||
| tar.add(tmp_extract_dir, arcname=".") |
There was a problem hiding this comment.
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.
| 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=".") |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 5 potential issues.
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 |
There was a problem hiding this comment.
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.
Reviewed by Cursor Bugbot for commit 3a56b9e. Configure here.
| "rw" if dest == container_cwd else "ro", | ||
| ], | ||
| } | ||
| ) |
There was a problem hiding this comment.
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)
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() |
There was a problem hiding this comment.
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.
Reviewed by Cursor Bugbot for commit 3a56b9e. Configure here.
| stdin=subprocess.DEVNULL, | ||
| stdout=subprocess.DEVNULL, | ||
| stderr=stderr_file, | ||
| ) |
There was a problem hiding this comment.
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)
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 |
There was a problem hiding this comment.
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.
Reviewed by Cursor Bugbot for commit 3a56b9e. Configure here.


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
Additional information