Skip to content

[POC] Try out experimental Ray sandbox environment - #2725

Closed
pcmoritz wants to merge 2 commits into
harbor-framework:mainfrom
pcmoritz:ray-sandbox-environment
Closed

pcmoritz wants to merge 2 commits into
harbor-framework:mainfrom
pcmoritz:ray-sandbox-environment

Conversation

@pcmoritz

@pcmoritz pcmoritz commented Aug 13, 2026 •

Copy link
Copy Markdown

This is to test the new Ray Sandbox feature with harbor (see ray-project/enhancements#69 and ray-project/ray#64964) and see if anything needs to be fixed on the Ray side (the feature is unreleased so far).

With this PR, it works end-to-end for some of the evals, but more fixes might be needed to get it working well.


Open in Devin Review

pcmoritz and others added 2 commits August 12, 2026 16:08
Adds `RaySandboxEnvironment` (`-e ray`), backed by
`ray.experimental.sandbox` (ray-project/ray#64964). Each environment is a
`Sandbox` Ray actor that Ray schedules onto a cluster node, which runs the
task image as a gVisor (`runsc`) container there, so cluster nodes must be
Linux hosts with `runsc` on PATH.

Notable mappings:

- The sandbox is created with workdir "/" so Ray does not bind an empty host
  directory over image content, and `readonly=False` so the rootfs stays
  writable through runsc's overlay. Per-command cwd comes from
  `[environment].workdir`.
- Network policy maps to the runsc network mode: "host" by default, "none"
  for no-network tasks (`disable_internet`). Allowlist mode is rejected.
- CPU/memory map to both the actor reservation (`num_cpus`/`memory`) and the
  OCI cgroup limits, with AUTO behaving as GUARANTEE.
- The actor runs with `max_concurrency=8` so cleanup and log collection are
  not queued behind a long-running agent exec.
- File transfers go through the actor's `write_file`/`read_file` (bytes over
  Ray) rather than its node-local upload/download helpers; directories use
  the shared tar helpers so modes and symlinks survive.

Prebuilt images only: Ray Sandbox pulls image layers and has no build step,
so Dockerfile-only and Docker Compose tasks are rejected with explicit
errors.

The `ray` extra pins `ray>=2.57.0` because 2.58 is not on PyPI yet; the
sandbox module landed after 2.57, so bump the floor to `>=2.58.0` once that
release ships (the environment fails with an explicit message until then).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

@rynewang, this PR changes a file listed for your review:

  • "src/harbor/environments/tar_transfer.py"

@github-actions

Copy link
Copy Markdown
Contributor

Enjoy a better diff viewing experience by clicking one of these URLs:

@devin-ai-integration devin-ai-integration 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.

Devin Review found 4 potential issues.

View 1 additional finding in Devin Review.

Open in Devin Review

Comment on lines +373 to +376
def _network_mode(self) -> str:
if self._network is not None:
return self._network
return _NETWORK_NONE if self._network_disabled else _NETWORK_HOST

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.

🟡 A task that asks for no network can silently be given full network access

The task's own network setting is discarded whenever an operator supplies a network value (self._network short-circuit at src/harbor/environments/ray_sandbox.py:373-376), so a task declared as offline still runs with host networking and no error is raised.
Impact: Tasks that rely on having no internet (for example to prevent cheating or leaking data) can run fully connected without any warning.

Mechanism: env kwarg override bypasses the network policy contract

--env-kwargs / trial kwargs are applied job-wide, so a single network="host" (or "sandbox") override applies to every task in a dataset, including ones whose task.toml sets network_mode = "no-network". _network_mode returns self._network unconditionally when it is set, never consulting self._network_disabled. BaseEnvironment's documented contract (src/harbor/environments/base.py:152-156) is that "Providers must enforce the policy exactly or reject the task before start". Additionally, _ensure_dns (src/harbor/environments/ray_sandbox.py:503) then seeds a resolver, so name resolution works too. A safer behaviour is to reject the combination (or ignore the override) when the effective policy is no-network.

Prompt for agents
In src/harbor/environments/ray_sandbox.py, the `_network_mode` property lets the constructor kwarg `network` unconditionally override the task's network policy. When the task's policy is NO_NETWORK (`self._network_disabled`), an operator-supplied `network="host"`/`"sandbox"` silently grants networking, violating BaseEnvironment's contract that providers enforce the requested policy exactly or reject the task before start. Consider raising a clear ValueError during validation when a networking override is combined with a no-network policy (or forcing "none" in that case), while still allowing the override for public-network tasks.
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

"network": self._network_mode,
"readonly": self._readonly,
}
host_network = self._network_mode != _NETWORK_NONE

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.

🟡 Choosing the isolated sandbox network mode still removes the sandbox's own network isolation

The sandbox's private network compartment is stripped away for every mode except the fully-offline one (host_network = self._network_mode != _NETWORK_NONE at src/harbor/environments/ray_sandbox.py:433), so a user asking for the isolated networking mode gets the node's network instead.
Impact: Selecting the isolated networking option gives the container the machine's network rather than an isolated one, which is the opposite of what was requested.

Mechanism: `host_network` conflates "sandbox" with "host"

_make_oci_spec_transform (src/harbor/environments/ray_sandbox.py:127-140) drops the pathless {"type": "network"} namespace entry when host_network is true. The comment explains this is specifically needed so runsc's --network=host is not defeated by an empty netns. But host_network is computed as "any mode other than none", so the documented third mode network="sandbox" (see the class docstring at src/harbor/environments/ray_sandbox.py:200-202) also loses its dedicated network namespace and inherits the launching netns. The condition should be self._network_mode == _NETWORK_HOST.

Suggested change
host_network = self._network_mode != _NETWORK_NONE
host_network = self._network_mode == _NETWORK_HOST
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +373 to +376
def _network_mode(self) -> str:
if self._network is not None:
return self._network
return _NETWORK_NONE if self._network_disabled else _NETWORK_HOST

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.

🟨 Task-declared no-network policy can be silently overridden by an environment kwarg

_network_mode returns the operator-supplied network kwarg unconditionally, ignoring the task's network policy (src/harbor/environments/ray_sandbox.py:373-376). A job-wide --env-kwargs network=host therefore gives full egress to tasks that declared network_mode = "no-network", and _ensure_dns (src/harbor/environments/ray_sandbox.py:503) additionally seeds a working resolver. BaseEnvironment documents that providers must enforce the policy exactly or reject the task before start (src/harbor/environments/base.py:152-156).

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

"network": self._network_mode,
"readonly": self._readonly,
}
host_network = self._network_mode != _NETWORK_NONE

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.

🟨 Isolated sandbox network mode loses its network namespace, inheriting the node's network

The OCI spec transform strips the sandbox's own (pathless) network namespace whenever the mode is not none, because host_network is computed as self._network_mode != _NETWORK_NONE (src/harbor/environments/ray_sandbox.py:433). The documented network="sandbox" mode (src/harbor/environments/ray_sandbox.py:200-202) is meant to be isolated, but with its namespace removed the container inherits the netns runsc was launched in, i.e. the Ray node's network, exposing node-local services to untrusted agent code.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

@alexgshaw

Copy link
Copy Markdown
Collaborator

Hi @pcmoritz ! Nice to see you here. Can you fix the CI & resolve / address devin comments?

@pcmoritz

Copy link
Copy Markdown
Author

Hey @alexgshaw thanks yes, the plan is to iterate a little more on the Ray Sandbox implementation so we can get rid of the workarounds in this PR and then get the PR in a mergeable state based on that :)

@alexgshaw

Copy link
Copy Markdown
Collaborator

Sounds good. Btw the EnvironmentCapabilities class is a nice checklist for all the different types of features people like to have in harbor environments!

pcmoritz pushed a commit to ray-project/ray 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]>
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]>
@stbenjam stbenjam added the triage:stale Inactive PR with conflicts; candidate for closure during backlog triage label Nov 18, 2026
@stbenjam

Copy link
Copy Markdown
Contributor

Thanks for the contribution! Harbor has changed since this was opened and the branch now has conflicts, so we're closing older inactive PRs to catch up on the queue. This isn't a judgment on the value of the change. If it's still important to you, please rebase on main and open a new PR that links this one.

@stbenjam stbenjam closed this Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core area:docs area:environments area:package area:tests triage:stale Inactive PR with conflicts; candidate for closure during backlog triage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants