Skip to content

[core][sandbox] Modal Compatible Sandbox API Prototype - #66782

Open
paa1750 wants to merge 1 commit into
ray-project:masterfrom
paa1750:modal-sandbox
Open

paa1750 wants to merge 1 commit into
ray-project:masterfrom
paa1750:modal-sandbox

Conversation

@paa1750

@paa1750 paa1750 commented Oct 6, 2026

Copy link
Copy Markdown

Description

This PR introduces the foundation for a modal compatible sandboxing API to ray to create and interact with sandboxes through a Modal like surface.

Additional information

#Key Additions & Changes

  1. Adds the modal sandbox class and associated async actor to manage the sandbox. The API surface is borrowed from modals documentation
  2. Execution of commands is done via create_subprocess_exec(). The process is started and its associated stdin, stdout and stderr are retained. Stdout and stderr are continoulsy drained and buffered and are streamed to the caller side container process via the ray streaming generator. The associated ContainerProcess is returned to the caller when they run exec() to interact with the running process.
  3. Modals Image API is added to support pulling images from registry and base config methods like env, workdir, entrypoint and startup files for starting and configuring the sandbox startup process. This PR does not add support for mutating the base image via methods like pip_install() or run_commands(), it only support pulling and build sandboxes on base registry images.
  4. Modals Probe API is added to support performing readiness probes to ensure that the sandbox is ready to execute commands. It currently support the with_exec() command which is periodically run on the sandbox actor while the main sandbox command is running.
  5. Adds the modal filesystem API and its associated commands to run in the sandbox via exec emulation. Large files are streamed to and from the sandbox to support the large file limits that modal allows (5 GB). All of modals filesystem methods are supported for now except their watch function.

DIfferences

Modals filesystem API uses a rust binary that is staged in the sandbox that is used to execute filesystem ops via JSON messages but here, filesystem operations are implemented via exec emulation to achieve the desired result. Also, This PR adds helper sync functionality to support both sync and async versions of the sandbox API. Modal uses their own package called syncronicity to syncronize their sandbox API and offer both a blocking and non-blocking version of the API via the .aio() method. The syncing in this PR offers the same surface but does differ in terms of it's interaction with the event loop and if needed, the syncronicity can be added as a dependency to provide the same modal experience.

Related issues

Related to #65352

Future Work

  • Support the Modal Image API functionally for building container filesystems through pip_install(), run_commands(), etc.
  • Support CloudBucketMounts for sandboxes. While ray does not have a native volume mechanism, cloud buckets can be mounted via mountpoint-s3 and fuse to support shared filesystem access for sandboxes
  • Support the ingress half of modals networking. While encrypted_ports and h2_ports are not acheivalbe right not as there is no tls proxy, unencrypted_ports can be implemented via port forwarding (need to investigate more)
  • Maybe consider adding a modal like filesystem binary for sandboxes

@paa1750 paa1750 changed the title Modal Compatible Sandbox API Prototype [core][sandbox] Modal Compatible Sandbox API Prototype Oct 14, 2026
@paa1750
paa1750 marked this pull request as ready for review October 14, 2026 11:45
@paa1750
paa1750 requested review from a team as code owners October 14, 2026 11:45
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@paa1750
paa1750 marked this pull request as draft October 14, 2026 11:45
@paa1750
paa1750 marked this pull request as ready for review October 14, 2026 11:49

@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 Modal-compatible API layer (ray.experimental.sandbox.modal) on top of Ray Sandboxes, allowing users to run Modal-based workloads on Ray. It includes an async-native background actor (_SandboxActor) to manage gVisor sandboxes, a custom synchronization layer to expose both blocking and async (.aio) interfaces, and a POSIX shell-based filesystem helper layer. Feedback has been provided to address potential event loop blocks when opening local files synchronously in copy_from_local, and to ensure that cleanup in exec_collect is shielded from cancellation to prevent orphaned processes.

