Skip to content

[core][sandbox] Restore sandbox checkpoints on any node from shared storage - #67485

Open
sunnylovestiramisu wants to merge 4 commits into
ray-project:masterfrom
sunnylovestiramisu:sandbox-checkpoint-remote
Open

sunnylovestiramisu wants to merge 4 commits into
ray-project:masterfrom
sunnylovestiramisu:sandbox-checkpoint-remote

Conversation

@sunnylovestiramisu

@sunnylovestiramisu sunnylovestiramisu commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Description

Split out of #66471 in review (comment).

#66471 (merged) made checkpoints node-local: sandbox.restore() pins the restored actor to the node that took the checkpoint, and the backend rejects a restore anywhere else. This PR adds remote=True for checkpoints written to storage that every node mounts at the same path, such as NFS, Filestore, or Cloud Storage FUSE:

  • Sandbox.checkpoint(remote=True), SandboxRuntime.checkpoint(remote=True), and GVisorSandboxBackend.checkpoint_sandbox(remote=True) record remote in the manifest and in the returned CheckpointPath.
  • sandbox.restore() doesn't pin a remote checkpoint's actor to a node, and the backend allows the restore on another node. restore(remote=...) overrides the recorded value.
  • The checkpoint stays owner-only (0700/0600) on shared storage. Nodes need the same UID, not world-readable files.

Restoring on another node also needs every node to build the sandbox's image identically. #67484 provides that. Without it, the restore-time superblock check from #66471 refuses the node with a clear error.

Related issues

Follow-up to #66471, now merged; this branch is rebased onto master. Works together with #67484.

Additional information

  • Not a duplicate: this was carved out of [core][sandbox] Add checkpoint/restore, pause/resume support using runsc #66471 at a reviewer's request.
  • Tests: TEST_SANDBOX=1 pytest python/ray/experimental/sandbox/tests/ --ignore=python/ray/experimental/sandbox/tests/test_sandbox.py gave 271 passed, 21 failed. The 21 failures are identical on master on the same machine, which lacks mkfs.erofs and runsc. pre-commit run --files <changed files> passes.
  • A two-node test on a cluster with shared storage, as the reviewer asked, is still to do.
  • This change was prepared with AI assistance and reviewed by the author.

@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 checkpointing, restoration, pausing, and resuming capabilities for Ray Sandboxes, enabling parallel branching for tree search and suspend/resume for multi-turn rollouts. It adds the high-level restore helper, updates the sandbox actor and runtime, implements robust checkpoint utilities with atomic staging, and includes comprehensive tests. The review feedback recommends enhancing the robustness of the checkpoint utilities by using the non-interactive -n flag with all sudo commands to prevent potential hangs in automated environments, and catching broader OSError exceptions during file ownership copying to prevent unexpected crashes.

Comment on lines +68 to +69
cmd = ["sudo", "cp", "-a", os.path.join(src, "."), dst]
res = subprocess.run(cmd, capture_output=True, text=True)

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 running sudo in a background process or automated script (like a Ray worker), it can hang indefinitely if passwordless sudo is not configured, as it will wait for a password prompt on stdin. To prevent this, use the -n (non-interactive) flag so that sudo fails immediately with an error instead of hanging.

Suggested change
cmd = ["sudo", "cp", "-a", os.path.join(src, "."), dst]
res = subprocess.run(cmd, capture_output=True, text=True)
cmd = ["sudo", "-n", "cp", "-a", os.path.join(src, "."), dst]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in b2748dc (in #66471, which this PR is stacked on): every sudo call in checkpoint_utils now passes -n.

Comment on lines +76 to +79
subprocess.run(
["sudo", "find", dst, "-name", pat, "-delete"],
capture_output=True,
)

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

Similarly, use the -n (non-interactive) flag with sudo here to prevent the command from hanging indefinitely if passwordless sudo is not configured.

Suggested change
subprocess.run(
["sudo", "find", dst, "-name", pat, "-delete"],
capture_output=True,
)
subprocess.run(
["sudo", "-n", "find", dst, "-name", pat, "-delete"],
capture_output=True,
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in b2748dc, together with the other sudo calls.

Comment on lines +444 to +466
subprocess.run(
["sudo", "chown", f"{uid}:{gid}", *paths_to_harden],
capture_output=True,
)
subprocess.run(
["sudo", "chown", "-R", f"{uid}:{gid}", self.state_dir],
capture_output=True,
)
for path in paths_to_harden:
if os.path.isdir(path):
subprocess.run(
["sudo", "chmod", dir_mode, path],
capture_output=True,
)
elif os.path.isfile(path):
subprocess.run(
["sudo", "chmod", file_mode, path],
capture_output=True,
)
subprocess.run(
["sudo", "chmod", "-R", state_mode, self.state_dir],
capture_output=True,
)

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

All sudo commands executed in harden_permissions should use the -n (non-interactive) flag to prevent the Ray worker from hanging indefinitely if passwordless sudo is not configured.

            subprocess.run(
                ["sudo", "-n", "chown", f"{uid}:{gid}", *paths_to_harden],
                capture_output=True,
            )
            subprocess.run(
                ["sudo", "-n", "chown", "-R", f"{uid}:{gid}", self.state_dir],
                capture_output=True,
            )
            for path in paths_to_harden:
                if os.path.isdir(path):
                    subprocess.run(
                        ["sudo", "-n", "chmod", dir_mode, path],
                        capture_output=True,
                    )
                elif os.path.isfile(path):
                    subprocess.run(
                        ["sudo", "-n", "chmod", file_mode, path],
                        capture_output=True,
                    )
            subprocess.run(
                ["sudo", "-n", "chmod", "-R", state_mode, self.state_dir],
                capture_output=True,
            )

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in b2748dc: all sudo calls in harden_permissions pass -n, and the permissions test asserts it.

Comment on lines +44 to +48
try:
st = os.lstat(src_path)
os.lchown(dst_path, st.st_uid, st.st_gid)
except FileNotFoundError:
continue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Catching OSError instead of just FileNotFoundError is more robust here, as os.lstat or os.lchown could raise other OS-level errors (such as PermissionError) which would otherwise crash the checkpoint process.

Suggested change
try:
st = os.lstat(src_path)
os.lchown(dst_path, st.st_uid, st.st_gid)
except FileNotFoundError:
continue
try:
st = os.lstat(src_path)
os.lchown(dst_path, st.st_uid, st.st_gid)
except OSError:
continue

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Keeping this narrow on purpose. FileNotFoundError covers an entry that has no counterpart, which is expected. Any other failure (e.g. lchown refused) means a guest file would keep the wrong owner. Swallowing it would bring back the silent ownership bug this code fixes, while raising fails the checkpoint cleanly: the sandbox is restored in place and the error is reported.

sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
Address review feedback from @gemini-code-assist on ray-project#67485, about code
that lives in this PR:

- checkpoint_utils.py: every sudo call (the copy fallback in copy_fs_tree
  and the chown/chmod calls in harden_permissions) passes -n, so a Ray
  worker without passwordless sudo fails fast instead of hanging on a
  password prompt.
  ray-project#67485 (comment)
  ray-project#67485 (comment)
  ray-project#67485 (comment)

Signed-off-by: Sunny Song <[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.

Stale Bugbot comment from a previous run.

@sunnylovestiramisu
sunnylovestiramisu force-pushed the sandbox-checkpoint-remote branch from 623e93a to fb2da6b Compare October 27, 2026 16:46
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
- __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]>

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

sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
Address review feedback from @gemini-code-assist on ray-project#67485, about code
that lives in this PR:

- checkpoint_utils.py: every sudo call (the copy fallback in copy_fs_tree
  and the chown/chmod calls in harden_permissions) passes -n, so a Ray
  worker without passwordless sudo fails fast instead of hanging on a
  password prompt.
  ray-project#67485 (comment)
  ray-project#67485 (comment)
  ray-project#67485 (comment)

Signed-off-by: Sunny Song <[email protected]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
- __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]>
@sunnylovestiramisu
sunnylovestiramisu force-pushed the sandbox-checkpoint-remote branch from 4903614 to f3ca43c Compare October 27, 2026 17:12
@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Oct 27, 2026
andrewsykim pushed a commit that referenced this pull request Oct 27, 2026
…nsc (#66471)

## Description

This PR introduces native **Checkpoint, Restore, Pause, and Resume**
capabilities to Ray Sandboxes (`ray.experimental.sandbox`), leveraging
gVisor's underlying `runsc checkpoint`, `runsc restore`, `runsc pause`,
and `runsc resume` mechanisms.

### Why is this needed?

Instantiating a fresh container sandbox from scratch for every
exploration step incurs substantial cold-start overhead (hundreds of
milliseconds to seconds). Furthermore, complex RL agents, code execution
environments, and LLM rollouts need efficient primitives to fork
environments and manage resource consumption:

1. **Parallel Branching for Tree Search (e.g. MCTS, Speculative
Decoding):**
- A golden base sandbox is initialized and warmed up once with heavy
dependencies, caches, or repository clones.
- Point-in-time snapshots are captured while keeping the parent sandbox
running (`leave_running=True`).
- Multiple parallel child sandboxes can be restored with low latency (<
10ms), achieving **> 30x faster startup** with full copy-on-write state
isolation across exploration branches.
2. **Cold Suspend & Resume for Multi-Turn Rollouts (Resource Reclaim):**
- Idle sandboxes waiting for long external LLM inference or human
feedback can be checkpointed to disk and stopped
(`leave_running=False`), **freeing 100% of host RAM and CPU**.
   - The environment can later be resumed with low latency on demand.
3. **In-Memory Concurrency Throttling (`pause()` / `resume()`):**
- Halts sandbox scheduling in-place without disk I/O, allowing CPU
yielding and rate-limiting while keeping guest memory hot in host RAM.

---

## Scope after the review split

As suggested in
[review](#66471 (review)),
this PR now covers node-local checkpoint/restore and pause/resume only.
Two follow-ups take the rest:

- #67485 adds `remote=True`, which restores checkpoints from shared
storage on any node. It's stacked on this PR.
- #67484 makes EROFS image builds reproducible (fixed UUID and build
time, extended inodes), so a restore works on another node or after the
cached image is rebuilt. It's independent of this PR.

In this PR, `sandbox.restore()` always pins the restored actor to the
node that took the checkpoint, and reserves the checkpointed CPU and
memory. A restore over a different build of the image fails with a clear
error instead of a gVisor panic.

**Tests:** `TEST_SANDBOX=1 pytest python/ray/experimental/sandbox/tests/
--ignore=python/ray/experimental/sandbox/tests/test_sandbox.py` gave 270
passed, 21 failed. The 21 failures are identical on `master` on the same
machine, which lacks `mkfs.erofs` and `runsc`. `pre-commit run --files
<changed files>` passes.

**Follow-ups, not in this PR:**
- A Modal-style snapshot-handle API on top of `CheckpointPath`.
- Snapshot RPCs and `SandboxHost` support in the SDK facade.

This change was prepared with AI assistance and reviewed by the author.

---

## Related issues

- Related to Ray Enhancement Proposal:
`reps/2026-09-24-ray-sandboxing-checkpoint-restore.md`
(ray-project/enhancements#77)
- Follow-up to Ray Sandboxing base implementation
(`reps/2026-07-14-ray-sandboxing.md`).

---

## Key Additions & Changes

1. **High-Level API (`ray.experimental.sandbox`)**:
- `sandbox.restore(checkpoint_path, ...)`: Instantiates a new `Sandbox`
actor from a saved checkpoint bundle.
- `Sandbox.checkpoint.remote(checkpoint_path=..., leave_running=True)`:
Captures sandbox state to disk. If `checkpoint_path=None`, Ray
automatically generates a default path under
`/tmp/ray/sandbox/checkpoints/<sandbox_id>-<uuid>`.
`leave_running=False` stops the sandbox to reclaim host memory.
- `Sandbox.pause.remote()` / `Sandbox.resume.remote()`: Directly
controls guest CPU thread execution in-place via `runsc pause` and
`runsc resume`.
- `Sandbox.get_status.remote()`: Returns operational status (`RUNNING`,
`PAUSED`, `TERMINATED`).
2. **Low-Level Interface (`SandboxRuntime` & `GVisorSandboxBackend`)**:
- Added `checkpoint_sandbox()`, `restore_sandbox()`, `pause_sandbox()`,
and `resume_sandbox()` across `base.py`, `runtime.py`, and `gvisor.py`.
- Manifest creation (`manifest.json`): Preserves base image config,
environment variables, working directories, OCI transforms, and resource
allocations.
- Filesystem snapshotting: Persists upper copy-on-write overlay layers
and writable workdirs while safely ignoring ephemeral runtime backing
files (e.g. `.gvisor.filestore*`).
- Privilege management: Handled permission propagation and rootful
container operations (`rootless=False`).
3. **Documentation & Unit Tests**:
- Updated documentation in `doc/source/core/sandboxes.md` clarifying
tree-search branching vs. suspend/resume rollouts.
- Unit tests in `python/ray/experimental/sandbox/tests/test_sandbox.py`
and `python/ray/experimental/sandbox/tests/test_sandbox_runtime.py`
covering status tracking, pause/resume forwarding, and
checkpoint/restore parameter validation. Formatted and validated against
`ruff` and `black`.

---

## Usage Example

```python
import ray
from ray.experimental import sandbox
from ray.experimental.sandbox.backend.base import SandboxStatus

ray.init()

# ======================================================================
# 1. Branching Workflow (Tree Search, MCTS)
# ======================================================================
# Warm up base sandbox (requires rootless=False)
base_sb = sandbox.create(
    image="python:3.10-slim",
    rootless=False,
    workdir="/workspace",
)
ray.get(base_sb.exec.remote("python3 -c 'import math; print(\"Environment warmed!\")'"))

# Checkpoint state to local disk / SSD (leave_running=True keeps parent sandbox running)
checkpoint_path = ray.get(base_sb.checkpoint.remote("/tmp/ray/checkpoints/base_snap"))

# Fast restore parallel branches (< 10ms startup)
branch_1 = sandbox.restore(checkpoint_path)
branch_2 = sandbox.restore(checkpoint_path)

# Execute independently without cross-branch pollution
res1 = ray.get(branch_1.exec.remote("echo 'branch 1' > /workspace/branch.txt && cat /workspace/branch.txt"))
res2 = ray.get(branch_2.exec.remote("echo 'branch 2' > /workspace/branch.txt && cat /workspace/branch.txt"))
print("Branch 1:", res1.stdout.strip())  # Output: branch 1
print("Branch 2:", res2.stdout.strip())  # Output: branch 2

# ======================================================================
# 2. In-Memory Pause and Resume (CPU Throttling / Concurrency Yielding)
# ======================================================================
# Freeze sandbox execution in-place (keeps memory hot in RAM, 0 disk I/O)
ray.get(base_sb.pause.remote())
print("Status:", ray.get(base_sb.get_status.remote()))  # SandboxStatus.PAUSED

# Resume sandbox execution
ray.get(base_sb.resume.remote())
print("Status:", ray.get(base_sb.get_status.remote()))  # SandboxStatus.RUNNING

# ======================================================================
# 3. Cold Suspend & Resume (Freeing 100% Host Memory Between Turns)
# ======================================================================
# Checkpoint and stop sandbox to release all RAM/CPU during multi-turn LLM waits
suspend_path = ray.get(base_sb.checkpoint.remote(leave_running=False))

# Later, resume execution when next turn is ready
resumed_sb = sandbox.restore(suspend_path)
res_resumed = ray.get(resumed_sb.exec.remote("python3 -c 'print(\"Resumed successfully!\")'"))
print(res_resumed.stdout.strip())

# Clean up
ray.get(branch_1.delete.remote())
ray.get(branch_2.delete.remote())
ray.get(resumed_sb.delete.remote())

```

## Testing & Verification

### 1. Unit Tests
- test_sandbox_runtime.py: Verified pause and resume delegation, and
checkpoint / restore config forwarding to the backend.
- test_sandbox.py: Verified actor wrapper methods, status tracking
(RUNNING -> PAUSED -> RUNNING), and file I/O.

### 2. End-to-End Testing on Live Kubernetes Cluster (GKE)

- Scenario A (User Code Snippet): Verified warmup, explicit checkpoint
to /tmp/ray/checkpoints/base_snap, restore of 2 parallel branches, and
verified branch filesystem isolation.
- Scenario B (Default Path Generation): Verified auto-generation of
checkpoint directory under
/tmp/ray/sandbox/checkpoints/<sandbox_id>-<uuid> when
checkpoint_path=None, verified directory contents (manifest.json,
config.json, state/, fs/), and restored child sandbox.
- Scenario C (Multi-Branch Parallel Restoration Benchmark): Checkpointed
complex pre-warmed state to disk with leave_running=False (cold
suspend), restored concurrent forks, and verified branch mutation
independence.
- Scenario D (Pause & Resume Lifecycle): Verified in-memory status
transitions (RUNNING -> PAUSED -> RUNNING), confirmed CPU pause in
0.023s, resume in 0.021s, and verified filesystem state persistence and
python command execution post-resume.

- Ray job:
https://gist.github.com/sunnylovestiramisu/7cd607727920186b6759a69967d7d37d
- Logs:
https://gist.github.com/sunnylovestiramisu/9d051ddff7bce1ec475f7992ff276818

---------

Signed-off-by: Sunny Song <[email protected]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
- __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]>
@sunnylovestiramisu
sunnylovestiramisu force-pushed the sandbox-checkpoint-remote branch from f3ca43c to 8da3ebe Compare October 27, 2026 20:13
@sunnylovestiramisu
sunnylovestiramisu force-pushed the sandbox-checkpoint-remote branch from 8da3ebe to 9ef3888 Compare October 27, 2026 22:31
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
- __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]>
justinyeh1995 pushed a commit to justinyeh1995/ray that referenced this pull request Oct 28, 2026
…nsc (ray-project#66471)

## Description

This PR introduces native **Checkpoint, Restore, Pause, and Resume**
capabilities to Ray Sandboxes (`ray.experimental.sandbox`), leveraging
gVisor's underlying `runsc checkpoint`, `runsc restore`, `runsc pause`,
and `runsc resume` mechanisms.

### Why is this needed?

Instantiating a fresh container sandbox from scratch for every
exploration step incurs substantial cold-start overhead (hundreds of
milliseconds to seconds). Furthermore, complex RL agents, code execution
environments, and LLM rollouts need efficient primitives to fork
environments and manage resource consumption:

1. **Parallel Branching for Tree Search (e.g. MCTS, Speculative
Decoding):**
- A golden base sandbox is initialized and warmed up once with heavy
dependencies, caches, or repository clones.
- Point-in-time snapshots are captured while keeping the parent sandbox
running (`leave_running=True`).
- Multiple parallel child sandboxes can be restored with low latency (<
10ms), achieving **> 30x faster startup** with full copy-on-write state
isolation across exploration branches.
2. **Cold Suspend & Resume for Multi-Turn Rollouts (Resource Reclaim):**
- Idle sandboxes waiting for long external LLM inference or human
feedback can be checkpointed to disk and stopped
(`leave_running=False`), **freeing 100% of host RAM and CPU**.
   - The environment can later be resumed with low latency on demand.
3. **In-Memory Concurrency Throttling (`pause()` / `resume()`):**
- Halts sandbox scheduling in-place without disk I/O, allowing CPU
yielding and rate-limiting while keeping guest memory hot in host RAM.

---

## Scope after the review split

As suggested in
[review](ray-project#66471 (review)),
this PR now covers node-local checkpoint/restore and pause/resume only.
Two follow-ups take the rest:

- ray-project#67485 adds `remote=True`, which restores checkpoints from shared
storage on any node. It's stacked on this PR.
- ray-project#67484 makes EROFS image builds reproducible (fixed UUID and build
time, extended inodes), so a restore works on another node or after the
cached image is rebuilt. It's independent of this PR.

In this PR, `sandbox.restore()` always pins the restored actor to the
node that took the checkpoint, and reserves the checkpointed CPU and
memory. A restore over a different build of the image fails with a clear
error instead of a gVisor panic.

**Tests:** `TEST_SANDBOX=1 pytest python/ray/experimental/sandbox/tests/
--ignore=python/ray/experimental/sandbox/tests/test_sandbox.py` gave 270
passed, 21 failed. The 21 failures are identical on `master` on the same
machine, which lacks `mkfs.erofs` and `runsc`. `pre-commit run --files
<changed files>` passes.

**Follow-ups, not in this PR:**
- A Modal-style snapshot-handle API on top of `CheckpointPath`.
- Snapshot RPCs and `SandboxHost` support in the SDK facade.

This change was prepared with AI assistance and reviewed by the author.

---

## Related issues

- Related to Ray Enhancement Proposal:
`reps/2026-09-24-ray-sandboxing-checkpoint-restore.md`
(ray-project/enhancements#77)
- Follow-up to Ray Sandboxing base implementation
(`reps/2026-07-14-ray-sandboxing.md`).

---

## Key Additions & Changes

1. **High-Level API (`ray.experimental.sandbox`)**:
- `sandbox.restore(checkpoint_path, ...)`: Instantiates a new `Sandbox`
actor from a saved checkpoint bundle.
- `Sandbox.checkpoint.remote(checkpoint_path=..., leave_running=True)`:
Captures sandbox state to disk. If `checkpoint_path=None`, Ray
automatically generates a default path under
`/tmp/ray/sandbox/checkpoints/<sandbox_id>-<uuid>`.
`leave_running=False` stops the sandbox to reclaim host memory.
- `Sandbox.pause.remote()` / `Sandbox.resume.remote()`: Directly
controls guest CPU thread execution in-place via `runsc pause` and
`runsc resume`.
- `Sandbox.get_status.remote()`: Returns operational status (`RUNNING`,
`PAUSED`, `TERMINATED`).
2. **Low-Level Interface (`SandboxRuntime` & `GVisorSandboxBackend`)**:
- Added `checkpoint_sandbox()`, `restore_sandbox()`, `pause_sandbox()`,
and `resume_sandbox()` across `base.py`, `runtime.py`, and `gvisor.py`.
- Manifest creation (`manifest.json`): Preserves base image config,
environment variables, working directories, OCI transforms, and resource
allocations.
- Filesystem snapshotting: Persists upper copy-on-write overlay layers
and writable workdirs while safely ignoring ephemeral runtime backing
files (e.g. `.gvisor.filestore*`).
- Privilege management: Handled permission propagation and rootful
container operations (`rootless=False`).
3. **Documentation & Unit Tests**:
- Updated documentation in `doc/source/core/sandboxes.md` clarifying
tree-search branching vs. suspend/resume rollouts.
- Unit tests in `python/ray/experimental/sandbox/tests/test_sandbox.py`
and `python/ray/experimental/sandbox/tests/test_sandbox_runtime.py`
covering status tracking, pause/resume forwarding, and
checkpoint/restore parameter validation. Formatted and validated against
`ruff` and `black`.

---

## Usage Example

```python
import ray
from ray.experimental import sandbox
from ray.experimental.sandbox.backend.base import SandboxStatus

ray.init()

# ======================================================================
# 1. Branching Workflow (Tree Search, MCTS)
# ======================================================================
# Warm up base sandbox (requires rootless=False)
base_sb = sandbox.create(
    image="python:3.10-slim",
    rootless=False,
    workdir="/workspace",
)
ray.get(base_sb.exec.remote("python3 -c 'import math; print(\"Environment warmed!\")'"))

# Checkpoint state to local disk / SSD (leave_running=True keeps parent sandbox running)
checkpoint_path = ray.get(base_sb.checkpoint.remote("/tmp/ray/checkpoints/base_snap"))

# Fast restore parallel branches (< 10ms startup)
branch_1 = sandbox.restore(checkpoint_path)
branch_2 = sandbox.restore(checkpoint_path)

# Execute independently without cross-branch pollution
res1 = ray.get(branch_1.exec.remote("echo 'branch 1' > /workspace/branch.txt && cat /workspace/branch.txt"))
res2 = ray.get(branch_2.exec.remote("echo 'branch 2' > /workspace/branch.txt && cat /workspace/branch.txt"))
print("Branch 1:", res1.stdout.strip())  # Output: branch 1
print("Branch 2:", res2.stdout.strip())  # Output: branch 2

# ======================================================================
# 2. In-Memory Pause and Resume (CPU Throttling / Concurrency Yielding)
# ======================================================================
# Freeze sandbox execution in-place (keeps memory hot in RAM, 0 disk I/O)
ray.get(base_sb.pause.remote())
print("Status:", ray.get(base_sb.get_status.remote()))  # SandboxStatus.PAUSED

# Resume sandbox execution
ray.get(base_sb.resume.remote())
print("Status:", ray.get(base_sb.get_status.remote()))  # SandboxStatus.RUNNING

# ======================================================================
# 3. Cold Suspend & Resume (Freeing 100% Host Memory Between Turns)
# ======================================================================
# Checkpoint and stop sandbox to release all RAM/CPU during multi-turn LLM waits
suspend_path = ray.get(base_sb.checkpoint.remote(leave_running=False))

# Later, resume execution when next turn is ready
resumed_sb = sandbox.restore(suspend_path)
res_resumed = ray.get(resumed_sb.exec.remote("python3 -c 'print(\"Resumed successfully!\")'"))
print(res_resumed.stdout.strip())

# Clean up
ray.get(branch_1.delete.remote())
ray.get(branch_2.delete.remote())
ray.get(resumed_sb.delete.remote())

```

## Testing & Verification

### 1. Unit Tests
- test_sandbox_runtime.py: Verified pause and resume delegation, and
checkpoint / restore config forwarding to the backend.
- test_sandbox.py: Verified actor wrapper methods, status tracking
(RUNNING -> PAUSED -> RUNNING), and file I/O.

### 2. End-to-End Testing on Live Kubernetes Cluster (GKE)

- Scenario A (User Code Snippet): Verified warmup, explicit checkpoint
to /tmp/ray/checkpoints/base_snap, restore of 2 parallel branches, and
verified branch filesystem isolation.
- Scenario B (Default Path Generation): Verified auto-generation of
checkpoint directory under
/tmp/ray/sandbox/checkpoints/<sandbox_id>-<uuid> when
checkpoint_path=None, verified directory contents (manifest.json,
config.json, state/, fs/), and restored child sandbox.
- Scenario C (Multi-Branch Parallel Restoration Benchmark): Checkpointed
complex pre-warmed state to disk with leave_running=False (cold
suspend), restored concurrent forks, and verified branch mutation
independence.
- Scenario D (Pause & Resume Lifecycle): Verified in-memory status
transitions (RUNNING -> PAUSED -> RUNNING), confirmed CPU pause in
0.023s, resume in 0.021s, and verified filesystem state persistence and
python command execution post-resume.

- Ray job:
https://gist.github.com/sunnylovestiramisu/7cd607727920186b6759a69967d7d37d
- Logs:
https://gist.github.com/sunnylovestiramisu/9d051ddff7bce1ec475f7992ff276818

---------

Signed-off-by: Sunny Song <[email protected]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 2, 2026
…nsc (ray-project#66471)

## Description

This PR introduces native **Checkpoint, Restore, Pause, and Resume**
capabilities to Ray Sandboxes (`ray.experimental.sandbox`), leveraging
gVisor's underlying `runsc checkpoint`, `runsc restore`, `runsc pause`,
and `runsc resume` mechanisms.

### Why is this needed?

Instantiating a fresh container sandbox from scratch for every
exploration step incurs substantial cold-start overhead (hundreds of
milliseconds to seconds). Furthermore, complex RL agents, code execution
environments, and LLM rollouts need efficient primitives to fork
environments and manage resource consumption:

1. **Parallel Branching for Tree Search (e.g. MCTS, Speculative
Decoding):**
- A golden base sandbox is initialized and warmed up once with heavy
dependencies, caches, or repository clones.
- Point-in-time snapshots are captured while keeping the parent sandbox
running (`leave_running=True`).
- Multiple parallel child sandboxes can be restored with low latency (<
10ms), achieving **> 30x faster startup** with full copy-on-write state
isolation across exploration branches.
2. **Cold Suspend & Resume for Multi-Turn Rollouts (Resource Reclaim):**
- Idle sandboxes waiting for long external LLM inference or human
feedback can be checkpointed to disk and stopped
(`leave_running=False`), **freeing 100% of host RAM and CPU**.
   - The environment can later be resumed with low latency on demand.
3. **In-Memory Concurrency Throttling (`pause()` / `resume()`):**
- Halts sandbox scheduling in-place without disk I/O, allowing CPU
yielding and rate-limiting while keeping guest memory hot in host RAM.

---

## Scope after the review split

As suggested in
[review](ray-project#66471 (review)),
this PR now covers node-local checkpoint/restore and pause/resume only.
Two follow-ups take the rest:

- ray-project#67485 adds `remote=True`, which restores checkpoints from shared
storage on any node. It's stacked on this PR.
- ray-project#67484 makes EROFS image builds reproducible (fixed UUID and build
time, extended inodes), so a restore works on another node or after the
cached image is rebuilt. It's independent of this PR.

In this PR, `sandbox.restore()` always pins the restored actor to the
node that took the checkpoint, and reserves the checkpointed CPU and
memory. A restore over a different build of the image fails with a clear
error instead of a gVisor panic.

**Tests:** `TEST_SANDBOX=1 pytest python/ray/experimental/sandbox/tests/
--ignore=python/ray/experimental/sandbox/tests/test_sandbox.py` gave 270
passed, 21 failed. The 21 failures are identical on `master` on the same
machine, which lacks `mkfs.erofs` and `runsc`. `pre-commit run --files
<changed files>` passes.

**Follow-ups, not in this PR:**
- A Modal-style snapshot-handle API on top of `CheckpointPath`.
- Snapshot RPCs and `SandboxHost` support in the SDK facade.

This change was prepared with AI assistance and reviewed by the author.

---

## Related issues

- Related to Ray Enhancement Proposal:
`reps/2026-09-24-ray-sandboxing-checkpoint-restore.md`
(ray-project/enhancements#77)
- Follow-up to Ray Sandboxing base implementation
(`reps/2026-07-14-ray-sandboxing.md`).

---

## Key Additions & Changes

1. **High-Level API (`ray.experimental.sandbox`)**:
- `sandbox.restore(checkpoint_path, ...)`: Instantiates a new `Sandbox`
actor from a saved checkpoint bundle.
- `Sandbox.checkpoint.remote(checkpoint_path=..., leave_running=True)`:
Captures sandbox state to disk. If `checkpoint_path=None`, Ray
automatically generates a default path under
`/tmp/ray/sandbox/checkpoints/<sandbox_id>-<uuid>`.
`leave_running=False` stops the sandbox to reclaim host memory.
- `Sandbox.pause.remote()` / `Sandbox.resume.remote()`: Directly
controls guest CPU thread execution in-place via `runsc pause` and
`runsc resume`.
- `Sandbox.get_status.remote()`: Returns operational status (`RUNNING`,
`PAUSED`, `TERMINATED`).
2. **Low-Level Interface (`SandboxRuntime` & `GVisorSandboxBackend`)**:
- Added `checkpoint_sandbox()`, `restore_sandbox()`, `pause_sandbox()`,
and `resume_sandbox()` across `base.py`, `runtime.py`, and `gvisor.py`.
- Manifest creation (`manifest.json`): Preserves base image config,
environment variables, working directories, OCI transforms, and resource
allocations.
- Filesystem snapshotting: Persists upper copy-on-write overlay layers
and writable workdirs while safely ignoring ephemeral runtime backing
files (e.g. `.gvisor.filestore*`).
- Privilege management: Handled permission propagation and rootful
container operations (`rootless=False`).
3. **Documentation & Unit Tests**:
- Updated documentation in `doc/source/core/sandboxes.md` clarifying
tree-search branching vs. suspend/resume rollouts.
- Unit tests in `python/ray/experimental/sandbox/tests/test_sandbox.py`
and `python/ray/experimental/sandbox/tests/test_sandbox_runtime.py`
covering status tracking, pause/resume forwarding, and
checkpoint/restore parameter validation. Formatted and validated against
`ruff` and `black`.

---

## Usage Example

```python
import ray
from ray.experimental import sandbox
from ray.experimental.sandbox.backend.base import SandboxStatus

ray.init()

# ======================================================================
# 1. Branching Workflow (Tree Search, MCTS)
# ======================================================================
# Warm up base sandbox (requires rootless=False)
base_sb = sandbox.create(
    image="python:3.10-slim",
    rootless=False,
    workdir="/workspace",
)
ray.get(base_sb.exec.remote("python3 -c 'import math; print(\"Environment warmed!\")'"))

# Checkpoint state to local disk / SSD (leave_running=True keeps parent sandbox running)
checkpoint_path = ray.get(base_sb.checkpoint.remote("/tmp/ray/checkpoints/base_snap"))

# Fast restore parallel branches (< 10ms startup)
branch_1 = sandbox.restore(checkpoint_path)
branch_2 = sandbox.restore(checkpoint_path)

# Execute independently without cross-branch pollution
res1 = ray.get(branch_1.exec.remote("echo 'branch 1' > /workspace/branch.txt && cat /workspace/branch.txt"))
res2 = ray.get(branch_2.exec.remote("echo 'branch 2' > /workspace/branch.txt && cat /workspace/branch.txt"))
print("Branch 1:", res1.stdout.strip())  # Output: branch 1
print("Branch 2:", res2.stdout.strip())  # Output: branch 2

# ======================================================================
# 2. In-Memory Pause and Resume (CPU Throttling / Concurrency Yielding)
# ======================================================================
# Freeze sandbox execution in-place (keeps memory hot in RAM, 0 disk I/O)
ray.get(base_sb.pause.remote())
print("Status:", ray.get(base_sb.get_status.remote()))  # SandboxStatus.PAUSED

# Resume sandbox execution
ray.get(base_sb.resume.remote())
print("Status:", ray.get(base_sb.get_status.remote()))  # SandboxStatus.RUNNING

# ======================================================================
# 3. Cold Suspend & Resume (Freeing 100% Host Memory Between Turns)
# ======================================================================
# Checkpoint and stop sandbox to release all RAM/CPU during multi-turn LLM waits
suspend_path = ray.get(base_sb.checkpoint.remote(leave_running=False))

# Later, resume execution when next turn is ready
resumed_sb = sandbox.restore(suspend_path)
res_resumed = ray.get(resumed_sb.exec.remote("python3 -c 'print(\"Resumed successfully!\")'"))
print(res_resumed.stdout.strip())

# Clean up
ray.get(branch_1.delete.remote())
ray.get(branch_2.delete.remote())
ray.get(resumed_sb.delete.remote())

```

## Testing & Verification

### 1. Unit Tests
- test_sandbox_runtime.py: Verified pause and resume delegation, and
checkpoint / restore config forwarding to the backend.
- test_sandbox.py: Verified actor wrapper methods, status tracking
(RUNNING -> PAUSED -> RUNNING), and file I/O.

### 2. End-to-End Testing on Live Kubernetes Cluster (GKE)

- Scenario A (User Code Snippet): Verified warmup, explicit checkpoint
to /tmp/ray/checkpoints/base_snap, restore of 2 parallel branches, and
verified branch filesystem isolation.
- Scenario B (Default Path Generation): Verified auto-generation of
checkpoint directory under
/tmp/ray/sandbox/checkpoints/<sandbox_id>-<uuid> when
checkpoint_path=None, verified directory contents (manifest.json,
config.json, state/, fs/), and restored child sandbox.
- Scenario C (Multi-Branch Parallel Restoration Benchmark): Checkpointed
complex pre-warmed state to disk with leave_running=False (cold
suspend), restored concurrent forks, and verified branch mutation
independence.
- Scenario D (Pause & Resume Lifecycle): Verified in-memory status
transitions (RUNNING -> PAUSED -> RUNNING), confirmed CPU pause in
0.023s, resume in 0.021s, and verified filesystem state persistence and
python command execution post-resume.

- Ray job:
https://gist.github.com/sunnylovestiramisu/7cd607727920186b6759a69967d7d37d
- Logs:
https://gist.github.com/sunnylovestiramisu/9d051ddff7bce1ec475f7992ff276818

---------

Signed-off-by: Sunny Song <[email protected]>
Signed-off-by: Pawel Beza <[email protected]>
Co-authored-by: Copilot <[email protected]>
Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
@sunnylovestiramisu
sunnylovestiramisu force-pushed the sandbox-checkpoint-remote branch from 9ef3888 to fa15db2 Compare November 2, 2026 18:05
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 2, 2026
- __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]>

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

@sunnylovestiramisu
sunnylovestiramisu force-pushed the sandbox-checkpoint-remote branch from fa15db2 to b342250 Compare November 3, 2026 01:09
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 3, 2026
- __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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 23, 2026
- __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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 23, 2026
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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 23, 2026
- __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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 24, 2026
- __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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 24, 2026
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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 24, 2026
- __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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 25, 2026
- __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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 25, 2026
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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 25, 2026
- __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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 25, 2026
- __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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 25, 2026
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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 25, 2026
- __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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 26, 2026
- __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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 26, 2026
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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 26, 2026
- __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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 26, 2026
- __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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 26, 2026
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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Nov 26, 2026
- __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]>
…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

community-contribution Contributed by the community core Issues that should be addressed in Ray Core sandbox

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants