Skip to content

[core][sandbox] Keep sandboxes booted with SandboxRuntime warm pools - #67077

Open
xyuzh wants to merge 25 commits into
ray-project:masterfrom
xyuzh:sandbox-runtime-warm-pool
Open

xyuzh wants to merge 25 commits into
ray-project:masterfrom
xyuzh:sandbox-runtime-warm-pool

Conversation

@xyuzh

@xyuzh xyuzh commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Description

Actors that drive SandboxRuntime directly pay a gVisor boot on every create: about half a second each when 48 start at once on 16 cores.

This PR adds warm pools (runtime.py):

  • SandboxRuntime(warm_pool=[...]) takes profiles (create() arguments plus a size) and keeps that many sandboxes booted per profile.
  • A create matching a profile's boot-time arguments takes a booted sandbox. The backend then stores the create's config (assign_config), so the create's env applies to every command, get_config() and checkpoints see it, and its TTL starts at the create. A matching create that finds none ready boots cold with the profile's env too, so a create's env doesn't depend on load, and every spelling of an image matches its profile.
  • A profile keeps at most size sandboxes, ready or in use. A taken sandbox keeps its slot until it's deleted (by delete, its TTL, or a checkpoint that stops it), and only then does a new one boot in it, so a pool never grows past its size. Creates that find none ready boot cold, outside the pool.
  • Boots run four at a time on a thread pool. wait_for_warm_pool() waits until every slot holds a sandbox, ready or in use. close() deletes the ready ones and waits for the boots under way; taken ones stay, and deleting them boots nothing. A profile whose boot fails pauses for a second, then twice as long after each further failure up to 30 s, and a timer refills it.
  • Pools never hand out a sandbox that died while it waited, because the gVisor backend's get_status reports one whose launch process exited ([core][sandbox] Enforce CPU and memory limits with host cgroups #66932).

Without warm_pool, nothing changes. The docs get a warm-pool section.

Measured on 2026-10-14 against base 00a3adb (16 cores, cached image, medians of 5 runs; 3 for the last row):

creates/s p50 per create
master, 48 at once 79/s 0.480 s
This PR, no pool, 48 at once 79/s 0.472 s
This PR, 48 at once from a pool of 48 3,206/s 2.8 ms
This PR, 96 at once from a pool of 96 2,258/s 4.5 ms

Related issues

Split out of #66821. Its warm pools for the gRPC facade come later, stacked on #67078. #67728 (stacked on this PR) publishes pools to a store, so callers on other actors can find ready sandboxes.

Additional information

  • Not a duplicate: only [core][sandbox] Make the gRPC facade fast under bursts of sandboxes #66821 matched "sandbox warm pool". The boot key also covers master's disk ([core][sandbox] Cap a sandbox's writable rootfs with disk #66988), cidr_allowlist ([core][sandbox] Default network="public" egress to the public internet and enforce allowlists #66359), mounts, gpu_ids and oom_score_adj ([core][sandbox] Make oom-score-adj configurable for each sandbox #67688), which test_boot_key_covers_every_boot_time_field enforces. [core][sandbox] Skip repeated work on each sandbox create #67076 edits the same lines of SandboxRuntime.create.
  • Tests: two tests boot real sandboxes: a pooled create with its env (through the runtime and the backend), then a delete that boots a new sandbox in its slot; and get_status after runsc run died. Twenty-three fake-backend tests cover the pool logic: the config handoff (and a sandbox that can't be handed over, which frees its slot and boots cold), boots on four threads, a failed boot's retry, the size bound (also with 8 threads creating and deleting), refills after TTL and checkpoint deletes (also a failed checkpoint, which frees the slot only if the backend deleted the sandbox), and close.
  • Tested at 8b92c6b (master a83e55e merged in), in a privileged container (aarch64, runsc release-20261026.0, erofs-utils 1.9.4): TEST_SANDBOX=1 pytest tests/test_{gvisor_backend,checkpoint_restore,image_manager,image_utils,sandbox_runtime,overlayfs,sandbox_config,cgroup,resource_limits}.py: 498 passed, 25 skipped, 2 failed (master: 473 passed, and the same two GPU tests fail, since that container's Ray predates get_cdi_kind). pre-commit passes.
  • At scale, on a 352-CPU NVIDIA Vera node: one runtime with a pool of 500 handed 500 creates made at once (64 threads) their sandboxes at a create p50 of 0.13 ms (p99 4.6 ms) and ran a first command in each within 1.1 s; cold, the same burst takes 34 s. The pool never held more than 500, and refilled the 500 slots in 39 s after the deletes.
  • I used Claude Code to help write and test this change.

@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 a warm-pool feature for Ray sandboxes, allowing pre-booted gVisor sandboxes to be kept ready to significantly reduce startup latency. It includes documentation, the implementation of a _WarmPool manager in the runtime, and corresponding unit tests. Feedback on the changes suggests adding a fallback check for os.waitid in the _exited helper function to prevent potential AttributeErrors on non-Linux platforms where the module might be imported or mocked.

Comment on lines +91 to +105
def _exited(proc: Optional[subprocess.Popen]) -> bool:
"""Whether ``proc`` has exited, without reaping it.

Its pid is the sandbox's process group id, which delete_sandbox signals;
reaping it earlier would free the id for an unrelated process group.
"""
if proc is None:
return False
if proc.returncode is not None:
return True
try:
status = os.waitid(os.P_PID, proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT)
except ChildProcessError:
return True
return status is not None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The _exited function uses os.waitid and os.WNOWAIT, which are not available on all platforms (e.g., Windows). While the gVisor sandbox runtime is Linux-only, the module might still be imported or mocked on other platforms during local development, testing, or documentation generation. Adding a fallback check using hasattr(os, 'waitid') prevents potential AttributeErrors on unsupported platforms.

Suggested change
def _exited(proc: Optional[subprocess.Popen]) -> bool:
"""Whether ``proc`` has exited, without reaping it.
Its pid is the sandbox's process group id, which delete_sandbox signals;
reaping it earlier would free the id for an unrelated process group.
"""
if proc is None:
return False
if proc.returncode is not None:
return True
try:
status = os.waitid(os.P_PID, proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT)
except ChildProcessError:
return True
return status is not None
def _exited(proc: Optional[subprocess.Popen]) -> bool:
"""Whether proc has exited, without reaping it.
Its pid is the sandbox's process group id, which delete_sandbox signals;
reaping it earlier would free the id for an unrelated process group.
"""
if proc is None:
return False
if proc.returncode is not None:
return True
if not hasattr(os, "waitid"):
return proc.poll() is not None
try:
status = os.waitid(os.P_PID, proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT)
except ChildProcessError:
return True
return status is not None

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this: the gVisor backend only runs on Linux, and os.waitid and os.WNOWAIT exist there (and on macOS). They're looked up when _exited runs, not at import, so the module still imports anywhere.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correction to my reply: on macOS, os.waitid only exists from Python 3.13. The answer stays the same, since _exited only runs in the Linux backend and looks the name up when it runs, not at import.

@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-gardener ray-gardener Bot added docs An issue or change related to documentation core Issues that should be addressed in Ray Core labels Oct 15, 2026
@xyuzh
xyuzh force-pushed the sandbox-runtime-warm-pool branch from 9e23926 to 3f35b73 Compare October 22, 2026 19:37
xyuzh added 2 commits October 22, 2026 15:01
Callers that drive SandboxRuntime directly, such as actors that create
sandboxes in bursts, pay a gVisor boot on every create.

`SandboxRuntime(warm_pool=[...])` takes profiles, each the create()
arguments of one boot configuration plus a pool `size`, and keeps that
many sandboxes booted per profile, a few boots at a time. A create
whose boot-time arguments match a profile takes a booted sandbox at
once and a replacement boots in the background. The create's `env` goes
on every command the sandbox runs, and its TTL starts at the create.
`wait_for_warm_pool()` waits for full pools, and `close()` deletes the
sandboxes the pool still holds. A profile whose boot fails boots no
replacements for 30 s, and two profiles that boot the same sandboxes
are refused.

The pool never hands out a sandbox that died while it waited, because
the gVisor backend's `get_status` reports one whose launch process
exited (ray-project#66932).

Signed-off-by: xyuzh <[email protected]>
A failed boot pauses a profile's refills for a while, and only __init__
and take() refilled. So after one failed boot during the initial fill,
nothing booted the missing sandbox again, and wait_for_warm_pool timed
out even once the pause was over and the other boots had succeeded.

wait_for_warm_pool now refills every profile while it waits. Refills
still respect the pause.

Signed-off-by: xyuzh <[email protected]>
@xyuzh
xyuzh force-pushed the sandbox-runtime-warm-pool branch from 3f35b73 to 2d06840 Compare October 22, 2026 22:05
@sunnylovestiramisu

Copy link
Copy Markdown
Contributor

Findings

Breaking / regression: nothing breaking. warm_pool is a new optional constructor argument, and without it behavior is unchanged.

  • B1 (needs-verification): when a sandbox comes from the pool, the env passed to create() is kept only in SandboxRuntime._exec_env and merged in on each exec. The backend's stored config still holds the profile's env and TTL, so two paths see the wrong env:

Design alternatives:

  • D1 (strong): when a sandbox is taken from the pool, update the backend's stored config with the create's env and TTL, instead of keeping the separate _exec_env dict. Everything then reads one source of truth, and this fixes B1.
  • D2 (moderate): the pool starts one thread per missing sandbox, all waiting on a 4-slot semaphore, and wait_for_warm_pool polls every 50 ms. A 4-worker thread pool plus a condition variable would avoid parking 96 threads and the polling. A timer could also restart refills after the 30 s failure pause.

xyuzh added 2 commits November 2, 2026 00:01
…pool

Review follow-ups:

- A sandbox taken from the warm pool booted with the profile's env and
  TTL. The backend now takes the create's config (assign_config), with
  its env on top of the boot's, and runs every command with that env.
  Sandbox.get_config(), the backend's own exec_command and checkpoints
  all see the create's config, and the runtime keeps no env of its own.
- Boots run on a 4-worker executor instead of a thread each parked on a
  semaphore, wait_for_warm_pool waits on a condition instead of polling,
  and a timer refills a profile once the pause after a failed boot is
  over. Boots still queued when one fails are skipped until then.

Signed-off-by: xyuzh <[email protected]>
@xyuzh

xyuzh commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

Thanks @sunnylovestiramisu, all three are addressed in cd5547c, on top of a master merge (b206234).

B1 and D1: done as you suggested. For a pooled sandbox, create() now calls GVisorSandboxBackend.assign_config(instance_id, cfg). The backend stores the create's config as the sandbox's config, with the create's env on top of the profile's and the create's TTL and timeout, and the runtime's _exec_env dict is gone. So Sandbox.get_config(), the backend's own exec_command and checkpoint() all read the same config. One detail: the profile's env is baked into the sandbox's OCI spec at boot, so the backend still passes the create's env on each command. Restores keep it too: an in-place restore keeps the metadata, and restore() builds the new bundle from the checkpoint's merged config. test_assigned_config_reaches_get_config_exec_and_checkpoints covers the backend path, and the real-gVisor test_runtime_warm_pool_serves_matching_creates now also checks runtime.backend.exec_command and the stored config.

D2: done. Boots run on a 4-worker ThreadPoolExecutor, and close() cancels queued boots. wait_for_warm_pool now waits on a condition that's notified when a boot ends, instead of polling. After the 30 s pause that follows a failed boot, a timer refills the profile, so a pool recovers without needing a create or a waiter. Boots still queued when one fails are skipped until then. test_warm_pool_boots_on_a_few_threads checks that 24 boots run on exactly 4 threads, and test_a_failed_boot_is_retried_once_the_pause_is_over covers the timer.

I also fixed a test-order flake in test_a_pooled_sandbox_that_died_is_deleted_not_handed_out: parallel boots fill the pool in whatever order they finish, so the test now reads that order. The runtime tests passed 60 runs in a row.

Real gVisor in a privileged container (aarch64, runsc release-20261026.0): test_{gvisor_backend,checkpoint_restore,image_manager,image_utils,sandbox_runtime,overlayfs,sandbox_config}.py 373 passed, 15 skipped (master: 361 passed, 15 skipped).

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

…t taken

A profile's size is now the number of sandboxes it holds, ready or in use.
Taking a sandbox no longer boots a replacement: its slot stays claimed
until the sandbox is deleted, by delete, its TTL, or a checkpoint that
stops it, and only then does the pool boot a new sandbox in it. So a pool
never holds more than its size, and a create that finds none ready boots
cold, outside the pool, as before.

The pool keeps one slot per sandbox: empty, booting, ready, claimed, or
deleting (a ready sandbox that died, deleted before its slot boots again).
wait_for_warm_pool waits until every slot holds a sandbox, ready or in use.
close deletes the ready sandboxes and leaves the claimed ones, whose
deletes then boot nothing. A boot that ends after close deletes its
sandbox and logs a failed delete instead of losing it in the boot thread.

Signed-off-by: xyuzh <[email protected]>
xyuzh added 3 commits November 2, 2026 22:31
…to a create

If assign_config fails after take claimed a sandbox (it died in between,
say), nothing held the sandbox's ID, so its slot stayed claimed and the
pool shrank for good. The create now deletes it, which boots a new one in
its slot, and boots cold itself.

Signed-off-by: xyuzh <[email protected]>
Signed-off-by: xyuzh <[email protected]>

# Conflicts:
#	doc/source/core/sandboxes.md
Master added SandboxConfig.gpu_ids and mounts, which are fixed when a
sandbox boots, so a create takes a pooled sandbox only if they match.

Signed-off-by: xyuzh <[email protected]>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

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

Docs review from Douglas Strodtman on the Ray docs team, assisted by Claude Code. I've read every comment here and stand behind each one.

Scope: style, grammar, and docs conventions in doc/source/core/sandboxes.md only, against Ray's writing-style guide. Technical accuracy and final approval belong to the Core maintainers. Both suggestions keep the existing claims as written and change only the wording and structure.

The new section reads well and the example is clear. My two suggestions are about readability. The main one breaks up the dense paragraph after the code block. No objection from the docs side.

Comment thread doc/source/core/sandboxes.md Resolved
Comment thread doc/source/core/sandboxes.md Resolved
xyuzh added 2 commits November 5, 2026 18:12
…point ends it

A checkpoint with leave_running=False freed the sandbox's warm-pool slot
only after checkpoint_sandbox returned. If it raised after the backend
had deleted the sandbox, or after it stopped the sandbox and couldn't
restore it, the slot stayed claimed and the profile stayed one sandbox
short. Now a failed stop-checkpoint frees the slot when the sandbox is
terminated. A sandbox that still runs keeps its slot until it's deleted.

Signed-off-by: xyuzh <[email protected]>
Applies the docs review's suggestions.

Signed-off-by: xyuzh <[email protected]>
xyuzh added 4 commits November 5, 2026 18:12
Signed-off-by: xyuzh <[email protected]>

ray-project#67688 added SandboxConfig.oom_score_adj, which the launch applies to the sandbox's processes, so a pooled sandbox can stand in only for creates that ask for the same score. test_boot_key_covers_every_boot_time_field caught it.
Microcheck build 58551 failed before it ran anything, fetching run_rayci.sh.

Signed-off-by: xyuzh <[email protected]>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

…dbox is deleted

0832f3f freed the warm-pool slot of any sandbox that a failed
stop-checkpoint left terminated. A checkpoint that stops a sandbox and
can't restore it leaves it tracked, though, with its bundle, cgroup and
image, so a replacement booted over it. Now a failed checkpoint, in
either mode, frees the slot and cancels the TTL only once the backend no
longer tracks the sandbox. A sandbox that's stopped or running keeps its
slot until it's deleted, as any sandbox that dies does.

Signed-off-by: xyuzh <[email protected]>

@xyuzh xyuzh left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks for the docs review, Douglas. @pcmoritz, code changes since your approval: 0832f3f and 8b92c6b handle a failed checkpoint's warm-pool slot (Bugbot's findings below), and 62df35c adds master's new oom_score_adj (#67688) to the warm pool's boot key, which test_boot_key_covers_every_boot_time_field caught. Master is merged in (cb2c7b1, 5a444ce), which also cleared the Read the Docs failure that came from master's docs build at the old base (fixed on master by #67741).

Comment thread doc/source/core/sandboxes.md Resolved
Comment thread doc/source/core/sandboxes.md Resolved
xyuzh added 5 commits November 8, 2026 22:46
GitHub sent no webhooks for 8b92c6b, so no checks ran on it.

Signed-off-by: xyuzh <[email protected]>
The jobs that failed in microcheck build 58569 failed only on downloads from GitHub during GitHub's incident on 2026-11-09.

Signed-off-by: xyuzh <[email protected]>
microcheck build 58575 failed before running tests: GitHub's incident on 2026-11-09 still blocked downloads from CI then. It's resolved now.

Signed-off-by: xyuzh <[email protected]>
…-pool key

ray-project#67974 made a GPU sandbox's NVIDIA_DRIVER_CAPABILITIES (from the create's
env) set runsc's --nvproxy-allowed-driver-capabilities at boot. The warm
pool treats env as per-create, so a GPU sandbox booted with the default
capabilities could serve a create that asks for profiling. The boot key
now includes that variable for GPU sandboxes; other env stays per-create.

Signed-off-by: xyuzh <[email protected]>
Comment on lines +142 to +164
def take(self, cfg: SandboxConfig) -> Optional[str]:
"""Claim a booted sandbox for ``cfg``, or return None.

The sandbox's slot stays claimed until the sandbox is deleted, so
taking one boots nothing.
"""
key = _boot_key(cfg)
if key not in self._profiles:
return None
taken = None
dead = []
with self._lock:
ready = self._ready[key]
while ready and taken is None:
slot = ready.popleft()
if slot.state != _READY: # deleted while it waited
continue
if self._runtime.get_status(slot.sandbox_id) == SandboxStatus.RUNNING:
slot.state = _CLAIMED
taken = slot.sandbox_id
else:
slot.state = _DELETING
dead.append(slot.sandbox_id)

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.

Keeping slots in _CLAIMED until delete() means once size long-running rollouts are active, ready headroom sits at 0 for subsequent arrivals even though create() already permits unbounded cold misses. Have you considered refilling on take() so size bounds standby warm headroom?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this: size bounds what a profile holds, ready or in use, and that bound is what a caller sizes against the CPUs and memory it set aside. Refilling on take would boot a sandbox for each one handed out, so a profile with size long-running sandboxes would hold twice its size. A caller that wants standby headroom beyond its running sandboxes sets a larger size, and the docs state the bound.

Comment on lines +42 to +60
return (
cfg.image,
float(cfg.cpu or 0.0),
parse_memory_bytes(cfg.memory) or 0,
cfg.workdir,
bool(cfg.rootless),
cfg.network,
tuple(cfg.dns) if cfg.dns is not None else None,
tuple(cfg.cidr_allowlist) if cfg.cidr_allowlist is not None else None,
tuple(cfg.capabilities) if cfg.capabilities is not None else None,
cfg.shell,
bool(cfg.readonly),
parse_memory_bytes(cfg.disk) or 0,
bool(cfg._ignore_cgroups),
tuple(cfg.gpu_ids or ()),
tuple(sorted((cfg.mounts or {}).items())),
cfg.oom_score_adj,
(cfg.env or {}).get("NVIDIA_DRIVER_CAPABILITIES") if cfg.gpu_ids else None,
)

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.

Have you considered normalizing cfg.image via parse_image_ref() in _boot_key (so 'python:3.12-slim' matches 'docker.io/library/python:3.12-slim') and exposing a typed WarmPoolProfile dataclass instead of raw dicts that ignore ttl_seconds/timeout_seconds?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The image is done in 53bdb08: the boot key uses the image's cache entry name, so every spelling matches its profile (test_every_spelling_of_an_image_matches_its_profile). I kept profiles as dicts: a profile is create()'s keyword arguments plus size, so it follows create() with no second type to keep in step. ttl_seconds and timeout_seconds belong to each create, which is why a profile's are ignored.

Comment on lines +251 to +255
except Exception as exc:
logger.warning("A warm-pool sandbox failed to boot: %s", exc)
with self._lock:
self._failed_at[slot.key] = time.monotonic()
self._refill_later(slot.key, _WARM_RETRY_SECONDS)

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.

Have you considered exponential backoff for transient boot errors and surfacing permanent setup failures from wait_for_warm_pool(), rather than pausing 30s on any blip and waiting the full 300s timeout on broken configs?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The backoff is in 53bdb08: the first failure pauses a profile for 1 s and each one that follows for twice as long, up to 30 s, and a boot that works starts over (test_a_failing_profile_pauses_longer_after_each_failure). I left wait_for_warm_pool() returning False on timeout: it can't tell a broken profile from a slow one, and raising would change what callers get from a call that only waits. Each failed boot logs its error.

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

…warm pool's cleanup

- A create that matches a profile gets the profile's env under its own
  whether it takes a booted sandbox or boots cold. A cold one used to get
  only its own, so a create's env depended on load.
- A profile matches every spelling of its image.
- Sandboxes that died while ready are deleted on a few threads, not one
  thread each.
- close() waits for the boots under way and those deletes, so the pool
  holds nothing once it returns.
- A failed boot pauses its profile for a second, then twice as long after
  each failure that follows, up to 30 s. Boots that fail together cause
  one pause.
- BaseSandboxBackend declares assign_config.

Signed-off-by: xyuzh <[email protected]>

@xyuzh xyuzh left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks for the review. 53bdb08 addresses the env difference, the unbounded cleanup threads, close(), image spellings, the retry pause and the base class. The slot design and the profile type are answered inline.

@pcmoritz, the changes since your approval are in that commit: a matching create now gets the profile's env when it boots cold too, close() waits for boots under way, dead sandboxes are deleted on a small executor, and a failed boot backs off from 1 s to 30 s.

Comment on lines +142 to +164
def take(self, cfg: SandboxConfig) -> Optional[str]:
"""Claim a booted sandbox for ``cfg``, or return None.

The sandbox's slot stays claimed until the sandbox is deleted, so
taking one boots nothing.
"""
key = _boot_key(cfg)
if key not in self._profiles:
return None
taken = None
dead = []
with self._lock:
ready = self._ready[key]
while ready and taken is None:
slot = ready.popleft()
if slot.state != _READY: # deleted while it waited
continue
if self._runtime.get_status(slot.sandbox_id) == SandboxStatus.RUNNING:
slot.state = _CLAIMED
taken = slot.sandbox_id
else:
slot.state = _DELETING
dead.append(slot.sandbox_id)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this: size bounds what a profile holds, ready or in use, and that bound is what a caller sizes against the CPUs and memory it set aside. Refilling on take would boot a sandbox for each one handed out, so a profile with size long-running sandboxes would hold twice its size. A caller that wants standby headroom beyond its running sandboxes sets a larger size, and the docs state the bound.

Comment on lines +42 to +60
return (
cfg.image,
float(cfg.cpu or 0.0),
parse_memory_bytes(cfg.memory) or 0,
cfg.workdir,
bool(cfg.rootless),
cfg.network,
tuple(cfg.dns) if cfg.dns is not None else None,
tuple(cfg.cidr_allowlist) if cfg.cidr_allowlist is not None else None,
tuple(cfg.capabilities) if cfg.capabilities is not None else None,
cfg.shell,
bool(cfg.readonly),
parse_memory_bytes(cfg.disk) or 0,
bool(cfg._ignore_cgroups),
tuple(cfg.gpu_ids or ()),
tuple(sorted((cfg.mounts or {}).items())),
cfg.oom_score_adj,
(cfg.env or {}).get("NVIDIA_DRIVER_CAPABILITIES") if cfg.gpu_ids else None,
)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The image is done in 53bdb08: the boot key uses the image's cache entry name, so every spelling matches its profile (test_every_spelling_of_an_image_matches_its_profile). I kept profiles as dicts: a profile is create()'s keyword arguments plus size, so it follows create() with no second type to keep in step. ttl_seconds and timeout_seconds belong to each create, which is why a profile's are ignored.

Comment on lines +251 to +255
except Exception as exc:
logger.warning("A warm-pool sandbox failed to boot: %s", exc)
with self._lock:
self._failed_at[slot.key] = time.monotonic()
self._refill_later(slot.key, _WARM_RETRY_SECONDS)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The backoff is in 53bdb08: the first failure pauses a profile for 1 s and each one that follows for twice as long, up to 30 s, and a boot that works starts over (test_a_failing_profile_pauses_longer_after_each_failure). I left wait_for_warm_pool() returning False on timeout: it can't tell a broken profile from a slow one, and raising would change what callers get from a call that only waits. Each failed boot logs its error.

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

… works

A boot that failed left its profile paused, and its slot empty, until the
pause's timer fired, even when another boot of the same wave had worked.
A boot that works now clears the pause and refills the profile at once.

Signed-off-by: xyuzh <[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 using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit f95fdfa. Configure here.

…t boot

A boot that failed, or was skipped for a pause, emptied its slot in a
second step. A boot that worked in between ended the pause, cancelled its
timer and refilled, and missed that slot, which then stayed empty until a
later delete. The boot now empties its slot and either leaves it to the
pause's timer or refills at once, under one lock.

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

`readonly=True` is the default today, and it buys little. A read-only
sandbox boots no faster than a writable one (27 ms both), and it's
slower once it does anything: with an explicit `workdir` it needs a
kernel overlay and takes 87 ms to create, and Python's stdlib imports
take 203 ms instead of 45 ms because nothing can cache `.pyc` files. On
a worker that can't mount a kernel overlay, a read-only sandbox with a
`workdir` already ran writable, with a warning. The mode also needs
special cases across the package, which keep complicating other sandbox
PRs.

This PR removes the option. Every sandbox writes to a private overlay
over its cached image, which is discarded with the sandbox. That
deletes:

- the host-backed scratch `workdir` and the `/tmp` tmpfs,
- the kernel overlay for missing mount points and the writable-root
fallback (`needs_rootfs_overlay` is hooks only now),
- `_seed_mountpoints` in the image build, since runsc creates mount
points in the sandbox's overlay,
- the `workdir` branches in `disk` capping (`--overlay2 all:`),
checkpoint, and restore.

About 600 lines net. Read `image_manager.py` and `backend/gvisor.py`
first. Most of the rest is tests and docs.

Behavior changes:

- The root filesystem is writable by default. A `workdir` is a plain
directory in the overlay, and `/tmp` is on the root filesystem.
- `readonly=False` passed to `create()`, `restore()`, `Sandbox`, or
`SandboxRuntime` is ignored with a `RayDeprecationWarning`, and the HTTP
API ignores `readonly: false`, so callers that pass it keep working.
`readonly=True` raises a `ValueError`, and the HTTP API answers `422`,
because ignoring it would hand the caller a writable sandbox.
- `disk` works without a `workdir`, and counts the `workdir` too.
- A relative `workdir` raises a `ValueError`, or gets a `422` over HTTP,
instead of failing when the container starts.
- Restore refuses a checkpoint of a `readonly=True` sandbox, whose saved
state depends on the read-only root. Checkpoints of writable sandboxes
restore as before. Restore also refuses a different `workdir`, which
runsc rejects anyway.
- Without `disk`, any sandbox can now fill the node's disk. A node-wide
default cap is a follow-up.
- `commit()` from #67972 works on every sandbox, so its read-only check
is gone. Its new layer leaves out the mount points runsc creates when
the base image lacks them, such as an empty `/etc/hosts`.

## Related issues

None filed. This comes from review feedback that the read-only mode
complicates other sandbox PRs.

## Additional information

- Not a duplicate: no open PR removes the option. It overlaps #67810
(its `_seed_erofs_image` pass can go), #67076 (the fallback's warning),
and #67077 and #67728 (`readonly` in the warm-pool key). #67972 merged
since, and the merge with master drops its read-only check. #66782 and
#67010 pass `readonly=False`, which still works.
- Numbers: measured on master on November 9 with `python:3.10-slim`,
medians of 10 rounds.
- Tests: new tests cover the writable default, `disk` with and without a
`workdir`, the ignored `readonly=False` and the refused `readonly=True`
in Python and over HTTP, the refused read-only checkpoint, and an image
with only `/bin` and `/lib`, which boots with host mounts, `/etc/hosts`,
and `/etc/resolv.conf`. I also booted that image from a kernel overlay
with a hook, and as a non-root user.
- Tested in a privileged container with runsc release-20261026.0, as
root. `pytest python/ray/experimental/sandbox/tests`: 651 passed, 39
skipped (no GPU, `erofsfuse`, or delegated cgroup there), 3 failed. The
3 are GPU and CDI tests that fail the same way on master in that
container, whose Ray core predates `get_cdi_kind`. `pytest
python/ray/experimental/sandbox/http/tests`: 185 passed, 10 skipped. The
skipped ones are the Modal SDK tests, which passed on the first commit
with the SDK installed. pre-commit and the API param coverage lint pass.
- I used Claude Code to help write and test this change.

---------

Signed-off-by: xyuzh <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Issues that should be addressed in Ray Core docs An issue or change related to documentation sandbox

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants