Skip to content

Ray Sandboxing with gVisor (experimental) - #64964

Merged
pcmoritz merged 59 commits into
ray-project:masterfrom
andrewsykim:ray-sandboxing-lib
Aug 11, 2026
Merged

pcmoritz merged 59 commits into
ray-project:masterfrom
andrewsykim:ray-sandboxing-lib

Conversation

@andrewsykim

@andrewsykim andrewsykim commented Jul 23, 2026 •

Copy link
Copy Markdown
Member

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.

@pcmoritz

pcmoritz commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Thanks a lot for putting this together it looks great as a first cut! I'm curious, in the K8s setups you are aware of, would the pods have permissions to create pods (that seems like the main prerequisite of this PR).

@andrewsykim

Copy link
Copy Markdown
Member Author

yes, that's correct. The user needs to grant the service account mounted to the Pod access to create Pods. It'll be up to users to lock down the access to specific namespaces where they expect sandboxes to run.

@andrewsykim

Copy link
Copy Markdown
Member Author

I updated this POC to also include gVisor as a sandbox runtime. When using gVisor, Ray will invoke runsc (OCI runtime from gVisor) to start containers inside the Ray node.

@andrewsykim andrewsykim changed the title [POC][WIP] Ray Sandbox Library [POC][WIP] Ray Sandboxing with gVisor Jul 28, 2026
if self._runsc_path_override is None and not shutil.which(runsc_path):
raise SandboxCreationError(
f"gVisor executable '{runsc_path}' not found in PATH. "
"Please install gVisor (runsc) on the node."

@pcmoritz pcmoritz Aug 1, 2026 •

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.

While trying the PR out, I ran into this. I think instead of saying "on the node" here, it would be better to say "on the container", since it is far far likely that Ray runs in a container (or you can say "on the container or node").

Are there any plans to get runsc into the official ubuntu / debian archives? That would make it much less of a hassle to install and make it more likely for people to adopt it.

Also, after installing runsc, I ran into gVisor container failed to start: running container: creating container: creating container root directory "/var/run/runsc": mkdir /var/run/runsc: permission denied

In containers, it seems quite likely that /var/run is not writable, maybe we can set a configuration option to use a different directory like /tmp?

@pcmoritz pcmoritz Aug 1, 2026 •

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.

If I add run_args.extend(["--root", "/tmp/runsc"]) to the run args, I can work around this error (and --root also needs to be passed in when a command is executed)

@pcmoritz

pcmoritz commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

This is the patch I ended up with to get it working in the container:

--- a/python/ray/experimental/sandbox/backend/gvisor.py
+++ b/python/ray/experimental/sandbox/backend/gvisor.py
@@ -23,6 +23,10 @@
 
 logger = logging.getLogger(__name__)
 
+# 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"
+
 
 def _call_actor(func, *args, **kwargs):
     try:
@@ -78,9 +82,7 @@
                 cpu=config.cpu,
                 memory=config.memory,
             )
-            run_args = [runsc_path]
-            if config.rootless:
-                run_args.append("--rootless")
+            run_args = self._runsc_base_args(runsc_path, config)
             if config.network:
                 run_args.extend(["--network", config.network])
             run_args.extend(["run", "--bundle", root_dir, sandbox_id])
@@ -117,9 +119,7 @@
             proc = meta.get("proc")
 
             if self._runsc_path_override is None:
-                kill_args = [runsc_path]
-                if config.rootless:
-                    kill_args.append("--rootless")
+                kill_args = self._runsc_base_args(runsc_path, config)
                 kill_args.extend(["kill", sandbox_id, "SIGKILL"])
                 subprocess.run(kill_args, capture_output=True)
 
@@ -130,9 +130,7 @@
                     except subprocess.TimeoutExpired:
                         proc.kill()
 
-                del_args = [runsc_path]
-                if config.rootless:
-                    del_args.append("--rootless")
+                del_args = self._runsc_base_args(runsc_path, config)
                 del_args.extend(["delete", sandbox_id])
                 subprocess.run(del_args, capture_output=True)
 
@@ -203,9 +201,7 @@
 
         wrapped_cmd = f"({cmd_str}) > '{container_out}' 2> '{container_err}'"
 
-        runsc_args = [runsc_path]
-        if config.rootless:
-            runsc_args.append("--rootless")
+        runsc_args = self._runsc_base_args(runsc_path, config)
         runsc_args.extend(["exec", "-cwd", raw_cwd])
         if env:
             for k, v in env.items():
@@ -290,6 +286,14 @@
             return SandboxStatus.RUNNING
         return SandboxStatus.TERMINATED
 
+    def _runsc_base_args(self, runsc_path: str, config: SandboxConfig) -> List[str]:
+        """Build the runsc global flags shared by run/exec/kill/delete."""
+        args = [runsc_path]
+        if config.rootless:
+            args.append("--rootless")
+        args.extend(["--root", _RUNSC_ROOT])
+        return args
+
     def _resolve_path(self, root_dir: str, relative_or_abs_path: str) -> str:
         clean_path = relative_or_abs_path.lstrip("/")
         return os.path.join(root_dir, clean_path)

Comment on lines +283 to +285
def _resolve_path(self, root_dir: str, relative_or_abs_path: str) -> str:
clean_path = relative_or_abs_path.lstrip("/")
return os.path.join(root_dir, clean_path)

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.

i assume this stripping of / is to restrict host access, then someone could do ../../<path> to gain access to the host FS?

are we going through runsc for file access?

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.

are we going through runsc for file access?

yes



def create(
image: str = "python:3.10-slim",

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.

We should remove the default here and anywhere else -- otherwise we will need to continuously upgrade it when new versions get released (3.10 is very old and any version we put as a default will get outdated) and that's not ok behavior for users. Instead it is better to have it in the docs / example to make it easy to get started.

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.

yup noted, I will remove this, the image is not actually used anywhere in the code yet anyways

self.delete()


class SandboxHandle:

@pcmoritz pcmoritz Aug 4, 2026 •

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.

I'm skeptical that trying to wrap this in SandboxHandle is the right thing to do -- it makes it much harder to orchestrate multiple sandboxes -- most of the calls are wrapped in ray.get so they are blocking. So the only way to use multiple of them is via the async methods and you can't do that in a sync context / through the Ray API in an idiomatic Ray program.

("/usr", "/usr"),
("/lib", "/lib"),
("/lib64", "/lib64"),
("/home/ray/anaconda3/bin", "/home/ray/anaconda3/bin"),

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.

@pcmoritz looking for your input here on how to handle default bindings (read only) when images are not provided.

It seems kind of hacky to include something like /home/ray/anaconda3/bin, but if you look at the default Ray images, this is where the Python binaries live. If we don't set this, then there's no Python executable available in the image unless a user creates a custom image where Python executable is in one of the default binds (/bin, /usr, /lib/, etc)

@pcmoritz pcmoritz Aug 6, 2026 •

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.

The most important settings is the setting where the image is provided, and in that case by default we should not bind mount anything or set additional env variables, just what is in the image (and make it possible for the user to add bind mounts or environment variables via the config options).

If somebody really wants to run without the image, I think by default we should just not bind mount anything or set any env variables by default and let the user configure it. That is both the safest default (what would be expected from a "sandbox") and also doesn't require us to hardcode or assume anything about the file system layout of the outer layer. But this scenario is far less important than the image case for the RL use cases we are targeting -- almost anything will run with container images.

The second case is kind of like https://github.com/containers/bubblewrap and I think people like the bubblewrap defaults. Now there is the additional complication that this might differ from the gvisor defaults -- if that's the case, we could always require an image and only allow running without an image if the gvisor configs are explicitly set? I do want to avoid (a) having ad hoc defaults like anaconda hard coded in the code and (b) having defaults that are unsafe like exposing the whole host filesystem -- we should only do unsafe things if the user explicitly asks us to do them.

Let me know what you think / if you think we should do something different :)

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.

I am leaning towards requiring an image and not doing any default bind mounts, except for the user specified working dir. I think this is significantly simpler for now and easier to reason about whether something is readonly or not. We may get users asking about sandboxes without images but we can revisit if we get user feedback, we know for sure that useres will want to use images

@andrewsykim andrewsykim changed the title [POC][WIP] Ray Sandboxing with gVisor Ray Sandboxing with gVisor Aug 7, 2026
@andrewsykim
andrewsykim marked this pull request as ready for review August 7, 2026 18:24
@andrewsykim
andrewsykim requested a review from a team as a code owner August 7, 2026 18:24

@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 new experimental sandboxing feature for Ray using gVisor (runsc), allowing isolated execution of commands inside container environments. It includes an OCI image puller and extractor, a gVisor backend, a Ray actor wrapper, and comprehensive unit tests. The review feedback highlights several critical issues: a path traversal vulnerability on Windows due to platform-dependent path splitting; potential Out-Of-Memory (OOM) crashes when loading large container images and layers entirely into memory; a potential deadlock and resource leaks in the sandbox creation process; and an unimplemented ttl_seconds cleanup mechanism.

Comment on lines +138 to +140
# Prevent path traversal
if ".." in name.split(os.sep) or name.startswith(os.sep):
continue

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.

security-critical critical

The path traversal check splits the path using os.sep. On Windows or in environments with mixed separators, os.sep is \\ while tar files always use / as the separator. This allows malicious tar files to bypass the check and perform path traversal attacks. Normalize the separators to / and split on / to ensure platform-independent security.

Suggested change
# Prevent path traversal
if ".." in name.split(os.sep) or name.startswith(os.sep):
continue
# Prevent path traversal
normalized_name = name.replace("\\", "/")
parts = normalized_name.split("/")
if ".." in parts or normalized_name.startswith("/"):
continue

Comment on lines +132 to +134
def extract_tar_layer(tar_bytes: bytes, dest_dir: str) -> None:
"""Extract a tar archive layer onto dest_dir with OCI whiteout handling."""
with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:*") as tar:

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

extract_tar_layer currently accepts tar_bytes: bytes and loads the entire archive into memory. For large container images, this can easily cause Out-Of-Memory (OOM) crashes. Refactor extract_tar_layer to accept either bytes or a file path (str), allowing us to process large tar files directly from disk without loading them into memory.

def extract_tar_layer(tar_source: Union[bytes, str], dest_dir: str) -> None:
    """Extract a tar archive layer onto dest_dir with OCI whiteout handling."""
    tar_context = (
        tarfile.open(fileobj=io.BytesIO(tar_source), mode="r:*")
        if isinstance(tar_source, bytes)
        else tarfile.open(name=tar_source, mode="r:*")
    )
    with tar_context as tar:

Comment on lines +278 to +296
if os.path.isfile(image):
try:
with open(image, "rb") as f:
extract_tar_layer(f.read(), tmp_extract_dir)
except Exception as err:
shutil.rmtree(tmp_extract_dir, ignore_errors=True)
raise SandboxCreationError(
f"Failed to extract local image archive '{image}': {err}"
) from err
elif os.path.isfile(tar_path):
try:
with open(tar_path, "rb") as f:
extract_tar_layer(f.read(), tmp_extract_dir)
except Exception as err:
shutil.rmtree(tmp_extract_dir, ignore_errors=True)
raise SandboxCreationError(
f"Failed to extract cached image archive '{tar_path}': {err}"
) from err
else:

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

Avoid reading the entire local or cached tar archive into memory. Instead, pass the file path directly to the refactored extract_tar_layer function to stream the extraction from disk.

            if os.path.isfile(image):
                try:
                    extract_tar_layer(image, tmp_extract_dir)
                except Exception as err:
                    shutil.rmtree(tmp_extract_dir, ignore_errors=True)
                    raise SandboxCreationError(
                        f"Failed to extract local image archive '{image}': {err}"
                    ) from err
            elif os.path.isfile(tar_path):
                try:
                    extract_tar_layer(tar_path, tmp_extract_dir)
                except Exception as err:
                    shutil.rmtree(tmp_extract_dir, ignore_errors=True)
                    raise SandboxCreationError(
                        f"Failed to extract cached image archive '{tar_path}': {err}"
                    ) from err

Comment on lines +358 to +367
for layer in layers:
digest = layer["digest"]
blob_url = f"https://{registry}/v2/{repo}/blobs/{digest}"
blob_req = urllib.request.Request(blob_url, headers=headers)
with urllib.request.urlopen(
blob_req, timeout=timeout_seconds
) as blob_resp:
layer_bytes = blob_resp.read()

extract_tar_layer(layer_bytes, tmp_extract_dir)

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

Avoid loading the entire remote layer blob into memory via blob_resp.read(). Stream the response directly to a temporary file on disk and extract it from there to prevent OOM crashes during image pulling.

Suggested change
for layer in layers:
digest = layer["digest"]
blob_url = f"https://{registry}/v2/{repo}/blobs/{digest}"
blob_req = urllib.request.Request(blob_url, headers=headers)
with urllib.request.urlopen(
blob_req, timeout=timeout_seconds
) as blob_resp:
layer_bytes = blob_resp.read()
extract_tar_layer(layer_bytes, tmp_extract_dir)
for layer in layers:
digest = layer["digest"]
blob_url = f"https://{registry}/v2/{repo}/blobs/{digest}"
blob_req = urllib.request.Request(blob_url, headers=headers)
temp_layer_path = os.path.join(images_dir, f"{safe_name}.layer.{uuid.uuid4().hex}.tmp")
try:
with urllib.request.urlopen(blob_req, timeout=timeout_seconds) as blob_resp, open(temp_layer_path, "wb") as f_out:
shutil.copyfileobj(blob_resp, f_out)
extract_tar_layer(temp_layer_path, tmp_extract_dir)
finally:
if os.path.exists(temp_layer_path):
try:
os.remove(temp_layer_path)
except OSError:
pass

Comment on lines +42 to +133
def create_sandbox(self, config: SandboxConfig) -> str:
"""Create a local directory structure and initialize a gVisor sandbox instance."""
if not shutil.which("runsc"):
raise SandboxCreationError(
"gVisor executable 'runsc' not found in PATH. "
"Please install gVisor (runsc) on the node."
)

sandbox_uuid = uuid.uuid4().hex[:12]
sandbox_id = f"ray-sandbox-{sandbox_uuid}"
root_dir = os.path.join(_RAY_SANDBOX_DIR, sandbox_id)

try:
os.makedirs(root_dir, mode=0o777, exist_ok=True)
work_dir_path = os.path.abspath(
os.path.join(root_dir, config.work_dir.lstrip("/"))
)
if not (
work_dir_path == os.path.abspath(root_dir)
or work_dir_path.startswith(os.path.abspath(root_dir) + os.sep)
):
raise SandboxCreationError(
f"Invalid work_dir '{config.work_dir}': Path traversal detected."
)
os.makedirs(work_dir_path, mode=0o777, exist_ok=True)
except Exception as err:
raise SandboxCreationError(
f"Failed to initialize local sandbox directory '{root_dir}': {err}"
) from err

# Prepare OCI bundle config for long-running container process
self._prepare_oci_bundle(
root_dir=root_dir,
work_dir_path=work_dir_path,
container_cwd=config.work_dir,
image=config.image,
env_dict=config.env,
cpu=config.cpu,
memory=config.memory,
readonly=config.readonly,
)
run_args = self._runsc_base_args(config)
if config.network:
run_args.extend(["--network", config.network])
overlay_dir = os.path.join(root_dir, "overlay")
os.makedirs(overlay_dir, mode=0o777, exist_ok=True)
run_args.append(f"--overlay2=root:dir={overlay_dir}")
run_args.extend(["run", "--bundle", root_dir, sandbox_id])

proc = subprocess.Popen(
run_args,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
start_time = time.time()
timeout = config.timeout_seconds
state_args = self._runsc_base_args(config) + ["state", sandbox_id]

while True:
if proc.poll() is not None:
_, stderr_str = proc.communicate()
raise SandboxCreationError(
f"gVisor container failed to start: {stderr_str.decode('utf-8', errors='replace')}"
)

res = subprocess.run(state_args, capture_output=True, text=True)
if res.returncode == 0:
try:
state_data = json.loads(res.stdout)
if state_data.get("status") == "running":
break
except Exception:
pass

if time.time() - start_time > timeout:
proc.kill()
proc.communicate()
raise SandboxTimeoutError(
f"gVisor container '{sandbox_id}' failed to reach 'running' state within {timeout} seconds."
)

time.sleep(0.1)

self._sandbox_metadata[sandbox_id] = {
"root_dir": root_dir,
"work_dir": work_dir_path,
"config": config,
"proc": proc,
"status": SandboxStatus.RUNNING,
}
return sandbox_id

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

This method has two major issues:

  1. If an exception or timeout occurs during sandbox creation, the local directory structure, runsc container state, and started processes are leaked on the node.
  2. Running runsc run with stdout=subprocess.PIPE and stderr=subprocess.PIPE without reading from them concurrently can cause a deadlock if the buffer fills up (64KB limit).

Refactor the method to redirect runsc output to a log file (which also aids debugging) and wrap the creation process in a try...except block to clean up all resources on failure.

    def create_sandbox(self, config: SandboxConfig) -> str:
        """Create a local directory structure and initialize a gVisor sandbox instance."""
        if not shutil.which("runsc"):
            raise SandboxCreationError(
                "gVisor executable 'runsc' not found in PATH. "
                "Please install gVisor (runsc) on the node."
            )

        sandbox_uuid = uuid.uuid4().hex[:12]
        sandbox_id = f"ray-sandbox-{sandbox_uuid}"
        root_dir = os.path.join(_RAY_SANDBOX_DIR, sandbox_id)

        try:
            os.makedirs(root_dir, mode=0o777, exist_ok=True)
            work_dir_path = os.path.abspath(
                os.path.join(root_dir, config.work_dir.lstrip("/"))
            )
            if not (
                work_dir_path == os.path.abspath(root_dir)
                or work_dir_path.startswith(os.path.abspath(root_dir) + os.sep)
            ):
                raise SandboxCreationError(
                    f"Invalid work_dir '{config.work_dir}': Path traversal detected."
                )
            os.makedirs(work_dir_path, mode=0o777, exist_ok=True)
        except Exception as err:
            if os.path.exists(root_dir):
                shutil.rmtree(root_dir, ignore_errors=True)
            raise SandboxCreationError(
                f"Failed to initialize local sandbox directory '{root_dir}': {err}"
            ) from err

        proc = None
        try:
            # Prepare OCI bundle config for long-running container process
            self._prepare_oci_bundle(
                root_dir=root_dir,
                work_dir_path=work_dir_path,
                container_cwd=config.work_dir,
                image=config.image,
                env_dict=config.env,
                cpu=config.cpu,
                memory=config.memory,
                readonly=config.readonly,
            )
            run_args = self._runsc_base_args(config)
            if config.network:
                run_args.extend(["--network", config.network])
            overlay_dir = os.path.join(root_dir, "overlay")
            os.makedirs(overlay_dir, mode=0o777, exist_ok=True)
            run_args.append(f"--overlay2=root:dir={overlay_dir}")
            run_args.extend(["run", "--bundle", root_dir, sandbox_id])

            log_file_path = os.path.join(root_dir, "runsc.log")
            with open(log_file_path, "w", encoding="utf-8") as log_file:
                proc = subprocess.Popen(
                    run_args,
                    stdin=subprocess.DEVNULL,
                    stdout=log_file,
                    stderr=log_file,
                )
            start_time = time.time()
            timeout = config.timeout_seconds
            state_args = self._runsc_base_args(config) + ["state", sandbox_id]

            while True:
                if proc.poll() is not None:
                    stderr_str = ""
                    if os.path.exists(log_file_path):
                        try:
                            with open(log_file_path, "r", encoding="utf-8", errors="replace") as f:
                                stderr_str = f.read()
                        except Exception:
                            pass
                    raise SandboxCreationError(
                        f"gVisor container failed to start: {stderr_str}"
                    )

                res = subprocess.run(state_args, capture_output=True, text=True)
                if res.returncode == 0:
                    try:
                        state_data = json.loads(res.stdout)
                        if state_data.get("status") == "running":
                            break
                    except Exception:
                        pass

                if time.time() - start_time > timeout:
                    raise SandboxTimeoutError(
                        f"gVisor container '{sandbox_id}' failed to reach 'running' state within {timeout} seconds."
                    )

                time.sleep(0.1)

            self._sandbox_metadata[sandbox_id] = {
                "root_dir": root_dir,
                "work_dir": work_dir_path,
                "config": config,
                "proc": proc,
                "status": SandboxStatus.RUNNING,
            }
            return sandbox_id

        except Exception as err:
            # Cleanup on failure
            kill_args = self._runsc_base_args(config)
            kill_args.extend(["kill", sandbox_id, "SIGKILL"])
            subprocess.run(kill_args, capture_output=True)

            if proc:
                if proc.poll() is None:
                    proc.terminate()
                    try:
                        proc.communicate(timeout=2)
                    except subprocess.TimeoutExpired:
                        proc.kill()

            del_args = self._runsc_base_args(config)
            del_args.extend(["delete", sandbox_id])
            subprocess.run(del_args, capture_output=True)

            shutil.rmtree(root_dir, ignore_errors=True)
            raise

import urllib.parse
import urllib.request
import uuid
from typing import Dict, Tuple

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

Import Union from typing to support type annotations for the refactored extract_tar_layer function.

Suggested change
from typing import Dict, Tuple
from typing import Dict, Tuple, Union

Comment on lines +77 to +92
self.runtime = SandboxRuntime()
self.instance_id = self.runtime.create(
image=image,
cpu=cpu,
memory=memory,
env=env,
work_dir=work_dir,
ttl_seconds=ttl_seconds,
labels=labels,
timeout_seconds=timeout_seconds,
rootless=rootless,
network=network,
resources=resources,
readonly=readonly,
**kwargs,
)

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

ttl_seconds is defined in the configuration but is currently completely ignored and unimplemented. Implement a simple background timer to automatically clean up and delete the sandbox when ttl_seconds is reached.

        self.runtime = SandboxRuntime()
        self.instance_id = self.runtime.create(
            image=image,
            cpu=cpu,
            memory=memory,
            env=env,
            work_dir=work_dir,
            ttl_seconds=ttl_seconds,
            labels=labels,
            timeout_seconds=timeout_seconds,
            rootless=rootless,
            network=network,
            resources=resources,
            readonly=readonly,
            **kwargs,
        )

        if ttl_seconds is not None and ttl_seconds > 0:
            import threading
            self._cleanup_timer = threading.Timer(ttl_seconds, self.delete)
            self._cleanup_timer.daemon = True
            self._cleanup_timer.start()

os.remove(del_path)
except OSError:
pass
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Whiteout deletion escapes extract dir

High Severity

OCI whiteout handling derives del_name from .wh. prefixes without rejecting . / .. or verifying del_path stays under dest_dir. A crafted image entry such as .wh... makes del_name .., so shutil.rmtree can delete directories outside the extract root, including sibling image caches under /tmp/ray/sandbox/images.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 8136f7d. Configure here.

@andrewsykim

andrewsykim commented Aug 7, 2026 •

Copy link
Copy Markdown
Member Author

I'm still working through various details, but the PR now reflects what is in the REP and is ready for a first full review. I will address Cursor review shortly.

I used these two scripts to test the changes on Kubernetes and locally:

cpu: float = 0.0,
memory: Union[str, int, float] = 0,
env: Optional[Dict[str, str]] = None,
work_dir: str = "/workspace",

@pcmoritz pcmoritz Aug 7, 2026 •

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.

Let's call this workdir everywhere (since both docker and modal call it that), make it optional, and if it is not set, use the container image WORKDIR by default.

stdout: Standard output text string.
stderr: Standard error text string.
duration_seconds: Command execution time in seconds.
truncated: True if stdout or stderr was truncated.

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.

This seems unused, let's remove it?

@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Aug 7, 2026
@andrewsykim
andrewsykim requested a review from a team as a code owner August 8, 2026 01:52
@andrewsykim andrewsykim changed the title Ray Sandboxing with gVisor Ray Sandboxing with gVisor (experimental) Aug 8, 2026
@andrewsykim

andrewsykim commented Aug 10, 2026 •

Copy link
Copy Markdown
Member Author

Looks like the sandbox tests are now running, thanks @elliot-barn for the pointer:

  | [2026-08-10T20:28:42Z] python/ray/experimental/sandbox/tests/test_image_manager.py::test_image_manager_init PASSED [ 11%]
  | [2026-08-10T20:28:42Z] python/ray/experimental/sandbox/tests/test_image_manager.py::test_get_default_oci_spec FAILED [ 22%]
  | [2026-08-10T20:28:42Z] python/ray/experimental/sandbox/tests/test_image_manager.py::test_image_manager_pull_and_paths PASSED [ 33%]
  | [2026-08-10T20:28:42Z] python/ray/experimental/sandbox/tests/test_image_manager.py::test_image_manager_config_parsing PASSED [ 44%]
  | [2026-08-10T20:28:42Z] python/ray/experimental/sandbox/tests/test_image_manager.py::test_image_manager_create_oci_spec FAILED [ 55%]
  | [2026-08-10T20:28:42Z] python/ray/experimental/sandbox/tests/test_image_manager.py::test_image_manager_prepare_oci_bundle FAILED [ 66%]
  | [2026-08-10T20:28:42Z] python/ray/experimental/sandbox/tests/test_image_manager.py::test_sandbox_runtime_image_manager_integration PASSED [ 77%]
  | [2026-08-10T20:28:42Z] python/ray/experimental/sandbox/tests/test_image_manager.py::test_base_image_manager_abstract PASSED [ 88%]
  | [2026-08-10T20:28:42Z] python/ray/experimental/sandbox/tests/test_image_manager.py::test_custom_image_manager_subclass PASSED [100%]


I'm looking into the failing test

if platform.machine().lower() in ("aarch64", "arm64")
else "x86_64"
)
url = f"https://storage.googleapis.com/gvisor/releases/release/latest/{arch}/runsc"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Do you always need latest or can we pin this

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.

let's do latest for now, I will follow-up and pin this version based on recommendation from gVisor maintainers

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

sounds good to me

pytest.skip("Sandbox tests are only run when TEST_SANDBOX=1")


@pytest.fixture(scope="session", autouse=True)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

lets move the install to a script inside of ci/env/install-runsc.sh and call the script here

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.

I will track this as a follow-up item

…ps -- this is required for runsc to work in buildkite's docker based runtime. This is not required in k8s-based environments

Signed-off-by: Andrew Sy Kim <[email protected]>
@pcmoritz

Copy link
Copy Markdown
Contributor

Nice, looks like the sandbox tests are passing now, great work @andrewsykim and @elliot-barn :)

@andrewsykim

andrewsykim commented Aug 11, 2026 •

Copy link
Copy Markdown
Member Author

Not sure why yet, but I was seeing this cgroup error even though we are using priviledged containers in buildkite:

ray.experimental.sandbox.exceptions.SandboxCreationError: gVisor container failed to start: running container: creating container: cannot set up cgroup for root: configuring cgroup: write /sys/fs/cgroup/cgroup.subtree_control: device or resource busy

For now I added a test only config to pass in --ignore-cgroups to runsc. I will investigate this further in a follow-up PR but the tests are passing now

@andrewsykim
andrewsykim enabled auto-merge (squash) August 11, 2026 02:11
@andrewsykim
andrewsykim disabled auto-merge August 11, 2026 02:12
@pcmoritz
pcmoritz merged commit 3c9e718 into ray-project:master Aug 11, 2026
6 checks passed
elliot-barn pushed a commit that referenced this pull request Aug 11, 2026
…) (#65397)

## 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.

---------

> Thank you for contributing to Ray! 🚀
> Please review the [Ray Contribution
Guide](https://docs.ray.io/en/master/ray-contribute/getting-involved.html)
before opening a pull request.

> ⚠️ Remove these instructions before submitting your PR.

> 💡 Tip: Mark as draft if you want early feedback, or ready for review
when it's complete.

## Description
> Briefly describe what this PR accomplishes and why it's needed.

## 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]>
Co-authored-by: Andrew Sy Kim <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
## 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 ray-project#1234", "Closes ray-project#1234", or "Related to
ray-project#1234".

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

---------

Signed-off-by: Andrew Sy Kim <[email protected]>
Signed-off-by: 400Ping <[email protected]>
pcmoritz pushed a commit that referenced this pull request Aug 20, 2026
…ox (#65570)

## Description

`ray.experimental.sandbox` cannot run standard Docker-built images
without reaching for the private `_oci_spec_transform_fn` hook and
client-side workarounds. We hit all of these while integrating Ray
Sandbox with the [Harbor](https://github.com/harbor-framework/harbor)
eval framework (see the workarounds carried in
harbor-framework/harbor#2725), and the follow-up items while testing
this PR end-to-end on a live Ray cluster with real gVisor.

### Capabilities

- **`SandboxConfig.capabilities`** (plumbed through `create()`, the
`Sandbox` actor, `SandboxRuntime.create`, and the gVisor backend): None
keeps the runtime default; otherwise the bounding/effective/permitted
sets are written exactly, so `[]` runs with no capabilities at all
(inheritable and ambient untouched, matching modern Docker, which
stopped setting inheritable for CVE-2022-24769). A new
`DOCKER_DEFAULT_CAPABILITIES` constant ([Docker's documented default
set](https://docs.docker.com/engine/containers/run/#runtime-privilege-and-linux-capabilities))
gives Docker parity in one line: the runtime's default (whatever `runsc
spec` emits) grants only three capabilities, and standard images break
confusingly without more — `apt-get` needs `CAP_SETUID`/`CAP_SETGID` for
its `_apt` sub-processes, `tar` extracting as root fatally fails
restoring archived uid/gids (e.g. `1000`) without `CAP_CHOWN`.

### Networking and DNS

- **`network="public"`** — the recommended internet-access mode: host
egress (`--network=host` under the hood) with a **synthetic
`/etc/resolv.conf`** generated from `dns` (default `8.8.8.8`,
`1.1.1.1`). Nothing about the host resolver is inherited, so the config
stays portable and doesn't leak host search domains or internal resolver
addresses (a cluster node's resolv.conf typically carries internal
Kubernetes search domains, the cluster DNS VIP, and `ndots:5`).
- **`network="host"`** stays the explicit power mode — full host network
identity (including internal networks reachable from the node) with the
host's own resolv.conf mounted read-only; `dns=` overrides it with a
generated file. Keeping the modes separate lets the docs state that
difference plainly. `"none"` remains the default.
- **`dns=`** mirrors `docker --dns` and is the escape hatch for
locked-down VPCs that block public DNS; it's rejected for modes that
mount no resolv.conf. Host-side networking also drops the spec's empty
network namespace, which previously left the sandbox loopback-only
despite `--network=host`.
- **`network="sandbox"` with `rootless=True` is rejected at config
time**: runsc refuses the combination at container start, after the
image pull, with an error naming a flag the user never set.

### Working directory and writability

- **Writability is now fully explicit** — determined by the two
parameters the user actually set, with the image's `WORKDIR` inherited
for the *process cwd only*:

  | `readonly` | `workdir` | writable | cwd |
  |---|---|---|---|
| `True` *(default)* | `None` *(default)* | nothing on the rootfs (safe
default; standard tmpfs mounts like `/tmp` remain writable) | image
`WORKDIR`, else `/` |
  | `True` | `/data` | only `/data` (host-backed scratch) | `/data` |
| `False` | any | everything (per-sandbox overlay; image content stays
visible, nothing shadowed) | explicit workdir, else image `WORKDIR` |

Previously the backend defaulted `workdir` to the image's `WORKDIR` (or
`/`) and scratch-mounted there, so what was writable depended on image
metadata invisible in the config. An inherited `WORKDIR` is never
silently made writable now. This made the interim `mount_workdir` knob
redundant, so it's removed; the backend also no longer mutates
`config.workdir` (the resolved cwd lives in sandbox metadata), and
inherited image `WORKDIR` values are no longer used in host path joins,
removing that traversal surface.

### TTL

- **`ttl_seconds` now defaults to `None`** (no TTL) everywhere: the old
1h default was wall-clock from creation, not idle time, so
actively-running sandboxes were deleted mid-work — a silent,
hard-to-attribute failure in long agent runs. Opt-in destruction is the
safer default.
- **`SandboxRuntime` now actually enforces a set TTL** (daemon timer,
canceled on delete); previously the parameter was a documented no-op
below the actor layer, and the `Sandbox` actor's duplicate timer is
dropped in favor of the runtime's.

### Shell for string commands

- String commands ran under `/bin/sh` — `dash` on Debian-family images —
while agent-generated commands overwhelmingly assume bash, failing
confusingly on `[[ ]]`/`pipefail`/arrays. **`SandboxConfig.shell`** now
defaults to `"/bin/bash"` outright (no auto-detection — deterministic
per review), with a per-command `shell=` override on `exec()`. Images
without bash set `shell="/bin/sh"` explicitly, as the busybox-based
tests now do; list commands still bypass the shell.

### Robustness

- `SandboxRuntime.create()` forwards `mount_workdir` into the config (it
was silently dropped — caught by live testing; a new runtime-layer test
suite pins config fields actually reaching the backend, the gap that let
it ship green).
- Caller-supplied `base_spec`s with null capability sets or non-dict
namespace entries no longer raise; malformed namespace entries are kept
for runsc to reject with its own error.
- `SandboxConfig` validates the network mode against `("none", "public",
"host", "sandbox")`.

Defaults are behavior-preserving except where called out (TTL, and
mount_workdir under `readonly=False`); the API is alpha.

## Related issues

Related to #64964 (Ray Sandboxing with gVisor). Enables removing the
OCI-spec transform, DNS seeding, and `tar --no-same-owner` workarounds
in harbor-framework/harbor#2725 / harbor-framework/harbor#2785.

## Additional information

Usage:

```python
from ray.experimental import sandbox
from ray.experimental.sandbox import DOCKER_DEFAULT_CAPABILITIES

sb = sandbox.create(
    image="ubuntu:24.04",
    network="public",
    capabilities=DOCKER_DEFAULT_CAPABILITIES,
    readonly=False,
)
# apt-get / tar / DNS / bash / image WORKDIR all behave as under Docker,
# without inheriting the host's resolver configuration.
```

Testing:
- Unit tests run without runsc or a cluster: spec construction against
`base_spec` with a stub image manager, config validation, resolv.conf
generation policy at the `prepare_oci_bundle` layer, and a new
`SandboxRuntime`-layer suite (fake backend) covering field forwarding
and TTL enforcement.
- Full `TEST_SANDBOX=1` suite with real gVisor/runsc on Linux: 64 tests
pass, including the shell-detection and rootless-rejection paths.
- Docs: new "Networking and DNS" section with the mode table and
security property of each mode, the recommended internet-access example,
the `dns=` escape hatch, and an updated OCI-transform section (its
example used the now-rejected `network="sandbox"` default combination
and hand-mounted resolv.conf).

This is the first of two changes for running Harbor evals on Ray
Sandbox; a follow-up adds an HTTP API service so sandboxes can be
consumed as a standalone service.

---------

Signed-off-by: xyuzh <[email protected]>
dstrodtman added a commit that referenced this pull request Aug 20, 2026
## Description

Style-only follow-up on the "Networking and DNS" section added in
#65570. No technical claim changes, and the section's structure and
content are the author's; this is polish against the [Ray documentation
style
guide](https://docs.ray.io/en/master/ray-contribute/writing-style.html).

I was asked for a docs review on #65570 but it merged before I finished,
so the feedback is landing here instead of as suggestions on a merged
PR.

### What changed

The one pattern worth naming, because it repeats: the new prose was
hard-wrapped at roughly 72 columns while the rest of the page uses one
source line per paragraph. The guide asks for [soft-wrapped
prose](https://docs.ray.io/en/master/ray-contribute/writing-style.html#soft-wrap-prose)
so diffs stay legible.

Beyond that:

* **Sentence splits** where an em dash, a semicolon, or a mid-sentence
colon was joining clauses. The guide asks us to [restructure rather than
punctuate](https://docs.ray.io/en/master/ray-contribute/writing-style.html#sentence-structure).
After this the whole page is free of Unicode dashes.
* **`### DNS in locked-down networks`** instead of a bold paragraph
lead-in. The guide reserves
[bold](https://docs.ray.io/en/master/ray-contribute/writing-style.html#bold-and-italics)
for UI elements, admonition lead-ins, and definition lists. As a real
heading it also picks up a TOC entry and a linkable anchor. A `note`
admonition would work too if you'd rather it read as an aside.
* **Dropped `— **recommended for internet access**`** from the `public`
row's first cell. That's bold for emphasis, and the prose above the
table already makes the recommendation.
* **Parallel structure in the `_oci_spec_transform_fn` list.** The
second bullet had lost the `**Term**: explanation` shape of the first
and grown to four sentences, so the migration guidance moves into prose
after the list. This also drops "no longer need this hook," which
orients a reader who knew the previous behavior rather than one arriving
fresh.
* **A complete lead-in** above the `network="public"` example, which was
a noun phrase with a colon on the end.
* **Direct advice and active voice**: "Prefer `public` for untrusted
code" to "Use `public`", and "Anything beyond that can be configured" to
"Configure anything beyond that."

### One question I couldn't answer myself

The `sandbox` row's "Network access" cell reads "gVisor netstack," which
says how the mode is implemented but not what the reader gets. Does
`network="sandbox"` provide egress, or is it isolated like `none`?
That's what someone scanning the table to pick a mode is asking, and
it's the one cell that doesn't answer it. I left the cell alone rather
than guess. Happy to add a few words here if you tell me which it is.

## Related issues

Follows #65570. Related to #64964.

## Additional information

`DOCKER_DEFAULT_CAPABILITIES` is in the sandbox package's `__all__`, so
naming it in the prose above the example is safe. `myst_heading_anchors
= 4`, so the new H3 and the existing
`#pass-custom-oci-configurations-to-gvisor` link both resolve.

Note that no pre-commit hook covers Markdown under `doc/source/`, and
Vale is scoped to the Ray Data docs and the example gallery, so nothing
lints this file automatically. Verified by hand: heading depth tops out
at H3, no stacked headings, and both in-page anchors match real
headings.

Signed-off-by: Douglas Strodtman <[email protected]>
dstrodtman added a commit that referenced this pull request Sep 2, 2026
…g section (#65627) (#65734)

Cherry-picks the Ray Sandboxes networking-section style pass onto
`releases/2.58.0`.

Ray Sandboxing (gVisor) ships in 2.58.0 (#64964, #65570, and the initial
docs #65503, all already on the release branch). This editorial pass on
the networking and DNS section landed on master after the branch cut, so
the versioned 2.58.0 docs are missing it. The change is prose-only: it
tightens the network-mode table, splits the DNS guidance into its own
subsection, and removes recommendation hedging. No behavior or API
content changes.

Cherry-pick of #65627.

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
rueian pushed a commit that referenced this pull request Sep 28, 2026
## Description
Added install runsc as standalone CI script.

### Context for Why this was done ?
<img width="1594" height="782" alt="image"
src="https://github.com/user-attachments/assets/474c40d9-1323-4dca-94c6-7ce232535c60"
/>



## Related issues
> "Related to  #65352 #64964 ".

---------

Signed-off-by: Limark Dcunha <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…ox (ray-project#65570)

## Description

`ray.experimental.sandbox` cannot run standard Docker-built images
without reaching for the private `_oci_spec_transform_fn` hook and
client-side workarounds. We hit all of these while integrating Ray
Sandbox with the [Harbor](https://github.com/harbor-framework/harbor)
eval framework (see the workarounds carried in
harbor-framework/harbor#2725), and the follow-up items while testing
this PR end-to-end on a live Ray cluster with real gVisor.

### Capabilities

- **`SandboxConfig.capabilities`** (plumbed through `create()`, the
`Sandbox` actor, `SandboxRuntime.create`, and the gVisor backend): None
keeps the runtime default; otherwise the bounding/effective/permitted
sets are written exactly, so `[]` runs with no capabilities at all
(inheritable and ambient untouched, matching modern Docker, which
stopped setting inheritable for CVE-2022-24769). A new
`DOCKER_DEFAULT_CAPABILITIES` constant ([Docker's documented default
set](https://docs.docker.com/engine/containers/run/#runtime-privilege-and-linux-capabilities))
gives Docker parity in one line: the runtime's default (whatever `runsc
spec` emits) grants only three capabilities, and standard images break
confusingly without more — `apt-get` needs `CAP_SETUID`/`CAP_SETGID` for
its `_apt` sub-processes, `tar` extracting as root fatally fails
restoring archived uid/gids (e.g. `1000`) without `CAP_CHOWN`.

### Networking and DNS

- **`network="public"`** — the recommended internet-access mode: host
egress (`--network=host` under the hood) with a **synthetic
`/etc/resolv.conf`** generated from `dns` (default `8.8.8.8`,
`1.1.1.1`). Nothing about the host resolver is inherited, so the config
stays portable and doesn't leak host search domains or internal resolver
addresses (a cluster node's resolv.conf typically carries internal
Kubernetes search domains, the cluster DNS VIP, and `ndots:5`).
- **`network="host"`** stays the explicit power mode — full host network
identity (including internal networks reachable from the node) with the
host's own resolv.conf mounted read-only; `dns=` overrides it with a
generated file. Keeping the modes separate lets the docs state that
difference plainly. `"none"` remains the default.
- **`dns=`** mirrors `docker --dns` and is the escape hatch for
locked-down VPCs that block public DNS; it's rejected for modes that
mount no resolv.conf. Host-side networking also drops the spec's empty
network namespace, which previously left the sandbox loopback-only
despite `--network=host`.
- **`network="sandbox"` with `rootless=True` is rejected at config
time**: runsc refuses the combination at container start, after the
image pull, with an error naming a flag the user never set.

### Working directory and writability

- **Writability is now fully explicit** — determined by the two
parameters the user actually set, with the image's `WORKDIR` inherited
for the *process cwd only*:

  | `readonly` | `workdir` | writable | cwd |
  |---|---|---|---|
| `True` *(default)* | `None` *(default)* | nothing on the rootfs (safe
default; standard tmpfs mounts like `/tmp` remain writable) | image
`WORKDIR`, else `/` |
  | `True` | `/data` | only `/data` (host-backed scratch) | `/data` |
| `False` | any | everything (per-sandbox overlay; image content stays
visible, nothing shadowed) | explicit workdir, else image `WORKDIR` |

Previously the backend defaulted `workdir` to the image's `WORKDIR` (or
`/`) and scratch-mounted there, so what was writable depended on image
metadata invisible in the config. An inherited `WORKDIR` is never
silently made writable now. This made the interim `mount_workdir` knob
redundant, so it's removed; the backend also no longer mutates
`config.workdir` (the resolved cwd lives in sandbox metadata), and
inherited image `WORKDIR` values are no longer used in host path joins,
removing that traversal surface.

### TTL

- **`ttl_seconds` now defaults to `None`** (no TTL) everywhere: the old
1h default was wall-clock from creation, not idle time, so
actively-running sandboxes were deleted mid-work — a silent,
hard-to-attribute failure in long agent runs. Opt-in destruction is the
safer default.
- **`SandboxRuntime` now actually enforces a set TTL** (daemon timer,
canceled on delete); previously the parameter was a documented no-op
below the actor layer, and the `Sandbox` actor's duplicate timer is
dropped in favor of the runtime's.

### Shell for string commands

- String commands ran under `/bin/sh` — `dash` on Debian-family images —
while agent-generated commands overwhelmingly assume bash, failing
confusingly on `[[ ]]`/`pipefail`/arrays. **`SandboxConfig.shell`** now
defaults to `"/bin/bash"` outright (no auto-detection — deterministic
per review), with a per-command `shell=` override on `exec()`. Images
without bash set `shell="/bin/sh"` explicitly, as the busybox-based
tests now do; list commands still bypass the shell.

### Robustness

- `SandboxRuntime.create()` forwards `mount_workdir` into the config (it
was silently dropped — caught by live testing; a new runtime-layer test
suite pins config fields actually reaching the backend, the gap that let
it ship green).
- Caller-supplied `base_spec`s with null capability sets or non-dict
namespace entries no longer raise; malformed namespace entries are kept
for runsc to reject with its own error.
- `SandboxConfig` validates the network mode against `("none", "public",
"host", "sandbox")`.

Defaults are behavior-preserving except where called out (TTL, and
mount_workdir under `readonly=False`); the API is alpha.

## Related issues

Related to ray-project#64964 (Ray Sandboxing with gVisor). Enables removing the
OCI-spec transform, DNS seeding, and `tar --no-same-owner` workarounds
in harbor-framework/harbor#2725 / harbor-framework/harbor#2785.

## Additional information

Usage:

```python
from ray.experimental import sandbox
from ray.experimental.sandbox import DOCKER_DEFAULT_CAPABILITIES

sb = sandbox.create(
    image="ubuntu:24.04",
    network="public",
    capabilities=DOCKER_DEFAULT_CAPABILITIES,
    readonly=False,
)
# apt-get / tar / DNS / bash / image WORKDIR all behave as under Docker,
# without inheriting the host's resolver configuration.
```

Testing:
- Unit tests run without runsc or a cluster: spec construction against
`base_spec` with a stub image manager, config validation, resolv.conf
generation policy at the `prepare_oci_bundle` layer, and a new
`SandboxRuntime`-layer suite (fake backend) covering field forwarding
and TTL enforcement.
- Full `TEST_SANDBOX=1` suite with real gVisor/runsc on Linux: 64 tests
pass, including the shell-detection and rootless-rejection paths.
- Docs: new "Networking and DNS" section with the mode table and
security property of each mode, the recommended internet-access example,
the `dns=` escape hatch, and an updated OCI-transform section (its
example used the now-rejected `network="sandbox"` default combination
and hand-mounted resolv.conf).

This is the first of two changes for running Harbor evals on Ray
Sandbox; a follow-up adds an HTTP API service so sandboxes can be
consumed as a standalone service.

---------

Signed-off-by: xyuzh <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…t#65627)

## Description

Style-only follow-up on the "Networking and DNS" section added in
ray-project#65570. No technical claim changes, and the section's structure and
content are the author's; this is polish against the [Ray documentation
style
guide](https://docs.ray.io/en/master/ray-contribute/writing-style.html).

I was asked for a docs review on ray-project#65570 but it merged before I finished,
so the feedback is landing here instead of as suggestions on a merged
PR.

### What changed

The one pattern worth naming, because it repeats: the new prose was
hard-wrapped at roughly 72 columns while the rest of the page uses one
source line per paragraph. The guide asks for [soft-wrapped
prose](https://docs.ray.io/en/master/ray-contribute/writing-style.html#soft-wrap-prose)
so diffs stay legible.

Beyond that:

* **Sentence splits** where an em dash, a semicolon, or a mid-sentence
colon was joining clauses. The guide asks us to [restructure rather than
punctuate](https://docs.ray.io/en/master/ray-contribute/writing-style.html#sentence-structure).
After this the whole page is free of Unicode dashes.
* **`### DNS in locked-down networks`** instead of a bold paragraph
lead-in. The guide reserves
[bold](https://docs.ray.io/en/master/ray-contribute/writing-style.html#bold-and-italics)
for UI elements, admonition lead-ins, and definition lists. As a real
heading it also picks up a TOC entry and a linkable anchor. A `note`
admonition would work too if you'd rather it read as an aside.
* **Dropped `— **recommended for internet access**`** from the `public`
row's first cell. That's bold for emphasis, and the prose above the
table already makes the recommendation.
* **Parallel structure in the `_oci_spec_transform_fn` list.** The
second bullet had lost the `**Term**: explanation` shape of the first
and grown to four sentences, so the migration guidance moves into prose
after the list. This also drops "no longer need this hook," which
orients a reader who knew the previous behavior rather than one arriving
fresh.
* **A complete lead-in** above the `network="public"` example, which was
a noun phrase with a colon on the end.
* **Direct advice and active voice**: "Prefer `public` for untrusted
code" to "Use `public`", and "Anything beyond that can be configured" to
"Configure anything beyond that."

### One question I couldn't answer myself

The `sandbox` row's "Network access" cell reads "gVisor netstack," which
says how the mode is implemented but not what the reader gets. Does
`network="sandbox"` provide egress, or is it isolated like `none`?
That's what someone scanning the table to pick a mode is asking, and
it's the one cell that doesn't answer it. I left the cell alone rather
than guess. Happy to add a few words here if you tell me which it is.

## Related issues

Follows ray-project#65570. Related to ray-project#64964.

## Additional information

`DOCKER_DEFAULT_CAPABILITIES` is in the sandbox package's `__all__`, so
naming it in the prose above the example is safe. `myst_heading_anchors
= 4`, so the new H3 and the existing
`#pass-custom-oci-configurations-to-gvisor` link both resolve.

Note that no pre-commit hook covers Markdown under `doc/source/`, and
Vale is scoped to the Ray Data docs and the example gallery, so nothing
lints this file automatically. Verified by hand: heading depth tops out
at H3, no stacked headings, and both in-page anchors match real
headings.

Signed-off-by: Douglas Strodtman <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
## Description
Added install runsc as standalone CI script.

### Context for Why this was done ?
<img width="1594" height="782" alt="image"
src="https://github.com/user-attachments/assets/474c40d9-1323-4dca-94c6-7ce232535c60"
/>



## Related issues
> "Related to  ray-project#65352 ray-project#64964 ".

---------

Signed-off-by: Limark Dcunha <[email protected]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Oct 23, 2026
## Description
Added install runsc as standalone CI script.

### Context for Why this was done ?
<img width="1594" height="782" alt="image"
src="https://github.com/user-attachments/assets/474c40d9-1323-4dca-94c6-7ce232535c60"
/>



## Related issues
> "Related to  ray-project#65352 ray-project#64964 ".

---------

Signed-off-by: Limark Dcunha <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community core Issues that should be addressed in Ray Core go add ONLY when ready to merge, run all tests sandbox

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ray fails to serialize self-reference objects

4 participants