Comment on lines +1817 to +1823
if process.returncode is None:
await self._stop_command(_ExecSession(process, pid_file))
# Bounded for the reason _refuse_if_ended_during_spawn gives.
try:
await asyncio.wait_for(process.wait(), 5)
except asyncio.TimeoutError:
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.

high

When exec_collect is cancelled (e.g., due to a timeout or client disconnection), the active exception is CancelledError. Awaiting self._stop_command directly inside the except BaseException block can be interrupted or raise CancelledError immediately, preventing the cleanup from completing and leaving orphaned processes running inside the sandbox. Wrap the cleanup in asyncio.shield to ensure the process is reliably stopped.

Suggested change
if process.returncode is None:
await self._stop_command(_ExecSession(process, pid_file))
# Bounded for the reason _refuse_if_ended_during_spawn gives.
try:
await asyncio.wait_for(process.wait(), 5)
except asyncio.TimeoutError:
pass
if process.returncode is None:
try:
await asyncio.shield(self._stop_command(_ExecSession(process, pid_file)))
await asyncio.shield(asyncio.wait_for(process.wait(), 5))
except asyncio.TimeoutError:
pass

Comment on lines +337 to +339
with open(local_path, "rb") as source:
with _fs.translate_exec_errors("copy_from_local", remote_path):
await self._upload(_read_chunks(source), remote_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.

medium

Opening a file synchronously in an async method can block the event loop, especially if the file is on a slow or network-mounted filesystem. Use asyncio.to_thread to open and close the file asynchronously to prevent event loop stalls.

        source = await asyncio.to_thread(open, local_path, "rb")
        try:
            with _fs.translate_exec_errors("copy_from_local", remote_path):
                await self._upload(_read_chunks(source), remote_path)
        finally:
            await asyncio.to_thread(source.close)

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

Stale Bugbot comment from a previous run.

@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Oct 14, 2026

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

Stale Bugbot comment from a previous run.

pcmoritz added a commit that referenced this pull request Oct 21, 2026
…t and enforce allowlists (#66359)

## Description

A `network="public"` sandbox could reach everything its pod reaches.
From a sandbox in a CoreWeave pod running a Ray head, GCS, the Ray
client server, the raylet, the object manager, the dashboard agent, the
Kubernetes API, the kubelet, and 169.254.169.254 all accepted
connections. Ray's ports take no token unless the cluster runs with
`RAY_AUTH_MODE=token`, and slirp4netns relays sandbox flows through the
pod's own sockets, so a pod NetworkPolicy can't single them out.

This PR filters every `public` sandbox's egress with an nftables ruleset
in its private network namespace, loaded after slirp4netns brings the
tap up and before runsc starts. A failed load fails the create.

- `cidr_allowlist` defaults to `["internet"]`, public addresses only.
Entries are addresses or networks with optional ports (`10.0.0.5:8000`,
`internet:443`).
- A denylist runs before any list: link-local (instance metadata),
loopback, Alibaba Cloud's and Azure's metadata endpoints, the Kubernetes
API Service, and `RAY_SANDBOX_EGRESS_DENY`. Ray doesn't track its nodes,
as pcmoritz suggested: `internet` leaves them out while their addresses
are internal, which the docs call a best effort, and an operator who
allows internal networks lists the nodes' network in
`RAY_SANDBOX_EGRESS_DENY`, which also covers nodes the autoscaler adds.
- `set_egress_allowlist`, on `SandboxRuntime` and on the actor that
`sandbox.create()` returns, replaces any public sandbox's ruleset in one
`nft -f`, entering its namespaces through fds checked against the ones
recorded at creation.
- With `dns` set, the create sends each resolver one UDP byte from
inside the sandbox and fails, naming the resolver, if the send fails. On
Cilium, which translates the cluster DNS Service IP before the filter
sees it, every lookup failed instead.
- The gRPC facade maps `block_network`, `outbound_cidr_allowlist`, and
`TaskSetNetworkAccess`; open access means `internet`.
- The REST API answers 403 to `network="host"`, `"sandbox"`, or
`rootless=false` unless `allowed_network_modes` / `allow_rootful` allow
them, and `build_app` requires `RAY_SANDBOX_API_TOKEN` unless
`allow_unauthenticated` is set.

Behavior changes: `public` needs `nft` on the node, no longer reaches
private networks without a list, and fails to create when a `dns`
resolver is unreachable. REST deployments need a token.

### Why nftables inside the sandbox netns is the right enforcement point

Inside the sandbox's private user + net namespace, the host-side launch
script has CAP_NET_ADMIN over that child network namespace (without
needing CAP_NET_ADMIN on the Kubernetes worker pod itself).

runsc runs inside that child netns with --network=host. That means
gVisor's hostinet creates real Linux kernel AF_INET/AF_INET6 sockets
inside the child netns, so every packet from the sandbox passes through
the Linux kernel's nf_tables output chain before reaching slirp4netns's
tap0.

**Why sandbox code cannot tamper with the rules (even with
CAP_NET_ADMIN):** gVisor's Sentry intercepts all syscalls inside the
sandbox. Even if the container process has CAP_NET_ADMIN or CAP_NET_RAW,
gVisor's hostinet (without --net-raw) never forwards AF_NETLINK
(NETLINK_NETFILTER / NETLINK_ROUTE) or AF_PACKET sockets to the host
kernel. Running nft flush ruleset or iptables -F inside the sandbox
talks only to gVisor's internal Sentry stub, never touching the host
kernel netns where the rules live.

### Results

TCP connects from a sandbox in a CoreWeave (Cilium) pod running a Ray
head, 5 s timeout, measured on dddd170:

| Destination | Default | `ALLOW_ALL_CIDRS` | +
`RAY_SANDBOX_EGRESS_DENY=<node>,<API server>` |
| --- | --- | --- | --- |
| GCS, Ray client server, raylet, object manager, dashboard | timeout |
open | timeout |
| 169.254.169.254:80 | timeout | timeout | timeout |
| Kubernetes API (Service and endpoint) | timeout | open | timeout |
| 1.1.1.1:443, DNS | open | open | open |

Allow-all reaches the Ray head's ports because Ray doesn't track its
nodes, and it reaches the API Service because Cilium rewrites it to the
API server's address at connect time; `RAY_SANDBOX_EGRESS_DENY` closes
both, and the docs say so. Root in a sandbox with `CAP_NET_ADMIN` and
`CAP_NET_RAW` ran `nft flush ruleset` and `iptables -F`: both failed
with "Protocol not supported", and GCS stayed closed.

How to review: `config.py`, `_internal/egress_guard.py`,
`backend/gvisor.py` (`_render_egress_ruleset`, the run command,
`set_egress_allowlist`, `_unreachable_resolver`), `http/host.py` and
`http/grpc_facade.py`, `http/schemas.py` and `http/app.py`, then the
docs. Skip the `_pb2.py` files.

## Related issues

Follows #65839. Found through SkyRL's SWE-bench Multimodal runs on Ray
Sandbox (skyrl-project/SkyRL#2467). #66782 and #67010 inherit the default.
#66471's restore path needs the same nft install.

## Additional information

- Not a duplicate: none of the 20 open sandbox PRs adds egress filtering
or a default deny.
- Tests on a CoreWeave pod (Cilium, runsc release-20261012.0, root),
rebased on master 7073066: `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 tests/test_egress_guard.py -k "not netns
and not test_create_sandbox_helper"`: 167 passed, 1 skipped. `-k netns`:
22 passed. `test_create_sandbox_helper`: 1 passed.
`tests/test_sandbox.py`: 7 passed. `http/tests`: 167 passed, 10 skipped.
With the Modal SDK 1.5.5 installed on macOS, which CI doesn't have,
`http/tests`: 175 passed, 2 skipped (the gVisor integration tests). On
the pod, `dns=["10.16.0.10"]`, the cluster DNS Service, now fails the
create with "Operation not permitted" and still resolves with
`ALLOW_ALL_CIDRS`; the check adds about 14 ms to a create. pre-commit
passes. This round wasn't rerun as uid 1000.
- I used Claude Code to help write and test this change.

---------

Signed-off-by: xyuzh <[email protected]>
Co-authored-by: Philipp Moritz <[email protected]>
pcmoritz added a commit that referenced this pull request Oct 22, 2026
#67026)

## Description

Ray Sandbox pulled every image anonymously. A registry that answers with
an HTTP basic challenge, as Amazon ECR does, failed every pull with
`HTTP Error 401: Unauthorized`, and private images on Docker Hub, GHCR
or Artifact Registry failed too.

This PR answers the registry's challenge with the credentials that the
node's Docker config (`$DOCKER_CONFIG/config.json`, by default
`~/.docker/config.json`) holds for it. It looks them up the way the
Docker CLI does: the registry's `credHelpers` helper, else `credsStore`,
else its `auths` entry. A helper such as `docker-credential-ecr-login`
mints short-lived credentials from the Pod's IAM role at pull time, so
no secret sits on disk. Start with the new `_internal/docker_config.py`,
then `get_registry_auth_headers` in `image_utils.py`.

- A basic challenge gets the credentials on every registry request. A
bearer challenge trades them, or an identity token through the OAuth2
refresh grant, for a pull token. Redirects to presigned storage never
carry them.
- Credentials stay in the pulling worker. They never reach the image
cache, logs, error messages, or a sandbox.
- A failed pull includes the registry's stated reason. ECR's `DENIED`
names the IAM action that the role lacks.
- A `RAY_SANDBOX_REGISTRY_MIRROR` mirror authenticates the same way, so
an ECR pull-through cache works.
- New docs section: "Pull from private registries", with an ECR example.

One change users may notice: Docker Hub and GHCR challenge every pull,
public images included. A node whose Docker config has credentials for
them now pulls public images with those, and if their credential helper
fails, so does the pull, as with `docker pull`. A node with no Docker
config pulls as before.

## Related issues

None filed. A user running Ray on EKS with sandbox images in private ECR
asked for this, and SkyRL's Harbor environment for Ray Sandbox
(skyrl-project/SkyRL#2467) lists registry auth as a gap.

## Additional information

- Not a duplicate: no open PR matching "sandbox registry", "sandbox
credentials", "credHelpers" or "ECR sandbox" authenticates pulls.
#66782, the Modal API prototype, rejects private registries.
- Tests: `tests/test_registry_auth.py` (37 tests, all failing on master)
serves a fake registry and fake credential helpers from the standard
library. It covers lookup order, both challenges, the refresh grant,
redirects, the mirror, malformed configs, and secrets in errors.
`tests/conftest.py` points `DOCKER_CONFIG` at an empty directory, so no
test uses the runner's credentials.
- Tested on a CoreWeave pod (runsc release-20261005.0, erofs-utils
1.9.4), `TEST_SANDBOX=1 pytest` in
`python/ray/experimental/sandbox/tests`:
- `test_gvisor_backend.py test_image_manager.py test_image_utils.py
test_sandbox_config.py test_sandbox_runtime.py test_registry_auth.py -k
"not netns and not test_create_sandbox_helper"`: 125 passed, 1 skipped.
- `test_gvisor_backend.py -k netns`: 7 passed. `test_sandbox.py` plus
`test_create_sandbox_helper`: 7 passed.
- macOS, `test_registry_auth.py test_image_utils.py`: 72 passed.
pre-commit passes.
- End to end, on the first commit: in the same kind of pod, a gVisor
sandbox booted from a private image behind a `registry` 3.0.0 with
htpasswd (a basic challenge, like ECR's), and the password reached none
of the sandbox's environment, processes or files. Master gets a 401.
- 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]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 2, 2026
…t and enforce allowlists (ray-project#66359)

## Description

A `network="public"` sandbox could reach everything its pod reaches.
From a sandbox in a CoreWeave pod running a Ray head, GCS, the Ray
client server, the raylet, the object manager, the dashboard agent, the
Kubernetes API, the kubelet, and 169.254.169.254 all accepted
connections. Ray's ports take no token unless the cluster runs with
`RAY_AUTH_MODE=token`, and slirp4netns relays sandbox flows through the
pod's own sockets, so a pod NetworkPolicy can't single them out.

This PR filters every `public` sandbox's egress with an nftables ruleset
in its private network namespace, loaded after slirp4netns brings the
tap up and before runsc starts. A failed load fails the create.

- `cidr_allowlist` defaults to `["internet"]`, public addresses only.
Entries are addresses or networks with optional ports (`10.0.0.5:8000`,
`internet:443`).
- A denylist runs before any list: link-local (instance metadata),
loopback, Alibaba Cloud's and Azure's metadata endpoints, the Kubernetes
API Service, and `RAY_SANDBOX_EGRESS_DENY`. Ray doesn't track its nodes,
as pcmoritz suggested: `internet` leaves them out while their addresses
are internal, which the docs call a best effort, and an operator who
allows internal networks lists the nodes' network in
`RAY_SANDBOX_EGRESS_DENY`, which also covers nodes the autoscaler adds.
- `set_egress_allowlist`, on `SandboxRuntime` and on the actor that
`sandbox.create()` returns, replaces any public sandbox's ruleset in one
`nft -f`, entering its namespaces through fds checked against the ones
recorded at creation.
- With `dns` set, the create sends each resolver one UDP byte from
inside the sandbox and fails, naming the resolver, if the send fails. On
Cilium, which translates the cluster DNS Service IP before the filter
sees it, every lookup failed instead.
- The gRPC facade maps `block_network`, `outbound_cidr_allowlist`, and
`TaskSetNetworkAccess`; open access means `internet`.
- The REST API answers 403 to `network="host"`, `"sandbox"`, or
`rootless=false` unless `allowed_network_modes` / `allow_rootful` allow
them, and `build_app` requires `RAY_SANDBOX_API_TOKEN` unless
`allow_unauthenticated` is set.

Behavior changes: `public` needs `nft` on the node, no longer reaches
private networks without a list, and fails to create when a `dns`
resolver is unreachable. REST deployments need a token.

### Why nftables inside the sandbox netns is the right enforcement point

Inside the sandbox's private user + net namespace, the host-side launch
script has CAP_NET_ADMIN over that child network namespace (without
needing CAP_NET_ADMIN on the Kubernetes worker pod itself).

runsc runs inside that child netns with --network=host. That means
gVisor's hostinet creates real Linux kernel AF_INET/AF_INET6 sockets
inside the child netns, so every packet from the sandbox passes through
the Linux kernel's nf_tables output chain before reaching slirp4netns's
tap0.

**Why sandbox code cannot tamper with the rules (even with
CAP_NET_ADMIN):** gVisor's Sentry intercepts all syscalls inside the
sandbox. Even if the container process has CAP_NET_ADMIN or CAP_NET_RAW,
gVisor's hostinet (without --net-raw) never forwards AF_NETLINK
(NETLINK_NETFILTER / NETLINK_ROUTE) or AF_PACKET sockets to the host
kernel. Running nft flush ruleset or iptables -F inside the sandbox
talks only to gVisor's internal Sentry stub, never touching the host
kernel netns where the rules live.

### Results

TCP connects from a sandbox in a CoreWeave (Cilium) pod running a Ray
head, 5 s timeout, measured on dddd170:

| Destination | Default | `ALLOW_ALL_CIDRS` | +
`RAY_SANDBOX_EGRESS_DENY=<node>,<API server>` |
| --- | --- | --- | --- |
| GCS, Ray client server, raylet, object manager, dashboard | timeout |
open | timeout |
| 169.254.169.254:80 | timeout | timeout | timeout |
| Kubernetes API (Service and endpoint) | timeout | open | timeout |
| 1.1.1.1:443, DNS | open | open | open |

Allow-all reaches the Ray head's ports because Ray doesn't track its
nodes, and it reaches the API Service because Cilium rewrites it to the
API server's address at connect time; `RAY_SANDBOX_EGRESS_DENY` closes
both, and the docs say so. Root in a sandbox with `CAP_NET_ADMIN` and
`CAP_NET_RAW` ran `nft flush ruleset` and `iptables -F`: both failed
with "Protocol not supported", and GCS stayed closed.

How to review: `config.py`, `_internal/egress_guard.py`,
`backend/gvisor.py` (`_render_egress_ruleset`, the run command,
`set_egress_allowlist`, `_unreachable_resolver`), `http/host.py` and
`http/grpc_facade.py`, `http/schemas.py` and `http/app.py`, then the
docs. Skip the `_pb2.py` files.

## Related issues

Follows ray-project#65839. Found through SkyRL's SWE-bench Multimodal runs on Ray
Sandbox (skyrl-project/SkyRL#2467). ray-project#66782 and ray-project#67010 inherit the default.
ray-project#66471's restore path needs the same nft install.

## Additional information

- Not a duplicate: none of the 20 open sandbox PRs adds egress filtering
or a default deny.
- Tests on a CoreWeave pod (Cilium, runsc release-20261012.0, root),
rebased on master 7073066: `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 tests/test_egress_guard.py -k "not netns
and not test_create_sandbox_helper"`: 167 passed, 1 skipped. `-k netns`:
22 passed. `test_create_sandbox_helper`: 1 passed.
`tests/test_sandbox.py`: 7 passed. `http/tests`: 167 passed, 10 skipped.
With the Modal SDK 1.5.5 installed on macOS, which CI doesn't have,
`http/tests`: 175 passed, 2 skipped (the gVisor integration tests). On
the pod, `dns=["10.16.0.10"]`, the cluster DNS Service, now fails the
create with "Operation not permitted" and still resolves with
`ALLOW_ALL_CIDRS`; the check adds about 14 ms to a create. pre-commit
passes. This round wasn't rerun as uid 1000.
- I used Claude Code to help write and test this change.

---------

Signed-off-by: xyuzh <[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
ray-project#67026)

## Description

Ray Sandbox pulled every image anonymously. A registry that answers with
an HTTP basic challenge, as Amazon ECR does, failed every pull with
`HTTP Error 401: Unauthorized`, and private images on Docker Hub, GHCR
or Artifact Registry failed too.

This PR answers the registry's challenge with the credentials that the
node's Docker config (`$DOCKER_CONFIG/config.json`, by default
`~/.docker/config.json`) holds for it. It looks them up the way the
Docker CLI does: the registry's `credHelpers` helper, else `credsStore`,
else its `auths` entry. A helper such as `docker-credential-ecr-login`
mints short-lived credentials from the Pod's IAM role at pull time, so
no secret sits on disk. Start with the new `_internal/docker_config.py`,
then `get_registry_auth_headers` in `image_utils.py`.

- A basic challenge gets the credentials on every registry request. A
bearer challenge trades them, or an identity token through the OAuth2
refresh grant, for a pull token. Redirects to presigned storage never
carry them.
- Credentials stay in the pulling worker. They never reach the image
cache, logs, error messages, or a sandbox.
- A failed pull includes the registry's stated reason. ECR's `DENIED`
names the IAM action that the role lacks.
- A `RAY_SANDBOX_REGISTRY_MIRROR` mirror authenticates the same way, so
an ECR pull-through cache works.
- New docs section: "Pull from private registries", with an ECR example.

One change users may notice: Docker Hub and GHCR challenge every pull,
public images included. A node whose Docker config has credentials for
them now pulls public images with those, and if their credential helper
fails, so does the pull, as with `docker pull`. A node with no Docker
config pulls as before.

## Related issues

None filed. A user running Ray on EKS with sandbox images in private ECR
asked for this, and SkyRL's Harbor environment for Ray Sandbox
(skyrl-project/SkyRL#2467) lists registry auth as a gap.

## Additional information

- Not a duplicate: no open PR matching "sandbox registry", "sandbox
credentials", "credHelpers" or "ECR sandbox" authenticates pulls.
ray-project#66782, the Modal API prototype, rejects private registries.
- Tests: `tests/test_registry_auth.py` (37 tests, all failing on master)
serves a fake registry and fake credential helpers from the standard
library. It covers lookup order, both challenges, the refresh grant,
redirects, the mirror, malformed configs, and secrets in errors.
`tests/conftest.py` points `DOCKER_CONFIG` at an empty directory, so no
test uses the runner's credentials.
- Tested on a CoreWeave pod (runsc release-20261005.0, erofs-utils
1.9.4), `TEST_SANDBOX=1 pytest` in
`python/ray/experimental/sandbox/tests`:
- `test_gvisor_backend.py test_image_manager.py test_image_utils.py
test_sandbox_config.py test_sandbox_runtime.py test_registry_auth.py -k
"not netns and not test_create_sandbox_helper"`: 125 passed, 1 skipped.
- `test_gvisor_backend.py -k netns`: 7 passed. `test_sandbox.py` plus
`test_create_sandbox_helper`: 7 passed.
- macOS, `test_registry_auth.py test_image_utils.py`: 72 passed.
pre-commit passes.
- End to end, on the first commit: in the same kind of pod, a gVisor
sandbox booted from a private image behind a `registry` 3.0.0 with
htpasswd (a basic challenge, like ECR's), and the password reached none
of the sandbox's environment, processes or files. Master gets a 401.
- 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
This PR introduces the foundation for a modal compatible sandboxing API to ray to create and interact with sandboxes through a Modal like surface.

Signed-off-by: paa1750 <[email protected]>
Co-authored-by: Claude <[email protected]>

@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 and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 70c51c2. Configure here.

target_dir = os.path.join(images_dir, safe_name)
if not os.path.isdir(target_dir):
return
lock_path = os.path.join(images_dir, f"{safe_name}.lock")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

force_build misses the image cache

High Severity

invalidate_cached_image looks up the cache with sanitize_image_name, but pulls store images under image_cache_name. For a registry reference those names differ, so the directory check fails and the function returns without removing .extracted. force_build=True therefore never refreshes a cached tag.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 70c51c2. Configure here.

@sunnylovestiramisu sunnylovestiramisu 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.

This adds ~10k non-test LOC across core sandbox image/backend fixes and 5+ Modal subsystems in a single commit. Please split into smaller PRs:

  • Core pull digest verification, cached runsc spec, bare-tar PATH floor, and retry-safe delete_sandbox (_internal/image_utils.py, image_manager.py, backend/gvisor.py + tests)
  • Core backend exec_argv / kill_process_group_argv, per-sandbox image_config, and invalidate_image (backend/base.py, backend/gvisor.py, _internal/image_utils.py, image_manager.py + tests; after 1)
  • Modal exception types, shared types, and .aio synchronize_api wrapper (BUILD.bazel, modal/_sync.py, modal/exception.py, modal/stream_type.py, modal/types.py, modal/_command.py, modal/app.py + sync tests; parallel with 1)
  • Core modal.Sandbox lifecycle, _SandboxActor, ContainerProcess streams, and Image.from_registry (modal/_actor.py without readiness probe, modal/io_streams.py, modal/container_process.py, modal/_resolved_image.py, modal/image.py, modal/sandbox.py, modal/__init__.py + tests; after 2 and 3)
  • Modal Sandbox.filesystem and Image.add_local_* (copy=False) startup files (modal/_fs_commands.py, modal/sandbox_fs.py, modal/image.py, modal/sandbox.py + tests; after 4)
  • Modal Probe readiness checks, API parity suite, and docs (modal/probe.py, modal/_actor.py wait_ready, modal/sandbox.py, doc/source/core/sandboxes.md, doc/source/core/api/sandboxes.md + probe/workflow tests; parallel with 5 after 4)

pcmoritz pushed a commit that referenced this pull request Nov 18, 2026
## Description

`readonly=True` is the default today, and it buys little. A read-only
sandbox boots no faster than a writable one (27 ms both), and it's
slower once it does anything: with an explicit `workdir` it needs a
kernel overlay and takes 87 ms to create, and Python's stdlib imports
take 203 ms instead of 45 ms because nothing can cache `.pyc` files. On
a worker that can't mount a kernel overlay, a read-only sandbox with a
`workdir` already ran writable, with a warning. The mode also needs
special cases across the package, which keep complicating other sandbox
PRs.

This PR removes the option. Every sandbox writes to a private overlay
over its cached image, which is discarded with the sandbox. That
deletes:

- the host-backed scratch `workdir` and the `/tmp` tmpfs,
- the kernel overlay for missing mount points and the writable-root
fallback (`needs_rootfs_overlay` is hooks only now),
- `_seed_mountpoints` in the image build, since runsc creates mount
points in the sandbox's overlay,
- the `workdir` branches in `disk` capping (`--overlay2 all:`),
checkpoint, and restore.

About 600 lines net. Read `image_manager.py` and `backend/gvisor.py`
first. Most of the rest is tests and docs.

Behavior changes:

- The root filesystem is writable by default. A `workdir` is a plain
directory in the overlay, and `/tmp` is on the root filesystem.
- `readonly=False` passed to `create()`, `restore()`, `Sandbox`, or
`SandboxRuntime` is ignored with a `RayDeprecationWarning`, and the HTTP
API ignores `readonly: false`, so callers that pass it keep working.
`readonly=True` raises a `ValueError`, and the HTTP API answers `422`,
because ignoring it would hand the caller a writable sandbox.
- `disk` works without a `workdir`, and counts the `workdir` too.
- A relative `workdir` raises a `ValueError`, or gets a `422` over HTTP,
instead of failing when the container starts.
- Restore refuses a checkpoint of a `readonly=True` sandbox, whose saved
state depends on the read-only root. Checkpoints of writable sandboxes
restore as before. Restore also refuses a different `workdir`, which
runsc rejects anyway.
- Without `disk`, any sandbox can now fill the node's disk. A node-wide
default cap is a follow-up.
- `commit()` from #67972 works on every sandbox, so its read-only check
is gone. Its new layer leaves out the mount points runsc creates when
the base image lacks them, such as an empty `/etc/hosts`.

## Related issues

None filed. This comes from review feedback that the read-only mode
complicates other sandbox PRs.

## Additional information

- Not a duplicate: no open PR removes the option. It overlaps #67810
(its `_seed_erofs_image` pass can go), #67076 (the fallback's warning),
and #67077 and #67728 (`readonly` in the warm-pool key). #67972 merged
since, and the merge with master drops its read-only check. #66782 and
#67010 pass `readonly=False`, which still works.
- Numbers: measured on master on November 9 with `python:3.10-slim`,
medians of 10 rounds.
- Tests: new tests cover the writable default, `disk` with and without a
`workdir`, the ignored `readonly=False` and the refused `readonly=True`
in Python and over HTTP, the refused read-only checkpoint, and an image
with only `/bin` and `/lib`, which boots with host mounts, `/etc/hosts`,
and `/etc/resolv.conf`. I also booted that image from a kernel overlay
with a hook, and as a non-root user.
- Tested in a privileged container with runsc release-20261026.0, as
root. `pytest python/ray/experimental/sandbox/tests`: 651 passed, 39
skipped (no GPU, `erofsfuse`, or delegated cgroup there), 3 failed. The
3 are GPU and CDI tests that fail the same way on master in that
container, whose Ray core predates `get_cdi_kind`. `pytest
python/ray/experimental/sandbox/http/tests`: 185 passed, 10 skipped. The
skipped ones are the Modal SDK tests, which passed on the first commit
with the SDK installed. pre-commit and the API param coverage lint pass.
- I used Claude Code to help write and test this change.

---------

Signed-off-by: xyuzh <[email protected]>
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Nov 27, 2026

This branch has not been deployed

No deployments
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 stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants