Skip to content

[core][sandbox] Add checkpoint/restore, pause/resume support using runsc - #66471

Merged
andrewsykim merged 8 commits into
ray-project:masterfrom
sunnylovestiramisu:checkpoint
Oct 27, 2026
Merged

andrewsykim merged 8 commits into
ray-project:masterfrom
sunnylovestiramisu:checkpoint

Conversation

@sunnylovestiramisu

@sunnylovestiramisu sunnylovestiramisu commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

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, this PR now covers node-local checkpoint/restore and pause/resume only. Two follow-ups take the rest:

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


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

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)

@sunnylovestiramisu
sunnylovestiramisu requested review from a team as code owners September 24, 2026 20:03

@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 checkpoint, restore, pause, and resume capabilities for Ray Sandboxes using gVisor's runsc backend, along with corresponding documentation and unit tests. The review feedback highlights several critical issues: a TypeError will occur during pause/resume operations due to missing timeout_seconds parameters in the backend signatures; configuration overrides are silently ignored during sandbox restoration; shutil.copytree will fail with an uncaught PermissionError when copying root-owned files in non-rootless mode; and the checkpoint timeout parameter is not properly propagated or enforced in the subprocess execution.

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

Comment thread doc/source/ray-core/sandboxes.md Outdated
ray.get(base_sb.exec.remote("python3 -c 'import math; print(\"Environment warmed!\")'"))

# 3. Take a snapshot checkpoint of the sandbox state to local disk or SSD
checkpoint_path = ray.get(base_sb.checkpoint.remote("/tmp/ray/checkpoints/base_snap"))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

is the checkpoint path required? I think we can make it optional and use some default path that includes the sandbox ID

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

@ray-gardener ray-gardener Bot added docs An issue or change related to documentation core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Sep 25, 2026

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.


ray.init()

# 1. Start a base sandbox (must run with rootless=False)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why rootless=False, does gVisor not support checkpoint / restore without root?

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.

https://github.com/google/gvisor/blob/master/runsc/cmd/restore.go#L129-L131

If it is Rootless, it does not execute runsc restore. So if the original checkpoint was taken from a rootless container, and you try to restore it with rootless=False, gVisor Sentry encounters a mismatch between the rootless user namespace state serialized in the checkpoint and the rootful environment.

So just making it completely rootless=False.


# 3. Take a snapshot checkpoint of the sandbox state to local disk or SSD
# (checkpoint_path is optional; defaults to /tmp/ray/sandbox/checkpoints/<sandbox_id>-<uuid>)
checkpoint_path = ray.get(base_sb.checkpoint.remote())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do you think Ray needs to make a clear distinction between "checkpoint" and "pause"? Are there use-cases where i want to checkpoint and pause the sandbox as separate operations? @xyuzh @pcmoritz curious about your thoughts here as well

@sunnylovestiramisu sunnylovestiramisu Oct 1, 2026 •

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.

We need to eventually. Pause/resume and checkpoint/restore should be separate cases because:

If a user just wants to pause execution for a second while waiting for a network event, doing a full disk checkpoint causes unnecessary disk I/O, wear, and 60ms+ latency. Conversely, if a user wants to fork 5 sandboxes, pause is incapable of creating replicas.

Summary:

  • pause() / resume() — Fine-grained CPU Throttling / Waiting for External Events
  • checkpoint() / restore() — State Branching, Migration, & Memory Reclaim

@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

Copy link
Copy Markdown
Contributor Author

The presubmit failed tests are not modified with this PR's change at all.

Rebasing it and see if it passes.

@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

Copy link
Copy Markdown
Contributor Author

/retest

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

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

Comment thread doc/source/core/sandboxes.md Outdated
@@ -276,6 +276,52 @@ print(result.stdout)
ray.get(pool.close.remote())
```

### Checkpoint and restore sandboxes

For tree-search algorithms (such as Monte Carlo Tree Search in agentic RL) or complex multi-turn LLM reasoning rollouts, starting a fresh container sandbox from scratch for every branching trial adds latency. You can checkpoint a running sandbox to a snapshot bundle on disk and restore multiple child sandboxes almost instantaneously (< 10ms):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: the branching use-case for tree search and the suspend/resume for multi-turn rollouts are two separate use-cases, can you try to make it clearer here?

Comment thread doc/source/core/sandboxes.md Outdated
@@ -276,6 +276,52 @@ print(result.stdout)
ray.get(pool.close.remote())
```

### Checkpoint and restore sandboxes

For tree-search algorithms (such as Monte Carlo Tree Search in agentic RL) or complex multi-turn LLM reasoning rollouts, starting a fresh container sandbox from scratch for every branching trial adds latency. You can checkpoint a running sandbox to a snapshot bundle on disk and restore multiple child sandboxes almost instantaneously (< 10ms):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: I would avoid the term "almost instantaneously", use "with low latency" or something similar

self,
sandbox_id: str,
checkpoint_path: Optional[str] = None,
leave_running: bool = True,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

do we really need leave_running if there are separate methods for pause / resume?

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.

They are still different use cases

  • pause() / resume()

    • Does NOT free host memory. Remains in RAM. Guest memory pages are pinned in host RAM.
    • Use case: Short-term concurrency throttling / CPU yielding (e.g. rate-limiting, temporary wait while keeping sandbox hot).
  • checkpoint(leave_running=True) with runsc checkpoint --leave-running

    • State dumped to disk; base process keeps running.
    • Use case: branch out parallel sandboxes from a running golden base sandbox without interrupting it.
  • checkpoint(leave_running=False) with runsc checkpoint (omits --leave-running) + teardown

    • Dumped to disk and process is terminated/unloaded.
    • Use case: multi-turn agent rollouts waiting for external LLM inference, user input, or migrating state across nodes/tasks.

Do we want to support them all?

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.

They are still different use cases

  • pause() / resume()

    • Does NOT free host memory. Remains in RAM. Guest memory pages are pinned in host RAM.
    • Use case: Short-term concurrency throttling / CPU yielding (e.g. rate-limiting, temporary wait while keeping sandbox hot).
  • checkpoint(leave_running=True) with runsc checkpoint --leave-running

    • State dumped to disk; base process keeps running.
    • Use case: branch out parallel sandboxes from a running golden base sandbox without interrupting it.
  • checkpoint(leave_running=False) with runsc checkpoint (omits --leave-running) + teardown

    • Dumped to disk and process is terminated/unloaded.
    • Use case: multi-turn agent rollouts waiting for external LLM inference, user input, or migrating state across nodes/tasks.

Do we want to support them all?

capabilities=config.capabilities,
network=config.network,
dns=config.dns,
_oci_spec_transform_fn=config._oci_spec_transform_fn,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

is this still preserving the OCI spec transformation in the base sandbox?

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.

This is for some advanced workloads, users might need to configure low-level runtime options such as custom host mounts, Linux capabilities, or custom network and DNS settings. Use the _oci_spec_transform_fn parameter to inspect and modify the generated Open Container Initiative (OCI) runtime specification dictionary before Ray passes it to gVisor (runsc).

An example will be: Fine-tuning OS-level limits inside the gVisor sandbox (e.g. increasing max open file descriptors RLIMIT_NOFILE)

def increase_nofile_limit(spec: dict) -> dict:
    # Ensure process.rlimits is populated
    process = spec.setdefault("process", {})
    rlimits = process.setdefault("rlimits", [])
    
    # Set max open file descriptors to 65536
    rlimits.append({
        "type": "RLIMIT_NOFILE",
        "hard": 65536,
        "soft": 65536,
    })
    return spec

sb = sandbox.create(
    image="python:3.10-slim",
    _oci_spec_transform_fn=increase_nofile_limit,
)

For regular users it defaults to None.

)
if res.returncode != 0:
raise SandboxError(f"Failed to pause sandbox '{sandbox_id}': {res.stderr}")
meta["status"] = SandboxStatus.PAUSED

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is it enough to just set this in-memory? I got the impression from previous conversations that gVisor actually has a pause capability?

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.

It is NOT just setting an in-memory flag. It is actually invoking gVisor's native CLI command a few line above:

pause_args = self._runsc_base_args(config) + ["pause", sandbox_id]
res = subprocess.run(
    pause_args, capture_output=True, text=True, timeout=timeout_seconds
)

Ray keeps a local metadata dictionary self._sandbox_metadata on the node for quick state lookups (such as responding to sb.status() without constantly spawning a subprocess to call runsc state).
Updating meta["status"] happens only after runsc pause exits with returncode 0. If gVisor fails to pause, it raises SandboxError and the in-memory state is never changed.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

oh my bad I think I just misread the code earlier

@sunnylovestiramisu sunnylovestiramisu changed the title [core][sandbox] Add checkpoint and restore support using runsc [core][sandbox] Add checkpoint/restore, pause/resume support using runsc Oct 7, 2026
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 26, 2026
Review: ray-project#66471 (comment)

- gvisor.py: checkpoint_sandbox no longer passes --leave-running. runsc
  checkpoint now stops the sandbox; its launch process exits and is
  reaped, and leave_running=True restores the sandbox in place from the
  new image (same ID, bundle, owner file, cgroup and egress allowlist)
  under a new launch process. A failed resume raises instead of logging,
  and the sandbox reads as TERMINATED rather than stuck in PAUSED. A
  checkpoint that fails after runsc stopped the sandbox restores it from
  the staged image. The filesystem copy now runs while the sandbox is
  stopped, so it matches the memory image without a pause/resume. (item 1)
- image_utils.py: stop zeroing file mtimes (_owner_filter, mkfs.erofs
  -T0). Builds keep a stable layout across nodes through
  -Eforce-inode-extended and the fixed UUID. (item 2)
- gvisor.py, checkpoint_utils.py: restore generates the bundle's
  config.json, resolv.conf and hosts with prepare_oci_bundle from the
  restored config instead of copying the source's config.json, so env,
  capabilities, dns, disk, cidr_allowlist and _oci_spec_transform_fn
  overrides apply (the guest-writable hosts file is kept). The manifest
  records disk and cidr_allowlist. Overrides of image, network, readonly
  and (on a readonly rootfs) workdir, which the saved memory state
  depends on, raise a SandboxError instead of being ignored. (item 3)
- gvisor.py, checkpoint_utils.py: the manifest records the checkpoint's
  compression. restore_sandbox's background now defaults to None, which
  uses runsc restore --background only for uncompressed checkpoints, and
  background=True on a compressed checkpoint raises. Unknown compression
  values are rejected instead of silently ignored. (item 4)

Rebase onto master: restore now goes through the same provisioning and
launch path as create (_provision, _launch_sandbox, _run_until_running,
_build_run_command with a restore image), so restored sandboxes get an
owner file, cgroup limits, the egress ruleset, the gofer network
namespace, interrupt immunity and owner-tied process group like created
ones. _build_restore_command and the unused _copy_fs_tree are removed.

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

@xyuzh xyuzh left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the rework. Stopping the sandbox for the copy and then restoring it in place fixes the file/memory race from my last pass, and the handle now carries the node and resources. Several things still look broken on the real runsc path, inline. The first one breaks the cross-node restore from the last commit. Given the size, I'd split remote=True and the image_utils change into their own PRs, each with a two-node test.

# independent of when mkfs runs, as a fixed UUID keeps the
# superblock; files keep their mtimes.
"-Eforce-inode-extended",
"-U00000000-0000-0000-0000-000000000000",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think this makes two builds match. Without -T, mkfs.erofs writes the current time into the superblock's build time, and gVisor's erofs afterLoad panics with "superblock mismatch detected on restore" when any superblock field differs (pkg/sentry/fsimpl/erofs/save_restore.go). So a restore on another node, or on the same node after the image was evicted and rebuilt, should panic. -T0 --mkfs-time pins only the build time and keeps file mtimes, but --mkfs-time needs erofs-utils 1.8, above _MKFS_EROFS_MIN_VERSION. Recording the image digest in the manifest would also catch a tag that moved between checkpoint and restore. Did the GKE run restore on a second node?

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.

Agreed, the build time alone breaks it. The build changes now live in #67484, with -T0 --mkfs-time when mkfs.erofs supports it (erofs-utils 1.8+, so the 1.7 minimum stays), plus the fixed UUID and extended inodes. Mtimes are kept. This PR keeps a guard (dfdb8cd): each checkpoint records a hash of the source image's EROFS superblock, and restore refuses a build whose superblock differs (moved tag, eviction and rebuild, or another node's build) with a clear error before runsc runs. No second-node GKE restore yet; I'll run one with #67484 + #67485.

"workdir": config.workdir,
"capabilities": config.capabilities,
"dns": config.dns,
"cidr_allowlist": config.cidr_allowlist,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This saves the allowlist the sandbox was created with, not the current one: set_egress_allowlist only updates meta["egress_allowlist"]. Narrow a public sandbox to ["10.0.0.5/32"], checkpoint it, and every restored child gets the original back, which is the whole public internet if cidr_allowlist was None. The in-place restore reads meta and is fine.

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.

Fixed in dfdb8cd: the manifest now saves meta["egress_allowlist"], the allowlist in force, so a list narrowed with set_egress_allowlist is what restored children get. Added a test.

return False

# Attempt atomic swap
if os.path.exists(self.target_path):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Any existing directory at the target is moved to .old.* and rmtree'd, as root, with no check that it's a checkpoint, so checkpoint.remote("/data/project") wipes /data/project. I'd refuse a non-empty dir unless it already has a manifest.json.

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.

Fixed in dfdb8cd: StagedCheckpoint refuses a non-empty target that has no manifest.json, before runsc runs. Only an earlier checkpoint gets replaced. Added a test.

# and the mounts, root filesystem mode and network stack that the guest
# kernel was saved with. A restore can't change them. ``workdir`` is one of
# them only on a readonly rootfs, where it is a host-backed mount.
_RESTORE_IMMUTABLE_FIELDS = ("image", "network", "readonly", "workdir", "rootless")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

capabilities and disk belong here too. runsc restores with --restore-spec-validation=enforce by default, which rejects a changed process.capabilities and any changed dev.gvisor.* annotation, and disk becomes dev.gvisor.spec.rootfs.options. Both are listed as supported overrides in sandboxes.md:379. Same for a source created with an _oci_spec_transform_fn that adds rlimits or mounts, since the transform isn't saved.

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.

Fixed in dfdb8cd: capabilities and disk are now immutable on restore, next to image/network/readonly/workdir. The manifest records whether the source used an _oci_spec_transform_fn, and restore requires one in that case. sandboxes.md is updated.

Comment thread doc/source/core/sandboxes.md Outdated
```python
# Checkpoint and terminate the running sandbox to free resources between turns
checkpoint_path = ray.get(sb.checkpoint.remote(leave_running=False))
ray.get(sb.delete.remote())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

delete() removes the sandbox but not the actor, so the source actor keeps its CPU and memory reserved. restore() then hard-pins the new actor to the same node with the same request, so on a full node it stays pending. To actually free the resources this needs ray.kill(sb), or checkpoint(leave_running=False) could exit the actor itself.

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.

Fixed in dfdb8cd: the suspend example now does ray.kill(sb) after checkpoint(leave_running=False) and explains why.

checkpoint_args,
capture_output=True,
text=True,
timeout=timeout_seconds,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What happens when this hits the 30 s default? subprocess.run kills the runsc checkpoint client, but I think the save keeps going inside the sandbox and stops it when done. stopped is still False here, so nothing restores it and the staging dir gets deleted, leaving neither the source nor a checkpoint. A few GiB written to NFS could easily take longer than 30 s.

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.

Good catch. In dfdb8cd, on TimeoutExpired we wait up to timeout_seconds again for the launch process to exit, since the save stops the sandbox when it's done. If it exits, the checkpoint completes normally. If not, the staging directory the save is writing to is kept (not deleted) and SandboxTimeoutError names its path. Tests cover both.

capture_output=True,
)
subprocess.run(
["sudo", "chmod", "-R", "u+rwX,go-rwx", self.staging_path],

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Modes look right now. Ownership still changes, though: copytree as root makes root-owned copies, and the sudo path runs chown -R over everything. So a guest user's workdir files (exec(user=...)) come back owned by someone else after restore, and that user can't write them.

sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
Review: ray-project#66471 (comment)

- gvisor.py: checkpoint_sandbox no longer passes --leave-running. runsc
  checkpoint now stops the sandbox; its launch process exits and is
  reaped, and leave_running=True restores the sandbox in place from the
  new image (same ID, bundle, owner file, cgroup and egress allowlist)
  under a new launch process. A failed resume raises instead of logging,
  and the sandbox reads as TERMINATED rather than stuck in PAUSED. A
  checkpoint that fails after runsc stopped the sandbox restores it from
  the staged image. The filesystem copy now runs while the sandbox is
  stopped, so it matches the memory image without a pause/resume. (item 1)
- image_utils.py: stop zeroing file mtimes (_owner_filter, mkfs.erofs
  -T0). Builds keep a stable layout across nodes through
  -Eforce-inode-extended and the fixed UUID. (item 2)
- gvisor.py, checkpoint_utils.py: restore generates the bundle's
  config.json, resolv.conf and hosts with prepare_oci_bundle from the
  restored config instead of copying the source's config.json, so env,
  capabilities, dns, disk, cidr_allowlist and _oci_spec_transform_fn
  overrides apply (the guest-writable hosts file is kept). The manifest
  records disk and cidr_allowlist. Overrides of image, network, readonly
  and (on a readonly rootfs) workdir, which the saved memory state
  depends on, raise a SandboxError instead of being ignored. (item 3)
- gvisor.py, checkpoint_utils.py: the manifest records the checkpoint's
  compression. restore_sandbox's background now defaults to None, which
  uses runsc restore --background only for uncompressed checkpoints, and
  background=True on a compressed checkpoint raises. Unknown compression
  values are rejected instead of silently ignored. (item 4)

Rebase onto master: restore now goes through the same provisioning and
launch path as create (_provision, _launch_sandbox, _run_until_running,
_build_run_command with a restore image), so restored sandboxes get an
owner file, cgroup limits, the egress ruleset, the gofer network
namespace, interrupt immunity and owner-tied process group like created
ones. _build_restore_command and the unused _copy_fs_tree are removed.

Signed-off-by: Sunny Song <[email protected]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
Review: ray-project#66471 (review)

- image_utils.py, gvisor.py: pin the EROFS superblock's build time with
  -T0 --mkfs-time when mkfs.erofs supports it (erofs-utils 1.8+), which
  keeps file mtimes. Checkpoints record the superblock fingerprint of the
  source's image, and restore refuses a build whose superblock differs
  (a moved tag, or a rebuild by an older mkfs.erofs) with a clear error
  instead of letting gVisor panic on "superblock mismatch".
  ray-project#66471 (comment)
- gvisor.py, checkpoint_utils.py: the manifest saves the egress allowlist
  in force (meta["egress_allowlist"], updated by set_egress_allowlist),
  not the one the sandbox was created with.
  ray-project#66471 (comment)
- checkpoint_utils.py: StagedCheckpoint refuses a non-empty target
  directory without a manifest.json instead of moving it aside and
  deleting it.
  ray-project#66471 (comment)
- checkpoint_utils.py: capabilities and disk can't be overridden on
  restore (runsc's restore spec validation compares process.capabilities
  and the dev.gvisor.* annotations). A source created with an
  _oci_spec_transform_fn is recorded in the manifest, and restore requires
  one.
  ray-project#66471 (comment)
- sandboxes.md: the suspend example kills the actor with ray.kill(sb), so
  its CPU and memory reservation is released before restore.
  ray-project#66471 (comment)
- gvisor.py: when runsc checkpoint times out, wait as long again for the
  save (which the timeout can't cancel) to stop the sandbox, then finish
  the checkpoint. If it's still running, keep the staging directory the
  save writes to and raise SandboxTimeoutError, instead of deleting it
  under the save.
  ray-project#66471 (comment)
- checkpoint_utils.py: copy_fs_tree keeps owners when run as root, and
  harden_permissions no longer chowns fs/ recursively, so guest users'
  files keep their owners through checkpoint and restore.
  ray-project#66471 (comment)

Signed-off-by: Sunny Song <[email protected]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
Splits this PR as suggested in review
(ray-project#66471 (review)):
this PR keeps node-local checkpoint/restore and pause/resume, and two
follow-up PRs, each with its own tests, take the rest:

- remote=True (checkpoints on shared storage restored on any node):
  removed here from sandbox.restore(), Sandbox, SandboxRuntime, the
  backends, CheckpointPath and the manifest. Restore always pins the
  actor to the node that took the checkpoint, and the backend rejects a
  restore on any other node.
- Reproducible EROFS builds (fixed UUID and build time, extended inodes)
  in image_utils.build_erofs_image and the image cache format bump:
  removed here. The restore-time superblock check stays, so a restore
  over a rebuilt image fails with a clear error instead of a gVisor panic.

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.

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit c052884. Configure here.

ignore_fn = shutil.ignore_patterns(*ignore_patterns) if ignore_patterns else None
try:
shutil.copytree(src, dst, dirs_exist_ok=True, ignore=ignore_fn, symlinks=True)
_copy_ownership(src, dst)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Restore loses guest file ownership

Medium Severity

copy_fs_tree only rewrites owners after copytree when the process is root, and only falls back to sudo cp -a when a permission error occurs. A non-root worker that can read guest files (typical 0644 workdir output from exec(user=...)) therefore succeeds with copytree and leaves those files owned by the worker. After restore, that guest user can no longer write them. sudo cp -a would have kept the original owners, but that path is skipped whenever the copy succeeds.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c052884. Configure here.

f"'{checkpoint_node_id}', but restore is running on node "
f"'{current_node_id}'. Checkpoints are node-local: restore on the "
"node that took it (sandbox.restore() schedules there)."
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Outside-Ray checkpoints fail same-node restore

Low Severity

get_current_node_id stores a hostname when Ray is not initialized, but restore_sandbox compares that value with Ray's hex node id after ray.init(). The strings never match, so a checkpoint taken with SandboxRuntime outside Ray is rejected even on the same machine. The high-level restore() path also treats the hostname as a hard NodeAffinitySchedulingStrategy target, which can leave the actor pending forever.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c052884. Configure here.

sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
…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]>
Support pausing and resuming sandbox processes in-place via runsc pause
and runsc resume. Adds PAUSED to SandboxStatus, exposes pause() and resume()
on SandboxRuntime and Sandbox actor handle, and adds documentation and unit tests.

Signed-off-by: Sunny Song <[email protected]>
Support state snapshotting and fast restoration for Ray sandboxes leveraging
runsc checkpoint and restore. Provides atomic staging swap, permission hardening,
filesystem copying, top-level sandbox.restore API, and unit tests.

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

- gvisor.py: checkpoint_sandbox no longer passes --leave-running. runsc
  checkpoint now stops the sandbox; its launch process exits and is
  reaped, and leave_running=True restores the sandbox in place from the
  new image (same ID, bundle, owner file, cgroup and egress allowlist)
  under a new launch process. A failed resume raises instead of logging,
  and the sandbox reads as TERMINATED rather than stuck in PAUSED. A
  checkpoint that fails after runsc stopped the sandbox restores it from
  the staged image. The filesystem copy now runs while the sandbox is
  stopped, so it matches the memory image without a pause/resume. (item 1)
- image_utils.py: stop zeroing file mtimes (_owner_filter, mkfs.erofs
  -T0). Builds keep a stable layout across nodes through
  -Eforce-inode-extended and the fixed UUID. (item 2)
- gvisor.py, checkpoint_utils.py: restore generates the bundle's
  config.json, resolv.conf and hosts with prepare_oci_bundle from the
  restored config instead of copying the source's config.json, so env,
  capabilities, dns, disk, cidr_allowlist and _oci_spec_transform_fn
  overrides apply (the guest-writable hosts file is kept). The manifest
  records disk and cidr_allowlist. Overrides of image, network, readonly
  and (on a readonly rootfs) workdir, which the saved memory state
  depends on, raise a SandboxError instead of being ignored. (item 3)
- gvisor.py, checkpoint_utils.py: the manifest records the checkpoint's
  compression. restore_sandbox's background now defaults to None, which
  uses runsc restore --background only for uncompressed checkpoints, and
  background=True on a compressed checkpoint raises. Unknown compression
  values are rejected instead of silently ignored. (item 4)

Rebase onto master: restore now goes through the same provisioning and
launch path as create (_provision, _launch_sandbox, _run_until_running,
_build_run_command with a restore image), so restored sandboxes get an
owner file, cgroup limits, the egress ruleset, the gofer network
namespace, interrupt immunity and owner-tied process group like created
ones. _build_restore_command and the unused _copy_fs_tree are removed.

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

- image_utils.py, gvisor.py: pin the EROFS superblock's build time with
  -T0 --mkfs-time when mkfs.erofs supports it (erofs-utils 1.8+), which
  keeps file mtimes. Checkpoints record the superblock fingerprint of the
  source's image, and restore refuses a build whose superblock differs
  (a moved tag, or a rebuild by an older mkfs.erofs) with a clear error
  instead of letting gVisor panic on "superblock mismatch".
  ray-project#66471 (comment)
- gvisor.py, checkpoint_utils.py: the manifest saves the egress allowlist
  in force (meta["egress_allowlist"], updated by set_egress_allowlist),
  not the one the sandbox was created with.
  ray-project#66471 (comment)
- checkpoint_utils.py: StagedCheckpoint refuses a non-empty target
  directory without a manifest.json instead of moving it aside and
  deleting it.
  ray-project#66471 (comment)
- checkpoint_utils.py: capabilities and disk can't be overridden on
  restore (runsc's restore spec validation compares process.capabilities
  and the dev.gvisor.* annotations). A source created with an
  _oci_spec_transform_fn is recorded in the manifest, and restore requires
  one.
  ray-project#66471 (comment)
- sandboxes.md: the suspend example kills the actor with ray.kill(sb), so
  its CPU and memory reservation is released before restore.
  ray-project#66471 (comment)
- gvisor.py: when runsc checkpoint times out, wait as long again for the
  save (which the timeout can't cancel) to stop the sandbox, then finish
  the checkpoint. If it's still running, keep the staging directory the
  save writes to and raise SandboxTimeoutError, instead of deleting it
  under the save.
  ray-project#66471 (comment)
- checkpoint_utils.py: copy_fs_tree keeps owners when run as root, and
  harden_permissions no longer chowns fs/ recursively, so guest users'
  files keep their owners through checkpoint and restore.
  ray-project#66471 (comment)

Signed-off-by: Sunny Song <[email protected]>
Splits this PR as suggested in review
(ray-project#66471 (review)):
this PR keeps node-local checkpoint/restore and pause/resume, and two
follow-up PRs, each with its own tests, take the rest:

- remote=True (checkpoints on shared storage restored on any node):
  removed here from sandbox.restore(), Sandbox, SandboxRuntime, the
  backends, CheckpointPath and the manifest. Restore always pins the
  actor to the node that took the checkpoint, and the backend rejects a
  restore on any other node.
- Reproducible EROFS builds (fixed UUID and build time, extended inodes)
  in image_utils.build_erofs_image and the image cache format bump:
  removed here. The restore-time superblock check stays, so a restore
  over a rebuilt image fails with a clear error instead of a gVisor panic.

Signed-off-by: Sunny Song <[email protected]>
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
…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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
Split out of ray-project#66471 in review
(ray-project#66471 (review)).

gVisor restores a checkpointed sandbox only onto an EROFS root filesystem
whose superblock matches the one it was saved with, and panics otherwise
("superblock mismatch detected on restore"). Two builds of the same image
differ today: mkfs.erofs writes a random UUID and the current time into
the superblock, and picks compact or extended inodes depending on that
time. So a checkpoint can't be restored on another node, or on the same
node once its cached image is evicted and rebuilt.

build_erofs_image now passes:
- -Eforce-inode-extended, so the layout doesn't depend on when mkfs runs
  (extended inodes carry each file's own mtime);
- a fixed all-zero UUID;
- -T0 --mkfs-time when mkfs.erofs supports it (erofs-utils 1.8+), which
  fixes only the superblock's build time and keeps file mtimes. The
  minimum stays 1.7, where builds share the layout but not the build time.

The image cache format goes to 4 so cached images are rebuilt this way.
mkfs.erofs --help is now probed once per binary (_mkfs_erofs_help).

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

@xyuzh xyuzh left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the PR, LGTM!

@andrewsykim
andrewsykim merged commit b5f0e08 into ray-project:master Oct 27, 2026
6 checks passed
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
…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]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
Split out of ray-project#66471 in review
(ray-project#66471 (review)).

gVisor restores a checkpointed sandbox only onto an EROFS root filesystem
whose superblock matches the one it was saved with, and panics otherwise
("superblock mismatch detected on restore"). Two builds of the same image
differ today: mkfs.erofs writes a random UUID and the current time into
the superblock, and picks compact or extended inodes depending on that
time. So a checkpoint can't be restored on another node, or on the same
node once its cached image is evicted and rebuilt.

build_erofs_image now passes:
- -Eforce-inode-extended, so the layout doesn't depend on when mkfs runs
  (extended inodes carry each file's own mtime);
- a fixed all-zero UUID;
- -T0 --mkfs-time when mkfs.erofs supports it (erofs-utils 1.8+), which
  fixes only the superblock's build time and keeps file mtimes. The
  minimum stays 1.7, where builds share the layout but not the build time.

The image cache format goes to 4 so cached images are rebuilt this way.
mkfs.erofs --help is now probed once per binary (_mkfs_erofs_help).

Signed-off-by: Sunny Song <[email protected]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
Split out of ray-project#66471 in review
(ray-project#66471 (review)).

gVisor restores a checkpointed sandbox only onto an EROFS root filesystem
whose superblock matches the one it was saved with, and panics otherwise
("superblock mismatch detected on restore"). Two builds of the same image
differ today: mkfs.erofs writes a random UUID and the current time into
the superblock, and picks compact or extended inodes depending on that
time. So a checkpoint can't be restored on another node, or on the same
node once its cached image is evicted and rebuilt.

build_erofs_image now passes:
- -Eforce-inode-extended, so the layout doesn't depend on when mkfs runs
  (extended inodes carry each file's own mtime);
- a fixed all-zero UUID;
- -T0 --mkfs-time when mkfs.erofs supports it (erofs-utils 1.8+), which
  fixes only the superblock's build time and keeps file mtimes. The
  minimum stays 1.7, where builds share the layout but not the build time.

The image cache format goes to 4 so cached images are rebuilt this way.
mkfs.erofs --help is now probed once per binary (_mkfs_erofs_help).

Signed-off-by: Sunny Song <[email protected]>
sunnylovestiramisu added a commit to sunnylovestiramisu/ray that referenced this pull request Oct 27, 2026
…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]>
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 docs An issue or change related to documentation go add ONLY when ready to merge, run all tests sandbox

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants