Skip to content

[core][sandbox] Add pluggable sandbox backends and an Agent Substrate backend - #68616

Draft
sunnylovestiramisu wants to merge 6 commits into
ray-project:masterfrom
sunnylovestiramisu:sandbox-substrate-backend
Draft

sunnylovestiramisu wants to merge 6 commits into
ray-project:masterfrom
sunnylovestiramisu:sandbox-substrate-backend

Conversation

@sunnylovestiramisu

@sunnylovestiramisu sunnylovestiramisu commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Draft. This is stacked on #67485 (sandbox-checkpoint-remote); please review only the two commits on top of it. It also depends on an env-rl release with ForkEnvironment (see "Dependencies" below), so it stays a draft until that release exists.

Why are these changes needed?

ray.experimental.sandbox has only one backend: gVisor sandboxes on the Ray node. Users who already run Agent Substrate want to run the same SandboxRuntime / Sandbox / HTTP-API code against it, without changing that code. Substrate provides snapshot-based suspend, wake, and fork of sandboxes on a separate fleet. This PR makes the backend selectable and adds a Substrate backend.

What does this PR do?

There are two commits, which can be reviewed separately.

1. [sandbox] Let SandboxRuntime select its backend by argument or RAY_SANDBOX_BACKEND

Backend-agnostic. gVisor stays the default and its behavior is unchanged.

  • SandboxRuntime(backend=...) takes a backend instance or a name. With no argument, it reads RAY_SANDBOX_BACKEND, and falls back to gvisor when that is unset.
  • A name resolves in this order:
    1. a built-in name (gvisor, substrate);
    2. an entry point in the new ray.sandbox_backends group, so out-of-tree backends need no Ray change;
    3. a module:Class import path.
      The registry lives in backend/registry.py.
  • New BaseSandboxBackend hooks:
    • needs_image_manager: a backend that pulls images itself doesn't get a local ImageManager.
    • checkpoint_format: restore() refuses another backend's checkpoint, and the error names that backend.
    • check_resources(): defaults to the existing local cgroup check.
    • delete_checkpoint(): the default validates that the path is a checkpoint directory, then removes it. It refuses /, $HOME, and the cwd.
  • SandboxRuntime:
    • New delete_checkpoint().
    • restore() cancels an old TTL timer when the backend returns an id the runtime already tracks.
    • commit() raises NotImplementedError on a backend that can't export a root filesystem.

2. [sandbox] Add a Substrate sandbox backend

backend/substrate.py runs each sandbox as a Substrate environment. You select it with RAY_SANDBOX_BACKEND=substrate. Ray doesn't install its SDK: pip install ate-env-rl. The SDK is imported only when the backend is selected, and a test checks that the default gVisor path never imports it.

Why the env-rl SDK and ate-env-api, rather than Substrate's control plane (ateapi) directly.

  • Ray's sandbox contract needs exec, file read/write, creation from an image, and fork.
  • Substrate's ateapi creates, resumes, and suspends actors and routes to them. It has no process or file RPCs and no fork.
  • ate-env (env-rl) adds exactly these, through an in-sandbox guest agent:
    • StartProcess / ReadFile / WriteFile;
    • per-image templates built from rootfs_image;
    • ForkEnvironment;
    • implicit wake with retries on the next call.
  • Calling ateapi directly would mean reimplementing and versioning that guest protocol inside Ray.
  • The cost is one extra gRPC hop per call, the ate-env-api service to operate, and a pre-1.0 SDK dependency. Ray uses the SDK only as an optional, lazily imported client.

Semantics (differences from gVisor are also in the docs and the module docstring):

Operation Substrate backend
create(...) Creates an environment from a digest-pinned image, placed on the requesting worker's domain (NODE_NAME → ate-env/domain). Fails closed on options it can't honor: mounts, cidr_allowlist, dns, non-default capabilities, gpu_ids, non-zero disk, oom_score_adj, and network other than "none". cpu/memory are logged, not enforced: the template sizes the sandbox. env, workdir, and shell behave as on gVisor.
exec(...) String commands run as [shell, "-c", cmd] with the configured shell (default /bin/bash). timeout=None means no deadline, as on gVisor. user= isn't supported.
checkpoint(sid, leave_running=False) Suspends the sandbox, which becomes the checkpoint. In this process, exec(sid) then raises and delete(sid) is a no-op.
checkpoint(sid, leave_running=True) Forks the sandbox into a new suspended environment, which is the checkpoint. The sandbox's later changes don't reach the checkpoint.
checkpoint(sid) without a path Returns a substrate:// CheckpointPath handle that restores on any node.
checkpoint(sid, checkpoint_path, remote=...) Writes a #67485-format manifest.json (plus a substrate section) and state/, so ray.experimental.sandbox.restore() and Sandbox(restore_from=...) work. Refuses a non-empty directory that holds no checkpoint.
restore(checkpoint) (default) Makes a new sandbox copied from the checkpoint, with one ForkEnvironment call. The checkpoint stays and can be restored any number of times. Substrate refuses concurrent forks of one environment, so concurrent copies of one checkpoint serialize: they retry ABORTED with jittered backoff until the call's timeout_seconds. Server-side coalescing is tracked in gke-labs/env-rl#69.
restore(checkpoint, resume_in_place=True) (or RAY_SUBSTRATE_RESTORE_MODE=resume) Returns the checkpointed environment itself, with no RPC: it wakes on its next command. This uses up the checkpoint, and another restore raises SandboxError. It fits per-step suspend/resume loops.
SandboxRuntime.delete_checkpoint(checkpoint) Deletes the checkpoint's environment (retrying while copies keep it busy) and its files. A new checkpoint at the same path replaces, and deletes, the old one.
pause() / resume() Suspends / no-op: the next command wakes the sandbox.

Robustness.

  • Write, resume, and delete of a path checkpoint hold an flock on <path>/.substrate.lock. Copies read the atomically replaced manifest without a lock: they re-read it before each fork attempt, and check again after the fork. A copy therefore never forks a checkpoint that was resumed in place or deleted.
  • If a fork times out on the client, the copy may still be made on the server; it is deleted once it exists.
  • The backend's state is per process: one event loop thread and one gRPC channel per endpoint. It survives os.fork() (register_at_fork), shuts down at exit, and keeps its per-process maps bounded.

Configuration uses RAY_SUBSTRATE_* env vars (endpoint, auth token or token file, atespace, templates per domain, node→domain map, restore mode, suspend mode, RPC timeout). They are documented in doc/source/core/sandboxes.md under "Sandbox backends".

Dependencies and known limitations

  • env-rl release. Copy restores and checkpoint(leave_running=True) need Client.fork (ForkEnvironment), which is in env-rl commit 6fd75328 but not yet in an ate-env-rl release; added in ate-env-api: ForkEnvironment copies one environment N times gke-labs/env-rl#70, not yet released. The backend checks both the SDK (hasattr(Client, "fork")) and the server (fork_environment in GetServerInfo.features), and points to resume_in_place=True otherwise. MIN_FORK_SDK_RELEASE will be set when the release exists.
  • grpcio/protobuf. ate-env-rl requires grpcio>=1.85.1 and protobuf>=7.35. Ray's compiled constraints pin grpcio==1.85.0 and protobuf==5.27.5 (Python < 3.12) / 6.33.6 (Python ≥ 3.12). So installing the SDK upgrades both past Ray's tested pins. Ray itself doesn't depend on the SDK. We will confirm that Ray's generated protobuf modules load on protobuf 7 before leaving draft.
  • Fork fan-out. N concurrent copies of one checkpoint take about N × fork latency until ate-env-api: coalesce or queue concurrent ForkEnvironment calls on the same source gke-labs/env-rl#69 lands. Pass timeout_seconds accordingly.
  • Cross-process coordination of path checkpoints works on one node, or on shared storage with POSIX locks and atomic rename (NFS; not gcsfuse). substrate:// handles coordinate within one process.

Benchmark

The unchanged Ray Sandbox RL benchmark (ray_prime_rl.py), with only the backend switched: 36,841 images × 6 rollouts × 40 steps = 8.84M tasks on the same 121 GKE nodes (9,328 vCPU). Each step wakes a suspended sandbox, runs a command and suspends it again. A fork pass in between copies 512 sandboxes 4 times each. Substrate run on this PR's exact code (c95449b663); the wake loop uses resume_in_place=True and the fork pass uses default copy restores.

Ray gVisor backend Substrate backend (this PR)
Total time 17.0 min 44.8 min
Failed tasks 0.00% 0.21%
New sandbox ready, p99 (includes slot wait) 3.16 s 2.55 s
Wake-up ready, p99 3.60 s 5.97 s
Suspend, p99 0.19 s 2.07 s
Fork 4×, client p50 / p99 0.42 s / 0.71 s 4.49 s / 7.17 s (serialized copies, see env-rl#69)
  • The gap is Substrate's per-step suspend and wake (about 1.1 s of work per task vs about 0.2 s on gVisor, plus control-plane round trips), not this backend: an in-house harness calling the SDK directly took 45.0 min on the same cluster.
  • Fork copies failed 49% (1,008 of 2,048) on this cluster, but not because of fork or this backend. The test cluster's Substrate build lacks atelet: refresh the credentials of provider leases agent-substrate/substrate#4030 (refresh the registry credentials of image-provider leases), so after the credentials expired, lazily loaded image data that a node had not fetched yet failed with Input/output error or hung. The fork check is the only benchmark step that runs a binary the image had not used yet (cat); plain sandboxes on the affected nodes failed the same way. Fork latencies above count only the copies that succeeded.

Related issue number

Checks

  • I've signed off every commit (by using the -s flag, i.e., git commit -s) in this PR.
  • I've linted the changed files with the repo's ruff and black configuration (scripts/format.sh equivalents).
  • I've included any doc changes needed for https://docs.ray.io/en/master/: doc/source/core/sandboxes.md, "Sandbox backends" and "Agent Substrate backend".
  • I've added any new APIs to the API Reference. For example, if I added a method in Tune, I've added it in doc/source/tune/api/ under the corresponding .rst file. (SandboxRuntime(backend=...) and SandboxRuntime.delete_checkpoint are alpha APIs under ray.experimental.sandbox.)
  • I've made sure the tests are passing (locally: 165 tests across the sandbox suites, with and without the SDK installed; Bazel/CI not yet run). Note that there might be a few flaky tests, see the recent failures at https://flakey-tests.ray.io/
  • Testing Strategy
    • Unit tests
    • Release tests
    • This PR is not tested :(

Tests. No cluster or SDK is needed: tests/substrate_fake.py is a file-backed fake of ate-env-api, loaded by path and shared across threads and processes. It models ABORTED on a busy source for both fork and delete.

  • tests/test_backend_selection.py (15 tests):
    • default gVisor;
    • selection by instance, by name, by env var, by import path, and by entry point (lookup cached);
    • no ImageManager for backends that don't need one;
    • TTL replacement;
    • commit() guard;
    • check_resources delegation;
    • delete_checkpoint validation;
    • cross-backend checkpoint refusal;
    • unknown backend.
  • tests/test_substrate_backend.py (51 tests):
    • Settings and placement parsing; the SDK-missing error; gVisor never importing the SDK; SDK and server fork capability checks.
    • Fail-closed options and Docker default capabilities; a SandboxHost booting on Substrate; configured shell.
    • Checkpoint semantics:
    • TTL; unbounded exec vs bounded control calls.
    • Concurrency:
      • 100 threads;
      • concurrent resumes;
      • concurrent copies from threads and from processes;
      • ABORTED until the deadline;
      • a copy stopping or being deleted when its checkpoint is resumed in place;
      • delete_checkpoint and replacement while copies fork;
      • fork timeout deleting the late copy;
      • re-checkpoint during a copy.
    • Lifecycle: use after os.fork() (runtimes built before and after the fork); shutdown and restart; bounded LRU maps.
    • A Sandbox actor checkpointing and restoring through ray.experimental.sandbox.restore().

…torage

Stacked on ray-project#66471 (node-local checkpoint/restore), split out of it in
review (ray-project#66471 (review)).

Adds remote=True to Sandbox.checkpoint(), SandboxRuntime.checkpoint() and
the backend for checkpoints written to storage that every node mounts at
the same path (NFS, Filestore, Cloud Storage FUSE). The manifest and the
returned CheckpointPath record it, sandbox.restore() then doesn't pin the
restored actor to the checkpoint's node, and the backend allows a restore
on another node. restore() also takes remote= to override the recorded
value.

Restoring on another node needs every node to build the sandbox's image
identically; the restore-time superblock check refuses a node whose build
differs. Reproducible builds come in a separate PR.

Signed-off-by: Sunny Song <[email protected]>
- __init__.py: sandbox.restore(path, remote=True) with a plain path this
  process can't read now raises unless cpu and memory are passed, instead
  of reserving Ray's default 1 CPU while the restored sandbox keeps the
  checkpoint's cgroup limits.
  ray-project#67485 (comment)

Signed-off-by: Sunny Song <[email protected]>
Review: ray-project#67485 (review)

- gvisor.py: checkpoint_sandbox(remote=True) without a checkpoint_path
  raises instead of writing to the node-local default location that a
  restore on another node can't find.
  ray-project#67485 (comment)
- sandbox.py, runtime.py, backend/base.py, backend/gvisor.py: remote comes
  after timeout_seconds in Sandbox.checkpoint, SandboxRuntime.checkpoint
  and restore, and the backend methods, as in sandbox.restore(), so a
  positional timeout can't bind to remote.
  ray-project#67485 (comment)
- __init__.py: sandbox.restore() treats a readable manifest as
  authoritative for node_id, cpu, memory and remote, over a possibly
  stale CheckpointPath, and falls back to the CheckpointPath's metadata
  when the manifest can't be read (missing, or PermissionError on shared
  storage).
  ray-project#67485 (comment)
- __init__.py: the error for a plain path this process can't read says to
  pass the CheckpointPath, or remote=True with cpu and memory, and the
  docstring says that cpu and memory set the restored sandbox's limits as
  well as the actor's reservation.
  ray-project#67485 (comment)
- sandbox.py: Sandbox passes image and an explicit disk (including 0) on
  to restore, so a changed image or disk is rejected instead of silently
  ignored; disk now defaults to None (still no cap on create).
  ray-project#67485 (comment)

Signed-off-by: Sunny Song <[email protected]>
- __init__.py: sandbox.restore() passes on only the caller's remote, not
  one inferred from a CheckpointPath, so the worker decides from the
  manifest on disk; a later node-local checkpoint at the same path is
  still rejected on another node. The inferred value still decides
  scheduling when this process can't read the manifest.
  ray-project#67485 (comment)
  ray-project#67485 (comment)
- checkpoint_utils.py, sandboxes.md: copying a checkpoint onto storage
  where root can't set owners (NFS root_squash) fails with an error that
  says so, and the docs say that shared storage needs no_root_squash,
  since checkpoints keep the owners of the sandbox's files.
  ray-project#67485 (comment)

Signed-off-by: Sunny Song <[email protected]>

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant