Skip to content

[core][sandbox] Bridge network="public" namespaces with slirp4netns instead of pasta - #66004

Merged
pcmoritz merged 2 commits into
ray-project:masterfrom
xyuzh:sandbox-slirp4netns
Sep 9, 2026
Merged

pcmoritz merged 2 commits into
ray-project:masterfrom
xyuzh:sandbox-slirp4netns

Conversation

@xyuzh

@xyuzh xyuzh commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

Description

pasta has a design flaw for our topology. It preserves the UDP source port on the host side of every flow (fwd_nat_from_tap: "for UDP we preserve the source port") and sets SO_REUSEADDR on every socket (sock_l4_). With one pasta per sandbox sharing the worker's network namespace, two sandboxes sending UDP from the same source port to the same server end up with two connected host sockets on an identical 4-tuple, and the kernel hands one sandbox's replies to the other.

Reproduced against the merged #65820 wrapper with two public sandboxes and an echo server outside the pod:

Case Sandbox A received Sandbox B received
Same source port 5000 1 own, 0 foreign 21 own, 23 of A's replies
Distinct source ports 24 own, 0 foreign 24 own, 0 foreign

Fixed-port UDP clients talking to a shared service (a DNS resolver, NTP on 123, STUN, game or QEMU forwarders) hit this; TCP is unaffected because pasta lets the kernel pick TCP source ports. A two-line pasta patch (kernel-picked UDP source ports) fixes it, verified locally, and will be sent upstream, but we can't rely on nodes carrying it.

This PR switches the bridge to slirp4netns, which NATs every flow through a fresh, kernel-assigned host port, so flows from different sandboxes can never share a host socket. The topology is unchanged: the unshare --user --net holder pins the namespaces, slirp4netns attaches from the pod side and runs in the foreground inside the sandbox's process group, runsc enters via nsenter as mapped root.

  • --ready-fd gives a real readiness signal and replaces the pidfile polling.
  • --disable-host-loopback and --disable-dns keep the pod's loopback and resolver out of reach; the sandbox sees only the generated resolv.conf.
  • --enable-seccomp filters the relay's syscalls. --enable-sandbox is not used: its setegid(0) fails inside a --map-root-user namespace.
  • Sandboxes get 198.18.0.100 behind NAT instead of a copy of the pod's address. The tap uses --cidr=198.18.0.0/24 (RFC 2544 benchmarking space) rather than slirp4netns's default 10.0.2.0/24, which would be on-link in the sandbox and shadow pod or service ranges that use it.
  • Static builds exist for x86_64 and aarch64, so the arm64 caveat in the docs goes away.

Unchanged: public still reaches whatever the pod can reach on the network; the egress filter remains a follow-up. The docs, the KubeRay example, and the config docstring are updated.

Related issues

Follow-up to #65820.

Additional information

Runtime tests in a privileged rayproject/ray:nightly-py312 container on arm64 (slirp4netns 1.3.5 static, runsc release-20260817), TEST_SANDBOX=1: the existing netns suite (concurrent same-port binds and isolation, egress and DNS, teardown reaps slirp4netns, failed create leaves nothing behind) plus the new test_netns_udp_flows_do_not_cross, which drives two sandboxes from UDP source port 5000 against one resolver with distinct query names and asserts neither receives the other's answers. All pass; the same test fails against pasta. Argv-level unit tests pin the slirp4netns flag list and the readiness gate.

…nstead of pasta

pasta preserves the UDP source port on the host side of every flow and
sets SO_REUSEADDR on every socket. With one pasta per sandbox sharing the
worker's network namespace, two sandboxes sending UDP from the same source
port to the same server end up with two connected host sockets on an
identical 4-tuple, and the kernel hands one sandbox's replies to the
other. Reproduced with the merged wrapper: with both clients on port 5000,
sandbox B received 23 of sandbox A's replies (fixed-port clients talking
to a shared DNS, NTP, or STUN server hit this).

slirp4netns NATs every flow through a fresh, kernel-assigned host port, so
flows from different sandboxes can never share a host socket. It attaches
to the same holder namespaces, runs in the foreground in the sandbox's
process group, and signals readiness through --ready-fd, which replaces
the pidfile polling. --disable-host-loopback and --disable-dns keep the
pod's loopback and resolver out of reach; --enable-seccomp filters the
relay's syscalls (--enable-sandbox is not used: its setegid(0) fails inside
a --map-root-user namespace). Sandboxes now get 10.0.2.100 behind NAT
instead of a copy of the pod's address. Static builds exist for x86_64 and
aarch64, so no arch-specific install path remains.

A new runtime test drives two sandboxes from the same UDP source port
against one resolver and asserts neither receives the other's answers.

Signed-off-by: xyuzh <[email protected]>
@xyuzh
xyuzh requested review from a team as code owners September 8, 2026 19:19

@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 replaces the pasta user-mode networking tool with slirp4netns for Ray Sandboxes configured with network="public". This change prevents UDP flows from crossing between sandboxes, which previously occurred because pasta preserved source ports. The updates span documentation, Dockerfiles, backend implementation, and tests. The review feedback highlights an issue in the newly added test_netns_udp_flows_do_not_cross test, where exceptions raised in background threads are not propagated to the main thread, potentially causing false passes. A robust thread-handling suggestion is provided to address this.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit ad4eb67. Configure here.

… thread errors in the UDP test

- Run slirp4netns with --cidr=198.18.0.0/24. Its default 10.0.2.0/24 is
  on-link in the sandbox, so pods or services in that range (common on
  GKE) would have been unreachable instead of NAT'd. The RFC 2544
  benchmarking range is never routed on the internet and does not overlap
  pod or service CIDRs.
- The UDP isolation test collects exceptions from its worker threads and
  requires a result for both sandboxes, so a failed exec cannot pass by
  leaving the results dict empty.
@ray-gardener ray-gardener Bot added docs An issue or change related to documentation core Issues that should be addressed in Ray Core stability labels Sep 9, 2026
@pcmoritz pcmoritz added the go add ONLY when ready to merge, run all tests label Sep 9, 2026
@pcmoritz
pcmoritz enabled auto-merge (squash) September 9, 2026 10:51
@pcmoritz
pcmoritz merged commit 4a5a0da into ray-project:master Sep 9, 2026
8 checks passed
NightWing1998 pushed a commit to NightWing1998/ray that referenced this pull request Sep 11, 2026
…nstead of pasta (ray-project#66004)

## Description

pasta has a design flaw for our topology. It preserves the UDP source
port on the host side of every flow (`fwd_nat_from_tap`: "for UDP we
preserve the source port") and sets `SO_REUSEADDR` on every socket
(`sock_l4_`). With one pasta per sandbox sharing the worker's network
namespace, two sandboxes sending UDP from the same source port to the
same server end up with two connected host sockets on an identical
4-tuple, and the kernel hands one sandbox's replies to the other.

Reproduced against the merged ray-project#65820 wrapper with two `public` sandboxes
and an echo server outside the pod:

| Case | Sandbox A received | Sandbox B received |
| --- | --- | --- |
| Same source port 5000 | 1 own, 0 foreign | 21 own, **23 of A's
replies** |
| Distinct source ports | 24 own, 0 foreign | 24 own, 0 foreign |

Fixed-port UDP clients talking to a shared service (a DNS resolver, NTP
on 123, STUN, game or QEMU forwarders) hit this; TCP is unaffected
because pasta lets the kernel pick TCP source ports. A two-line pasta
patch (kernel-picked UDP source ports) fixes it, verified locally, and
will be sent upstream, but we can't rely on nodes carrying it.

This PR switches the bridge to **slirp4netns**, which NATs every flow
through a fresh, kernel-assigned host port, so flows from different
sandboxes can never share a host socket. The topology is unchanged: the
`unshare --user --net` holder pins the namespaces, slirp4netns attaches
from the pod side and runs in the foreground inside the sandbox's
process group, runsc enters via `nsenter` as mapped root.

- `--ready-fd` gives a real readiness signal and replaces the pidfile
polling.
- `--disable-host-loopback` and `--disable-dns` keep the pod's loopback
and resolver out of reach; the sandbox sees only the generated
`resolv.conf`.
- `--enable-seccomp` filters the relay's syscalls. `--enable-sandbox` is
not used: its `setegid(0)` fails inside a `--map-root-user` namespace.
- Sandboxes get `198.18.0.100` behind NAT instead of a copy of the pod's
address. The tap uses `--cidr=198.18.0.0/24` (RFC 2544 benchmarking
space) rather than slirp4netns's default `10.0.2.0/24`, which would be
on-link in the sandbox and shadow pod or service ranges that use it.
- Static builds exist for x86_64 and aarch64, so the arm64 caveat in the
docs goes away.

Unchanged: `public` still reaches whatever the pod can reach on the
network; the egress filter remains a follow-up. The docs, the KubeRay
example, and the config docstring are updated.

## Related issues

Follow-up to ray-project#65820.

## Additional information

Runtime tests in a privileged `rayproject/ray:nightly-py312` container
on arm64 (slirp4netns 1.3.5 static, runsc release-20260817),
`TEST_SANDBOX=1`: the existing netns suite (concurrent same-port binds
and isolation, egress and DNS, teardown reaps slirp4netns, failed create
leaves nothing behind) plus the new `test_netns_udp_flows_do_not_cross`,
which drives two sandboxes from UDP source port 5000 against one
resolver with distinct query names and asserts neither receives the
other's answers. All pass; the same test fails against pasta. Argv-level
unit tests pin the slirp4netns flag list and the readiness gate.

---------

Signed-off-by: xyuzh <[email protected]>
pcmoritz pushed a commit that referenced this pull request Sep 22, 2026
## Description

Rootless gVisor serves each image's extracted directory through the
gofer, so every file inside a sandbox reads as the worker's uid (root),
image-baked ownership (postfix's `0700` uid-101 spool, mailman's uid-38
data) flattens away, and `chown` to another uid fails. Fixing that on
the host needs subordinate id ranges and setuid helpers (#65823), which
many environments can't provide.

This caches each image as an **EROFS root filesystem** instead. gVisor
mounts it inside the Sentry, so uids and gids live in the image and in
the private overlay upper layer and never need a host representation:
files keep their real owners and `chown` works for any uid, from an
unprivileged worker, with no id mapping and no user namespace of ours.

- **Build without root.** Extraction records each layer's non-root
owners (whiteout-aware; a later root-owned layer drops the entry;
hardlinks are recorded under their own name so the re-pack keeps the
owner whichever name it emits first), the tree is re-packed as a tar
whose headers carry them, and `mkfs.erofs --tar` (erofs-utils 1.7+)
turns that into the image with `-E^inline_data` (gVisor's EROFS reader
maps the image and only handles the flat-plain layout) and 4 KiB blocks.
The extracted tree is deleted afterwards; the cache holds one file per
image plus the image config.
- **Mount via annotations.** The bundle gets
`dev.gvisor.spec.rootfs.source/type/overlay`; the `self` overlay is
anchored at a per-sandbox directory, and runsc no longer gets
`--overlay2`. `readonly=True` keeps its semantics because the standard
mount points (`/proc`, `/sys`, `/dev`, `/dev/pts`, `/dev/shm`, `/run`,
`/tmp`, `/etc/{resolv.conf,hosts,hostname}`) are seeded into the image
at build time; runsc applies no rootfs overlay to a read-only root and
can't create mount points in an immutable image.
- **Paths resolve inside the tree.** Extraction resolves each member's
parent with the extracted tree as `/` (an absolute symlink target
restarts at the root, `..` never climbs above it), so a member under a
symlinked directory (UsrMerge's `bin -> usr/bin`, Debian's `/var/run ->
/run`) lands where the image means it, its owner is recorded under that
canonical path (where the re-pack finds it), and whiteouts delete
through the same resolution. Before, a relative link left the owner
keyed under the link path and the built image had the file as `0:0`; an
absolute link dropped the member. The `/tmp` and mount-point seeding use
the same resolver, so an image whose `etc`, `dev` or `tmp` links to a
host directory gets its seeds inside the tree, never on the host;
created files use `O_NOFOLLOW`, and a hardlink to a symlink links the
symlink itself.
- **EROFS is the only layout.** Per review, the extracted-directory
layout (and its `RAY_SANDBOX_ROOTFS=dir` switch) is gone, so
`mkfs.erofs` 1.7+ is a hard requirement on worker nodes next to `runsc`.
A pull checks for it before downloading anything and fails with an error
naming what to install. Ubuntu 24.04 and Debian 13 package a new enough
erofs-utils; Ubuntu 22.04's is 1.4 and predates `--tar`, so nodes built
on today's `rayproject/ray` images need it built from source (the docs
carry the recipe). The `.extracted` marker moves to format 3, so a cache
left by an earlier Ray re-pulls once; sandboxes still running on an old
extracted tree keep it (the tree moves into the rebuilt entry, since a
rename leaves the gofer's open root fd alone) and it is deleted on a
later pull once no sandbox uses the image.
- **CI.** The sandbox tests boot real sandboxes with `TEST_SANDBOX=1`,
so the `corebuild` image now builds erofs-utils v1.9.4 from source
(pinned to the tag's commit). Unit tests build images through a fake
`mkfs.erofs` from `conftest.py` and inspect the resulting tar, so they
run anywhere.

**One known gap.** `readonly=True` with an explicit `workdir` runs on a
private writable overlay (warned at spec time and documented): runsc
drops the requested rootfs overlay for read-only roots, and an immutable
image can't grow the workdir mount point. The clean fix is a small
upstream change to runsc (`initGoferConfs`) to honor an explicitly
requested rootfs overlay on a read-only root; `mountAll` already makes
the root writable only while creating mount points. The test for the
intended behavior is skipped with that reason and a new test pins
today's behavior.

Together with a Sentry-side network adapter that proxies to the host
without `unshare --net`, this leaves no host requirements beyond `runsc`
and `mkfs.erofs`.

## Related issues

Supersedes #65823 (closed). Related to #65820 and #66004.

**Merge order: this PR first.** #65942 (per-exec user), #65633 (HTTP
API), and #65839 (gRPC facade) are stacked on this branch in that order;
each carries the commits below it until those merge, so their diffs on
GitHub include this commit until it lands. #65942 resolves
`exec(user=<name>)` inside the running sandbox, so it works unchanged on
this cache layout.

## Additional information

Validated on x86_64 as well: an Anyscale staging cluster
(`anyscale/ray:2.58.0-py312` + runsc release-20260817 + erofs-utils
1.9.4, three 8-CPU nodes) running Terminal-Bench 2.1 with the oracle
agent through the `ray.experimental.sandbox` Python API. The `mailman`
task, which depends on image-baked postfix/mailman file ownership
surviving inside the sandbox, scores 0 on the directory layout and 1.0
with this change; the other 88 tasks are unchanged (89 trials, 0
errored). That is the exact ownership scenario this PR exists for, on a
real cluster rather than a privileged dev container.

Measured in a privileged `rayproject/ray:nightly-py312` container on
arm64 (erofs-utils 1.9.4 built from source, runsc release-20260817):

| image | pull + build | `rootfs.erofs` | extracted tree |
| --- | --- | --- | --- |
| python:3.10-slim | 7.1 s | 156.8 MB | 147 MB |
| ubuntu:24.04 | 4.6 s | 108.0 MB | 104 MB |

`mkfs.erofs` itself takes about 2 s for python:3.10-slim;
`-E^inline_data` costs roughly 6% over the tree size, and the tree is
gone afterwards, so the cache shrinks. A cache hit no longer walks an
extracted tree for eviction accounting either (one file per image),
which removes the ~60 ms per `pull_image` that @OneSizeFitsQuorum
profiled on the directory layout.

Runtime tests in that container as the unprivileged `ray` user with
`TEST_SANDBOX=1` (`test_gvisor_backend.py`, `test_image_utils.py`,
`test_image_manager.py`): 79 passed, 1 skipped (the readonly + workdir
case above); the `ray.init` smoke test was run on its own. The run
started from the cache the directory layout had left on that node, which
the first pull rebuilt to the format-3 marker. They cover image-baked
ownership from a local tar (`101:0:700`, `101:104:2710` setgid dir, a
setuid tool), root traversing another user's `0700` directory, `chown`
to arbitrary uids and `chown -R` with setgid inheritance, a readonly
EROFS root with writable `/tmp`, `network="host"` egress, the
`network="public"` netns suite, and the existing lifecycle, overlay
isolation, and workdir suites. Unit tests cover ownership recording
across layers including hardlinks, the owner-restoring tar filter, the
build through a fake `mkfs.erofs`, the missing/too-old `mkfs.erofs`
error, the format-3 re-pull with and without running sandboxes, and the
EROFS OCI spec.

Signed-off-by: xyuzh <[email protected]>
owenowenisme pushed a commit to owenowenisme/ray that referenced this pull request Sep 23, 2026
…5992)

## Description

Rootless gVisor serves each image's extracted directory through the
gofer, so every file inside a sandbox reads as the worker's uid (root),
image-baked ownership (postfix's `0700` uid-101 spool, mailman's uid-38
data) flattens away, and `chown` to another uid fails. Fixing that on
the host needs subordinate id ranges and setuid helpers (ray-project#65823), which
many environments can't provide.

This caches each image as an **EROFS root filesystem** instead. gVisor
mounts it inside the Sentry, so uids and gids live in the image and in
the private overlay upper layer and never need a host representation:
files keep their real owners and `chown` works for any uid, from an
unprivileged worker, with no id mapping and no user namespace of ours.

- **Build without root.** Extraction records each layer's non-root
owners (whiteout-aware; a later root-owned layer drops the entry;
hardlinks are recorded under their own name so the re-pack keeps the
owner whichever name it emits first), the tree is re-packed as a tar
whose headers carry them, and `mkfs.erofs --tar` (erofs-utils 1.7+)
turns that into the image with `-E^inline_data` (gVisor's EROFS reader
maps the image and only handles the flat-plain layout) and 4 KiB blocks.
The extracted tree is deleted afterwards; the cache holds one file per
image plus the image config.
- **Mount via annotations.** The bundle gets
`dev.gvisor.spec.rootfs.source/type/overlay`; the `self` overlay is
anchored at a per-sandbox directory, and runsc no longer gets
`--overlay2`. `readonly=True` keeps its semantics because the standard
mount points (`/proc`, `/sys`, `/dev`, `/dev/pts`, `/dev/shm`, `/run`,
`/tmp`, `/etc/{resolv.conf,hosts,hostname}`) are seeded into the image
at build time; runsc applies no rootfs overlay to a read-only root and
can't create mount points in an immutable image.
- **Paths resolve inside the tree.** Extraction resolves each member's
parent with the extracted tree as `/` (an absolute symlink target
restarts at the root, `..` never climbs above it), so a member under a
symlinked directory (UsrMerge's `bin -> usr/bin`, Debian's `/var/run ->
/run`) lands where the image means it, its owner is recorded under that
canonical path (where the re-pack finds it), and whiteouts delete
through the same resolution. Before, a relative link left the owner
keyed under the link path and the built image had the file as `0:0`; an
absolute link dropped the member. The `/tmp` and mount-point seeding use
the same resolver, so an image whose `etc`, `dev` or `tmp` links to a
host directory gets its seeds inside the tree, never on the host;
created files use `O_NOFOLLOW`, and a hardlink to a symlink links the
symlink itself.
- **EROFS is the only layout.** Per review, the extracted-directory
layout (and its `RAY_SANDBOX_ROOTFS=dir` switch) is gone, so
`mkfs.erofs` 1.7+ is a hard requirement on worker nodes next to `runsc`.
A pull checks for it before downloading anything and fails with an error
naming what to install. Ubuntu 24.04 and Debian 13 package a new enough
erofs-utils; Ubuntu 22.04's is 1.4 and predates `--tar`, so nodes built
on today's `rayproject/ray` images need it built from source (the docs
carry the recipe). The `.extracted` marker moves to format 3, so a cache
left by an earlier Ray re-pulls once; sandboxes still running on an old
extracted tree keep it (the tree moves into the rebuilt entry, since a
rename leaves the gofer's open root fd alone) and it is deleted on a
later pull once no sandbox uses the image.
- **CI.** The sandbox tests boot real sandboxes with `TEST_SANDBOX=1`,
so the `corebuild` image now builds erofs-utils v1.9.4 from source
(pinned to the tag's commit). Unit tests build images through a fake
`mkfs.erofs` from `conftest.py` and inspect the resulting tar, so they
run anywhere.

**One known gap.** `readonly=True` with an explicit `workdir` runs on a
private writable overlay (warned at spec time and documented): runsc
drops the requested rootfs overlay for read-only roots, and an immutable
image can't grow the workdir mount point. The clean fix is a small
upstream change to runsc (`initGoferConfs`) to honor an explicitly
requested rootfs overlay on a read-only root; `mountAll` already makes
the root writable only while creating mount points. The test for the
intended behavior is skipped with that reason and a new test pins
today's behavior.

Together with a Sentry-side network adapter that proxies to the host
without `unshare --net`, this leaves no host requirements beyond `runsc`
and `mkfs.erofs`.

## Related issues

Supersedes ray-project#65823 (closed). Related to ray-project#65820 and ray-project#66004.

**Merge order: this PR first.** ray-project#65942 (per-exec user), ray-project#65633 (HTTP
API), and ray-project#65839 (gRPC facade) are stacked on this branch in that order;
each carries the commits below it until those merge, so their diffs on
GitHub include this commit until it lands. ray-project#65942 resolves
`exec(user=<name>)` inside the running sandbox, so it works unchanged on
this cache layout.

## Additional information

Validated on x86_64 as well: an Anyscale staging cluster
(`anyscale/ray:2.58.0-py312` + runsc release-20260817 + erofs-utils
1.9.4, three 8-CPU nodes) running Terminal-Bench 2.1 with the oracle
agent through the `ray.experimental.sandbox` Python API. The `mailman`
task, which depends on image-baked postfix/mailman file ownership
surviving inside the sandbox, scores 0 on the directory layout and 1.0
with this change; the other 88 tasks are unchanged (89 trials, 0
errored). That is the exact ownership scenario this PR exists for, on a
real cluster rather than a privileged dev container.

Measured in a privileged `rayproject/ray:nightly-py312` container on
arm64 (erofs-utils 1.9.4 built from source, runsc release-20260817):

| image | pull + build | `rootfs.erofs` | extracted tree |
| --- | --- | --- | --- |
| python:3.10-slim | 7.1 s | 156.8 MB | 147 MB |
| ubuntu:24.04 | 4.6 s | 108.0 MB | 104 MB |

`mkfs.erofs` itself takes about 2 s for python:3.10-slim;
`-E^inline_data` costs roughly 6% over the tree size, and the tree is
gone afterwards, so the cache shrinks. A cache hit no longer walks an
extracted tree for eviction accounting either (one file per image),
which removes the ~60 ms per `pull_image` that @OneSizeFitsQuorum
profiled on the directory layout.

Runtime tests in that container as the unprivileged `ray` user with
`TEST_SANDBOX=1` (`test_gvisor_backend.py`, `test_image_utils.py`,
`test_image_manager.py`): 79 passed, 1 skipped (the readonly + workdir
case above); the `ray.init` smoke test was run on its own. The run
started from the cache the directory layout had left on that node, which
the first pull rebuilt to the format-3 marker. They cover image-baked
ownership from a local tar (`101:0:700`, `101:104:2710` setgid dir, a
setuid tool), root traversing another user's `0700` directory, `chown`
to arbitrary uids and `chown -R` with setgid inheritance, a readonly
EROFS root with writable `/tmp`, `network="host"` egress, the
`network="public"` netns suite, and the existing lifecycle, overlay
isolation, and workdir suites. Unit tests cover ownership recording
across layers including hardlinks, the owner-restoring tar filter, the
build through a fake `mkfs.erofs`, the missing/too-old `mkfs.erofs`
error, the format-3 re-pull with and without running sandboxes, and the
EROFS OCI spec.

Signed-off-by: xyuzh <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…nstead of pasta (ray-project#66004)

## Description

pasta has a design flaw for our topology. It preserves the UDP source
port on the host side of every flow (`fwd_nat_from_tap`: "for UDP we
preserve the source port") and sets `SO_REUSEADDR` on every socket
(`sock_l4_`). With one pasta per sandbox sharing the worker's network
namespace, two sandboxes sending UDP from the same source port to the
same server end up with two connected host sockets on an identical
4-tuple, and the kernel hands one sandbox's replies to the other.

Reproduced against the merged ray-project#65820 wrapper with two `public` sandboxes
and an echo server outside the pod:

| Case | Sandbox A received | Sandbox B received |
| --- | --- | --- |
| Same source port 5000 | 1 own, 0 foreign | 21 own, **23 of A's
replies** |
| Distinct source ports | 24 own, 0 foreign | 24 own, 0 foreign |

Fixed-port UDP clients talking to a shared service (a DNS resolver, NTP
on 123, STUN, game or QEMU forwarders) hit this; TCP is unaffected
because pasta lets the kernel pick TCP source ports. A two-line pasta
patch (kernel-picked UDP source ports) fixes it, verified locally, and
will be sent upstream, but we can't rely on nodes carrying it.

This PR switches the bridge to **slirp4netns**, which NATs every flow
through a fresh, kernel-assigned host port, so flows from different
sandboxes can never share a host socket. The topology is unchanged: the
`unshare --user --net` holder pins the namespaces, slirp4netns attaches
from the pod side and runs in the foreground inside the sandbox's
process group, runsc enters via `nsenter` as mapped root.

- `--ready-fd` gives a real readiness signal and replaces the pidfile
polling.
- `--disable-host-loopback` and `--disable-dns` keep the pod's loopback
and resolver out of reach; the sandbox sees only the generated
`resolv.conf`.
- `--enable-seccomp` filters the relay's syscalls. `--enable-sandbox` is
not used: its `setegid(0)` fails inside a `--map-root-user` namespace.
- Sandboxes get `198.18.0.100` behind NAT instead of a copy of the pod's
address. The tap uses `--cidr=198.18.0.0/24` (RFC 2544 benchmarking
space) rather than slirp4netns's default `10.0.2.0/24`, which would be
on-link in the sandbox and shadow pod or service ranges that use it.
- Static builds exist for x86_64 and aarch64, so the arm64 caveat in the
docs goes away.

Unchanged: `public` still reaches whatever the pod can reach on the
network; the egress filter remains a follow-up. The docs, the KubeRay
example, and the config docstring are updated.

## Related issues

Follow-up to ray-project#65820.

## Additional information

Runtime tests in a privileged `rayproject/ray:nightly-py312` container
on arm64 (slirp4netns 1.3.5 static, runsc release-20260817),
`TEST_SANDBOX=1`: the existing netns suite (concurrent same-port binds
and isolation, egress and DNS, teardown reaps slirp4netns, failed create
leaves nothing behind) plus the new `test_netns_udp_flows_do_not_cross`,
which drives two sandboxes from UDP source port 5000 against one
resolver with distinct query names and asserts neither receives the
other's answers. All pass; the same test fails against pasta. Argv-level
unit tests pin the slirp4netns flag list and the readiness gate.

---------

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

## Description

Rootless gVisor serves each image's extracted directory through the
gofer, so every file inside a sandbox reads as the worker's uid (root),
image-baked ownership (postfix's `0700` uid-101 spool, mailman's uid-38
data) flattens away, and `chown` to another uid fails. Fixing that on
the host needs subordinate id ranges and setuid helpers (ray-project#65823), which
many environments can't provide.

This caches each image as an **EROFS root filesystem** instead. gVisor
mounts it inside the Sentry, so uids and gids live in the image and in
the private overlay upper layer and never need a host representation:
files keep their real owners and `chown` works for any uid, from an
unprivileged worker, with no id mapping and no user namespace of ours.

- **Build without root.** Extraction records each layer's non-root
owners (whiteout-aware; a later root-owned layer drops the entry;
hardlinks are recorded under their own name so the re-pack keeps the
owner whichever name it emits first), the tree is re-packed as a tar
whose headers carry them, and `mkfs.erofs --tar` (erofs-utils 1.7+)
turns that into the image with `-E^inline_data` (gVisor's EROFS reader
maps the image and only handles the flat-plain layout) and 4 KiB blocks.
The extracted tree is deleted afterwards; the cache holds one file per
image plus the image config.
- **Mount via annotations.** The bundle gets
`dev.gvisor.spec.rootfs.source/type/overlay`; the `self` overlay is
anchored at a per-sandbox directory, and runsc no longer gets
`--overlay2`. `readonly=True` keeps its semantics because the standard
mount points (`/proc`, `/sys`, `/dev`, `/dev/pts`, `/dev/shm`, `/run`,
`/tmp`, `/etc/{resolv.conf,hosts,hostname}`) are seeded into the image
at build time; runsc applies no rootfs overlay to a read-only root and
can't create mount points in an immutable image.
- **Paths resolve inside the tree.** Extraction resolves each member's
parent with the extracted tree as `/` (an absolute symlink target
restarts at the root, `..` never climbs above it), so a member under a
symlinked directory (UsrMerge's `bin -> usr/bin`, Debian's `/var/run ->
/run`) lands where the image means it, its owner is recorded under that
canonical path (where the re-pack finds it), and whiteouts delete
through the same resolution. Before, a relative link left the owner
keyed under the link path and the built image had the file as `0:0`; an
absolute link dropped the member. The `/tmp` and mount-point seeding use
the same resolver, so an image whose `etc`, `dev` or `tmp` links to a
host directory gets its seeds inside the tree, never on the host;
created files use `O_NOFOLLOW`, and a hardlink to a symlink links the
symlink itself.
- **EROFS is the only layout.** Per review, the extracted-directory
layout (and its `RAY_SANDBOX_ROOTFS=dir` switch) is gone, so
`mkfs.erofs` 1.7+ is a hard requirement on worker nodes next to `runsc`.
A pull checks for it before downloading anything and fails with an error
naming what to install. Ubuntu 24.04 and Debian 13 package a new enough
erofs-utils; Ubuntu 22.04's is 1.4 and predates `--tar`, so nodes built
on today's `rayproject/ray` images need it built from source (the docs
carry the recipe). The `.extracted` marker moves to format 3, so a cache
left by an earlier Ray re-pulls once; sandboxes still running on an old
extracted tree keep it (the tree moves into the rebuilt entry, since a
rename leaves the gofer's open root fd alone) and it is deleted on a
later pull once no sandbox uses the image.
- **CI.** The sandbox tests boot real sandboxes with `TEST_SANDBOX=1`,
so the `corebuild` image now builds erofs-utils v1.9.4 from source
(pinned to the tag's commit). Unit tests build images through a fake
`mkfs.erofs` from `conftest.py` and inspect the resulting tar, so they
run anywhere.

**One known gap.** `readonly=True` with an explicit `workdir` runs on a
private writable overlay (warned at spec time and documented): runsc
drops the requested rootfs overlay for read-only roots, and an immutable
image can't grow the workdir mount point. The clean fix is a small
upstream change to runsc (`initGoferConfs`) to honor an explicitly
requested rootfs overlay on a read-only root; `mountAll` already makes
the root writable only while creating mount points. The test for the
intended behavior is skipped with that reason and a new test pins
today's behavior.

Together with a Sentry-side network adapter that proxies to the host
without `unshare --net`, this leaves no host requirements beyond `runsc`
and `mkfs.erofs`.

## Related issues

Supersedes ray-project#65823 (closed). Related to ray-project#65820 and ray-project#66004.

**Merge order: this PR first.** ray-project#65942 (per-exec user), ray-project#65633 (HTTP
API), and ray-project#65839 (gRPC facade) are stacked on this branch in that order;
each carries the commits below it until those merge, so their diffs on
GitHub include this commit until it lands. ray-project#65942 resolves
`exec(user=<name>)` inside the running sandbox, so it works unchanged on
this cache layout.

## Additional information

Validated on x86_64 as well: an Anyscale staging cluster
(`anyscale/ray:2.58.0-py312` + runsc release-20260817 + erofs-utils
1.9.4, three 8-CPU nodes) running Terminal-Bench 2.1 with the oracle
agent through the `ray.experimental.sandbox` Python API. The `mailman`
task, which depends on image-baked postfix/mailman file ownership
surviving inside the sandbox, scores 0 on the directory layout and 1.0
with this change; the other 88 tasks are unchanged (89 trials, 0
errored). That is the exact ownership scenario this PR exists for, on a
real cluster rather than a privileged dev container.

Measured in a privileged `rayproject/ray:nightly-py312` container on
arm64 (erofs-utils 1.9.4 built from source, runsc release-20260817):

| image | pull + build | `rootfs.erofs` | extracted tree |
| --- | --- | --- | --- |
| python:3.10-slim | 7.1 s | 156.8 MB | 147 MB |
| ubuntu:24.04 | 4.6 s | 108.0 MB | 104 MB |

`mkfs.erofs` itself takes about 2 s for python:3.10-slim;
`-E^inline_data` costs roughly 6% over the tree size, and the tree is
gone afterwards, so the cache shrinks. A cache hit no longer walks an
extracted tree for eviction accounting either (one file per image),
which removes the ~60 ms per `pull_image` that @OneSizeFitsQuorum
profiled on the directory layout.

Runtime tests in that container as the unprivileged `ray` user with
`TEST_SANDBOX=1` (`test_gvisor_backend.py`, `test_image_utils.py`,
`test_image_manager.py`): 79 passed, 1 skipped (the readonly + workdir
case above); the `ray.init` smoke test was run on its own. The run
started from the cache the directory layout had left on that node, which
the first pull rebuilt to the format-3 marker. They cover image-baked
ownership from a local tar (`101:0:700`, `101:104:2710` setgid dir, a
setuid tool), root traversing another user's `0700` directory, `chown`
to arbitrary uids and `chown -R` with setgid inheritance, a readonly
EROFS root with writable `/tmp`, `network="host"` egress, the
`network="public"` netns suite, and the existing lifecycle, overlay
isolation, and workdir suites. Unit tests cover ownership recording
across layers including hardlinks, the owner-restoring tar filter, the
build through a fake `mkfs.erofs`, the missing/too-old `mkfs.erofs`
error, the format-3 re-pull with and without running sandboxes, and the
EROFS OCI spec.

Signed-off-by: xyuzh <[email protected]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Oct 23, 2026
…nstead of pasta (ray-project#66004)

## Description

pasta has a design flaw for our topology. It preserves the UDP source
port on the host side of every flow (`fwd_nat_from_tap`: "for UDP we
preserve the source port") and sets `SO_REUSEADDR` on every socket
(`sock_l4_`). With one pasta per sandbox sharing the worker's network
namespace, two sandboxes sending UDP from the same source port to the
same server end up with two connected host sockets on an identical
4-tuple, and the kernel hands one sandbox's replies to the other.

Reproduced against the merged ray-project#65820 wrapper with two `public` sandboxes
and an echo server outside the pod:

| Case | Sandbox A received | Sandbox B received |
| --- | --- | --- |
| Same source port 5000 | 1 own, 0 foreign | 21 own, **23 of A's
replies** |
| Distinct source ports | 24 own, 0 foreign | 24 own, 0 foreign |

Fixed-port UDP clients talking to a shared service (a DNS resolver, NTP
on 123, STUN, game or QEMU forwarders) hit this; TCP is unaffected
because pasta lets the kernel pick TCP source ports. A two-line pasta
patch (kernel-picked UDP source ports) fixes it, verified locally, and
will be sent upstream, but we can't rely on nodes carrying it.

This PR switches the bridge to **slirp4netns**, which NATs every flow
through a fresh, kernel-assigned host port, so flows from different
sandboxes can never share a host socket. The topology is unchanged: the
`unshare --user --net` holder pins the namespaces, slirp4netns attaches
from the pod side and runs in the foreground inside the sandbox's
process group, runsc enters via `nsenter` as mapped root.

- `--ready-fd` gives a real readiness signal and replaces the pidfile
polling.
- `--disable-host-loopback` and `--disable-dns` keep the pod's loopback
and resolver out of reach; the sandbox sees only the generated
`resolv.conf`.
- `--enable-seccomp` filters the relay's syscalls. `--enable-sandbox` is
not used: its `setegid(0)` fails inside a `--map-root-user` namespace.
- Sandboxes get `198.18.0.100` behind NAT instead of a copy of the pod's
address. The tap uses `--cidr=198.18.0.0/24` (RFC 2544 benchmarking
space) rather than slirp4netns's default `10.0.2.0/24`, which would be
on-link in the sandbox and shadow pod or service ranges that use it.
- Static builds exist for x86_64 and aarch64, so the arm64 caveat in the
docs goes away.

Unchanged: `public` still reaches whatever the pod can reach on the
network; the egress filter remains a follow-up. The docs, the KubeRay
example, and the config docstring are updated.

## Related issues

Follow-up to ray-project#65820.

## Additional information

Runtime tests in a privileged `rayproject/ray:nightly-py312` container
on arm64 (slirp4netns 1.3.5 static, runsc release-20260817),
`TEST_SANDBOX=1`: the existing netns suite (concurrent same-port binds
and isolation, egress and DNS, teardown reaps slirp4netns, failed create
leaves nothing behind) plus the new `test_netns_udp_flows_do_not_cross`,
which drives two sandboxes from UDP source port 5000 against one
resolver with distinct query names and asserts neither receives the
other's answers. All pass; the same test fails against pasta. Argv-level
unit tests pin the slirp4netns flag list and the readiness gate.

---------

Signed-off-by: xyuzh <[email protected]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Oct 23, 2026
…5992)

## Description

Rootless gVisor serves each image's extracted directory through the
gofer, so every file inside a sandbox reads as the worker's uid (root),
image-baked ownership (postfix's `0700` uid-101 spool, mailman's uid-38
data) flattens away, and `chown` to another uid fails. Fixing that on
the host needs subordinate id ranges and setuid helpers (ray-project#65823), which
many environments can't provide.

This caches each image as an **EROFS root filesystem** instead. gVisor
mounts it inside the Sentry, so uids and gids live in the image and in
the private overlay upper layer and never need a host representation:
files keep their real owners and `chown` works for any uid, from an
unprivileged worker, with no id mapping and no user namespace of ours.

- **Build without root.** Extraction records each layer's non-root
owners (whiteout-aware; a later root-owned layer drops the entry;
hardlinks are recorded under their own name so the re-pack keeps the
owner whichever name it emits first), the tree is re-packed as a tar
whose headers carry them, and `mkfs.erofs --tar` (erofs-utils 1.7+)
turns that into the image with `-E^inline_data` (gVisor's EROFS reader
maps the image and only handles the flat-plain layout) and 4 KiB blocks.
The extracted tree is deleted afterwards; the cache holds one file per
image plus the image config.
- **Mount via annotations.** The bundle gets
`dev.gvisor.spec.rootfs.source/type/overlay`; the `self` overlay is
anchored at a per-sandbox directory, and runsc no longer gets
`--overlay2`. `readonly=True` keeps its semantics because the standard
mount points (`/proc`, `/sys`, `/dev`, `/dev/pts`, `/dev/shm`, `/run`,
`/tmp`, `/etc/{resolv.conf,hosts,hostname}`) are seeded into the image
at build time; runsc applies no rootfs overlay to a read-only root and
can't create mount points in an immutable image.
- **Paths resolve inside the tree.** Extraction resolves each member's
parent with the extracted tree as `/` (an absolute symlink target
restarts at the root, `..` never climbs above it), so a member under a
symlinked directory (UsrMerge's `bin -> usr/bin`, Debian's `/var/run ->
/run`) lands where the image means it, its owner is recorded under that
canonical path (where the re-pack finds it), and whiteouts delete
through the same resolution. Before, a relative link left the owner
keyed under the link path and the built image had the file as `0:0`; an
absolute link dropped the member. The `/tmp` and mount-point seeding use
the same resolver, so an image whose `etc`, `dev` or `tmp` links to a
host directory gets its seeds inside the tree, never on the host;
created files use `O_NOFOLLOW`, and a hardlink to a symlink links the
symlink itself.
- **EROFS is the only layout.** Per review, the extracted-directory
layout (and its `RAY_SANDBOX_ROOTFS=dir` switch) is gone, so
`mkfs.erofs` 1.7+ is a hard requirement on worker nodes next to `runsc`.
A pull checks for it before downloading anything and fails with an error
naming what to install. Ubuntu 24.04 and Debian 13 package a new enough
erofs-utils; Ubuntu 22.04's is 1.4 and predates `--tar`, so nodes built
on today's `rayproject/ray` images need it built from source (the docs
carry the recipe). The `.extracted` marker moves to format 3, so a cache
left by an earlier Ray re-pulls once; sandboxes still running on an old
extracted tree keep it (the tree moves into the rebuilt entry, since a
rename leaves the gofer's open root fd alone) and it is deleted on a
later pull once no sandbox uses the image.
- **CI.** The sandbox tests boot real sandboxes with `TEST_SANDBOX=1`,
so the `corebuild` image now builds erofs-utils v1.9.4 from source
(pinned to the tag's commit). Unit tests build images through a fake
`mkfs.erofs` from `conftest.py` and inspect the resulting tar, so they
run anywhere.

**One known gap.** `readonly=True` with an explicit `workdir` runs on a
private writable overlay (warned at spec time and documented): runsc
drops the requested rootfs overlay for read-only roots, and an immutable
image can't grow the workdir mount point. The clean fix is a small
upstream change to runsc (`initGoferConfs`) to honor an explicitly
requested rootfs overlay on a read-only root; `mountAll` already makes
the root writable only while creating mount points. The test for the
intended behavior is skipped with that reason and a new test pins
today's behavior.

Together with a Sentry-side network adapter that proxies to the host
without `unshare --net`, this leaves no host requirements beyond `runsc`
and `mkfs.erofs`.

## Related issues

Supersedes ray-project#65823 (closed). Related to ray-project#65820 and ray-project#66004.

**Merge order: this PR first.** ray-project#65942 (per-exec user), ray-project#65633 (HTTP
API), and ray-project#65839 (gRPC facade) are stacked on this branch in that order;
each carries the commits below it until those merge, so their diffs on
GitHub include this commit until it lands. ray-project#65942 resolves
`exec(user=<name>)` inside the running sandbox, so it works unchanged on
this cache layout.

## Additional information

Validated on x86_64 as well: an Anyscale staging cluster
(`anyscale/ray:2.58.0-py312` + runsc release-20260817 + erofs-utils
1.9.4, three 8-CPU nodes) running Terminal-Bench 2.1 with the oracle
agent through the `ray.experimental.sandbox` Python API. The `mailman`
task, which depends on image-baked postfix/mailman file ownership
surviving inside the sandbox, scores 0 on the directory layout and 1.0
with this change; the other 88 tasks are unchanged (89 trials, 0
errored). That is the exact ownership scenario this PR exists for, on a
real cluster rather than a privileged dev container.

Measured in a privileged `rayproject/ray:nightly-py312` container on
arm64 (erofs-utils 1.9.4 built from source, runsc release-20260817):

| image | pull + build | `rootfs.erofs` | extracted tree |
| --- | --- | --- | --- |
| python:3.10-slim | 7.1 s | 156.8 MB | 147 MB |
| ubuntu:24.04 | 4.6 s | 108.0 MB | 104 MB |

`mkfs.erofs` itself takes about 2 s for python:3.10-slim;
`-E^inline_data` costs roughly 6% over the tree size, and the tree is
gone afterwards, so the cache shrinks. A cache hit no longer walks an
extracted tree for eviction accounting either (one file per image),
which removes the ~60 ms per `pull_image` that @OneSizeFitsQuorum
profiled on the directory layout.

Runtime tests in that container as the unprivileged `ray` user with
`TEST_SANDBOX=1` (`test_gvisor_backend.py`, `test_image_utils.py`,
`test_image_manager.py`): 79 passed, 1 skipped (the readonly + workdir
case above); the `ray.init` smoke test was run on its own. The run
started from the cache the directory layout had left on that node, which
the first pull rebuilt to the format-3 marker. They cover image-baked
ownership from a local tar (`101:0:700`, `101:104:2710` setgid dir, a
setuid tool), root traversing another user's `0700` directory, `chown`
to arbitrary uids and `chown -R` with setgid inheritance, a readonly
EROFS root with writable `/tmp`, `network="host"` egress, the
`network="public"` netns suite, and the existing lifecycle, overlay
isolation, and workdir suites. Unit tests cover ownership recording
across layers including hardlinks, the owner-restoring tar filter, the
build through a fake `mkfs.erofs`, the missing/too-old `mkfs.erofs`
error, the format-3 re-pull with and without running sandboxes, and the
EROFS OCI spec.

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

Labels

core Issues that should be addressed in Ray Core docs An issue or change related to documentation go add ONLY when ready to merge, run all tests sandbox stability

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants