Repository navigation
[core][sandbox] Add checkpoint/restore, pause/resume support using runsc - #66471
Conversation
There was a problem hiding this comment.
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.
| 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")) |
There was a problem hiding this comment.
is the checkpoint path required? I think we can make it optional and use some default path that includes the sandbox ID
ae5b400 to
88f7e92
Compare
|
|
||
| ray.init() | ||
|
|
||
| # 1. Start a base sandbox (must run with rootless=False) |
There was a problem hiding this comment.
Why rootless=False, does gVisor not support checkpoint / restore without root?
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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
88f7e92 to
fd4ec23
Compare
fd4ec23 to
f40b82b
Compare
|
The presubmit failed tests are not modified with this PR's change at all. Rebasing it and see if it passes. |
|
/retest |
f40b82b to
564fda6
Compare
564fda6 to
a45c7db
Compare
| @@ -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): | |||
There was a problem hiding this comment.
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?
| @@ -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): | |||
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
do we really need leave_running if there are separate methods for pause / resume?
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
is this still preserving the OCI spec transformation in the base sandbox?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
Is it enough to just set this in-memory? I got the impression from previous conversations that gVisor actually has a pause capability?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
oh my bad I think I just misread the code earlier
a45c7db to
e8c56b6
Compare
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
left a comment
There was a problem hiding this comment.
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", |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| ```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()) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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], |
There was a problem hiding this comment.
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.
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]>
fd7f208 to
c052884
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
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) |
There was a problem hiding this comment.
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)
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)." | ||
| ) |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit c052884. Configure here.
…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]>
…restore 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]>
b2748dc to
1be01ff
Compare
…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]>
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]>
…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]>
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]>
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]>
…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]>


Description
This PR introduces native Checkpoint, Restore, Pause, and Resume capabilities to Ray Sandboxes (
ray.experimental.sandbox), leveraging gVisor's underlyingrunsc checkpoint,runsc restore,runsc pause, andrunsc resumemechanisms.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:
leave_running=True).leave_running=False), freeing 100% of host RAM and CPU.pause()/resume()):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:
remote=True, which restores checkpoints from shared storage on any node. It's stacked on 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.pygave 270 passed, 21 failed. The 21 failures are identical onmasteron the same machine, which lacksmkfs.erofsandrunsc.pre-commit run --files <changed files>passes.Follow-ups, not in this PR:
CheckpointPath.SandboxHostsupport in the SDK facade.This change was prepared with AI assistance and reviewed by the author.
Related issues
reps/2026-09-24-ray-sandboxing-checkpoint-restore.md(REP: Ray Sandboxing with Checkpoint and Restore enhancements#77)reps/2026-07-14-ray-sandboxing.md).Key Additions & Changes
ray.experimental.sandbox):sandbox.restore(checkpoint_path, ...): Instantiates a newSandboxactor from a saved checkpoint bundle.Sandbox.checkpoint.remote(checkpoint_path=..., leave_running=True): Captures sandbox state to disk. Ifcheckpoint_path=None, Ray automatically generates a default path under/tmp/ray/sandbox/checkpoints/<sandbox_id>-<uuid>.leave_running=Falsestops the sandbox to reclaim host memory.Sandbox.pause.remote()/Sandbox.resume.remote(): Directly controls guest CPU thread execution in-place viarunsc pauseandrunsc resume.Sandbox.get_status.remote(): Returns operational status (RUNNING,PAUSED,TERMINATED).SandboxRuntime&GVisorSandboxBackend):checkpoint_sandbox(),restore_sandbox(),pause_sandbox(), andresume_sandbox()acrossbase.py,runtime.py, andgvisor.py.manifest.json): Preserves base image config, environment variables, working directories, OCI transforms, and resource allocations..gvisor.filestore*).rootless=False).doc/source/core/sandboxes.mdclarifying tree-search branching vs. suspend/resume rollouts.python/ray/experimental/sandbox/tests/test_sandbox.pyandpython/ray/experimental/sandbox/tests/test_sandbox_runtime.pycovering status tracking, pause/resume forwarding, and checkpoint/restore parameter validation. Formatted and validated againstruffandblack.Usage Example
Testing & Verification
1. Unit Tests
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>- 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