Skip to content

[sandbox] Build EROFS images by merging per-layer images - #67810

Closed
pcmoritz wants to merge 5 commits into
masterfrom
sandbox-erofs-oci-pull
Closed

pcmoritz wants to merge 5 commits into
masterfrom
sandbox-erofs-oci-pull

Conversation

@pcmoritz

@pcmoritz pcmoritz commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Description

A cold image pull spends most of its time turning layers into a tree on disk and back into a tar. The layers are extracted into a tree, and the tree is re-tarred into mkfs.erofs --tar. With this PR, a registry image is built without that tree, when the node's mkfs.erofs supports it:

  1. Each layer becomes an EROFS image of its own. As a layer downloads into the layer cache ([core][sandbox] Image layers caching #67874), it streams through Python's gzip and tarfile into mkfs.erofs --tar=f --aufs --sort=none. tarfile only reads the headers for the checks described under "Fallback" below. Up to three layers build at a time.
  2. One pass merges the layer images. mkfs.erofs --clean=data --ovlfs-strip=1 copies their data into one self-contained image and applies the whiteouts. gVisor mounts that one image.
  3. Seeds. The mount points runsc needs go in as an extra layer below the image's own layers, so the image's own entries win, as _seed_mountpoints leaves existing entries alone. The root and /tmp go on top in a small --incremental pass, because a merge gives the root the building user's owner and mode 0777, whatever the layers say.

Ray resolves and fetches the image exactly as for extraction, so mirrors, credential helpers, digests, the host's platform and timeout_seconds all behave the same. Layer digests are verified by the layer cache.

This PR first used mkfs.erofs --oci, which downloads the image itself. Review found that it ignores whiteouts, can pull the wrong platform on erofs-utils 1.9.0–1.9.3, runs outside the pull timeout, and needs an --enable-oci build. This version drops it.

Build while downloading

The build of a layer doesn't wait for its download. layer_cache.fetch_blob can hand out a GrowingBlob over the partial download as soon as the registry answers. A read past what has arrived waits for more, and the blob ends only once the download is verified. A failed or mismatched download raises instead, so no image is ever built from an unverified layer. Extraction still reads finished layers. _download_blobs used to stop outstanding downloads once it had yielded every layer; it now stops them only when abandoned early, since a yielded layer may still be downloading.

Fallback

The pull falls back to extraction unchanged in any of these cases:

  • RAY_SANDBOX_EROFS_MERGE=0 is set;
  • the node's mkfs.erofs --help lacks --aufs, --sort=, --clean=, --ovlfs-strip or --incremental=;
  • the image is a local archive;
  • a layer image build or the merge fails;
  • the layers would merge into a different tree than extraction gives. The layer headers read during the build catch these cases:
    • a member whose parent directory has no entry in the same layer. mkfs.erofs makes up that parent with mode 0777 and the building user's ownership, over the parent from the layers below.
    • a directory entry at a path that is a symlink by then, such as bin/ over UsrMerge's bin -> usr/bin. The merge replaces the symlink, as Docker does, but extraction keeps it and writes through it.
    • a layer that deletes a seeded path, or an image whose /etc or /dev ends up a symlink. Extraction seeds again, or seeds through the symlink.
    • a member path containing ...

Image builders don't write the first two kinds of layer, so in practice these checks are a guard. Registry and download errors still fail the pull with the same SandboxCreationError as before, without a fallback.

Same image, faster

I compared the images both pipelines build for ubuntu:22.04 (3,518 entries), python:3.12 (33,003) and pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime (77,826). I extracted each image as root with fsck.erofs --extract, which keeps owners, and compared the trees. Every entry matches on type, mode (setuid and sticky bits included), uid/gid, size, content, symlink target and device number. runsc boots the merged images; I checked busybox and python:3.10-slim by running commands in sandboxes with RAY_SANDBOX_IGNORE_CGROUPS=1.

Cold pulls, each into an empty cache, from Docker Hub, on two nodes:

  • EBS: 64 vCPU, EBS root volume at about 125 MB/s, container memory limit 30 GiB.
  • NVMe: 32 vCPU, root on local NVMe instance storage (about 980 MB/s with direct I/O), container memory limit 120 GiB. Medians of three runs, alternating master and this PR; all runs of an image were within 0.5 s of each other, except master's PyTorch pulls (95.6–99.5 s).
image size EBS: master EBS: this PR speedup NVMe: master NVMe: this PR speedup
ubuntu:22.04 85 MB 2.9 s 1.7 s ~1.7× 3.2 s 2.1 s ~1.5×
python:3.12 1.2 GB 37.2 s 13.6 s ~2.7× 22.4 s 8.3 s ~2.7×
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime 6.3 GB 152.4 s 92.6 s ~1.6× 95.8 s 43.2 s ~2.2×

The EBS ubuntu time is from the version just before "build while downloading"; that change saves time only on large layers. Timings vary with network speed between runs.

On the EBS node, writing to disk is the limit. mkfs.erofs hardly uses any CPU: built onto tmpfs, the largest PyTorch layer takes 2.7 s instead of about 50 s. There, decompression is not on the critical path, and isal's gzip barely helps (90.7 s instead of 92.6 s for PyTorch).

On the NVMe node, decompression is the limit. PyTorch's largest layer (3.3 GB gzipped, 6.1 GB of tar) finishes downloading 13.5 s into the pull, but its image is done only at 39 s. From the cached layer, mkfs.erofs builds that image in 4.1 s from the uncompressed tar. Python's gzip alone takes 26.2 s to decompress it, and tarfile's stream-mode header parsing with a 1 MiB buffer adds about 7 s more.

Experiment: isal decompression (not in this PR)

On the NVMe node I tried a faster decoder for the layer builds. Decompressing PyTorch's largest layer takes:

decoder time
stdlib gzip 26.2 s
zlib-ng (python-zlib-ng 1.1.0) 15.8 s
isal (python-isal 1.9.1) 12.1 s

A patch on top of this PR, with three changes:

  • _build_layer_image decompresses with isal.igzip_threaded when isal is installed, and with stdlib gzip otherwise. Decompression then runs in its own thread, overlapping header parsing and the writes to mkfs.erofs.
  • the tarfile stream buffer shrinks from 1 MiB to 64 KiB;
  • GrowingBlob gains readinto and readable, which isal's reader needs.

With the patch, that layer builds from the cache in 18.3 s instead of 37.5 s. Cold pulls on the NVMe node, medians of three runs, alternating:

image master this PR this PR + isal vs. this PR vs. master
ubuntu:22.04 3.2 s 2.1 s 1.6 s ~1.3× ~2.0×
python:3.12 22.4 s 8.3 s 4.6 s ~1.8× ~4.9×
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime 95.8 s 43.2 s 20.0 s ~2.2× ~4.8×

Every patched pull merged its layers, without a fallback. For python:3.12, the patched image matches this PR's entry for entry (extracted as root and compared as above). PyTorch's pull now takes 20 s, and its largest layer's download takes 13.5 s of that.

This PR leaves the patch out. It adds an optional dependency, and the test suite hasn't run on it. It can follow in its own PR.

Known limits

  • Disk use: while an image builds, its layer images and the merged image are on disk together, roughly twice the image size. The extraction pipeline also peaks near that.
  • Reproducibility: [core][sandbox] Build sandbox EROFS images reproducibly #67484 (build EROFS images reproducibly) adds -Eforce-inode-extended, a fixed UUID and -T0 --mkfs-time to build_erofs_image. The merge and seed passes here would need the same flags; whichever PR lands second should add them.

Related issues

Part of the Ray Sandboxing effort (#65352).

Additional information

Requirements

The merged build needs erofs-utils 1.8+ (it uses --aufs, --sort=none, --clean=data, --ovlfs-strip and --incremental=data). Debian 13's package qualifies; Ubuntu 24.04's (1.7.1) doesn't, and there the pull uses extraction as before. The tests that need a real mkfs.erofs skip without a capable one.

Changes

  • image_utils.py:
    • New functions: _build_erofs_image_from_registry, _build_layer_image, _layer_merge_problem and _seed_layer.
    • Refactor: manifest resolution moved out of _extract_image_layers into _resolve_registry_image, so both pipelines share it.
    • Downloads: _download_blobs gained a growing flag.
  • layer_cache.py: GrowingBlob, and an optional started future on fetch_blob; existing callers are unaffected.

Tests

New tests in python/ray/experimental/sandbox/tests/test_image_utils.py. Those that need a real mkfs.erofs skip without one that can merge.

  • test_pull_merges_layer_images: three layers with whiteouts, an opaque directory, replaced files, a hard link, a non-root owner and a symlinked /dev/shm. The merged image equals the extracted one, entry for entry, and is seeded.
  • test_pull_extracts_layers_that_merge_differently: each fallback case (a directory over a symlink, missing parent entries, a deleted seed, a symlinked /etc or /tmp) logs a warning and gives the extracted image.
  • test_layer_merge_problem: unit tests of the header check.
  • test_pull_with_a_real_mkfs_merge: a pull from the in-process fake registry (bearer-token challenge, multi-arch index, blob redirect).
  • test_merged_pull_skipped_when_disabled, test_merged_pull_reports_a_missing_image, test_merged_pull_fails_on_a_bad_layer (cut short or swapped, without a fallback), test_merged_pull_stops_other_layers_when_one_fails.
  • test_growing_layers_are_read_while_they_download: a layer is handed over and readable before its download completes.

Commands run on an Anyscale workspace (64 vCPU), with this checkout's ray.experimental on top of an installed Ray 3.0.0.dev0 and erofs-utils 1.9.4:

TEST_SANDBOX=1 pytest python/ray/experimental/sandbox/tests/test_image_utils.py \
    python/ray/experimental/sandbox/tests/test_registry_auth.py \
    python/ray/experimental/sandbox/tests/test_image_manager.py \
    python/ray/experimental/sandbox/tests/test_overlayfs.py
# 252 passed, 3 skipped (also with RAY_SANDBOX_EROFS_MERGE=0)

black passes on the changed files.

AI assistance

This change was developed with AI assistance (Claude Code). The submitter has reviewed every changed line and run the tests above.

🤖 Generated with Claude Code

@pcmoritz
pcmoritz requested a review from a team as a code owner November 4, 2026 04:01
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@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 the core Issues that should be addressed in Ray Core label Nov 4, 2026

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

(from AI review)

Comment on lines +1028 to +1029
# Apply the layers' whiteouts instead of keeping them.
"--ovlfs-strip=1",

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.

Blocking: mkfs.erofs --oci in erofs-utils 1.9.4 silently ignores multi-layer whiteouts and clobbers UsrMerge directory symlinks (returncode == 0, no fallback)

Testing multi-layer images end-to-end with erofs-utils 1.9.4 (--enable-oci) + runsc uncovered two upstream erofs-utils bugs where _build_erofs_image_from_registry succeeds (True) and caches a broken or leaky rootfs.erofs:

  1. .wh.<name> and .wh..wh..opq whiteouts are ignored (--ovlfs-strip=1 is a no-op under --oci):
    With --tar=f, mkfs/main.c sets erofstar.aufs = true, which gates .wh.* and .wh..wh..opq parsing in erofs_rebuild_get_dentry (lib/rebuild.c:112, if (aufs && !slash)), and --ovlfs-strip=1 then strips the resulting overlayfs whiteout inodes at pack time. However, ocierofs_process_tar_stream (lib/remotes/oci.c:856) initializes a local struct erofs_tarfile tarfile = {}; without setting tarfile.aufs = true. As a result, every .wh.* / .wh..wh..opq marker in upper OCI layers is written as a literal 0-byte file and lower-layer files/directories are never deleted—so build-time secrets or stale package files removed in later RUN rm ... layers remain readable inside the gVisor sandbox.

  2. Upper-layer S_ISDIR entry clobbers lower-layer UsrMerge symlinks (/bin -> usr/bin):
    On Debian/Ubuntu UsrMerge base images where /bin -> usr/bin is a symlink, an upper layer that ships bin/hello without a bin/ directory entry fails in mkfs.erofs ([Error 20] Not a directory) and falls back cleanly. But if the upper layer includes a bin/ directory tar header followed by bin/hello (as tar cf layer.tar bin/ emits), tarerofs_parse_tar (lib/tar.c:1129-1135) unlinks the /bin -> usr/bin symlink and replaces /bin with a directory containing only hello (mkfs.erofs and _seed_erofs_image both exit 0), wiping /bin/sh from the sandbox whereas extract_tar_layer preserves /bin -> usr/bin.

Suggestion: Until upstream erofs-utils fixes both (tarfile.aufs = true in oci.c and preserving directory symlinks on S_ISDIR in tar.c) and _mkfs_erofs_supports_oci checks for a fixed version, consider either:

  • defaulting _EROFS_OCI_ENV to "0" (opt-in), or
  • fetching the manifest/config first (which _extract_image_layers(..., False) already does) and only invoking mkfs.erofs --oci automatically when len(layer_descs) == 1, where cross-layer whiteouts and cross-layer directory-over-symlink clobbers cannot occur.

Comment on lines +1041 to +1044
_extract_image_layers(
image, image_dir, image_dir, timeout_seconds, image_dir, False
)
returncode = proc.wait()

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.

timeout_seconds is not enforced on proc.wait()

_extract_image_layers(..., False) applies timeout_seconds only to the manifest and config HTTP requests; proc.wait() then blocks without a deadline (bounded only by erofs-utils's hardcoded CURLOPT_TIMEOUT = 120L per layer in lib/remotes/oci.c:146). In testing against a stalled layer blob (8s delay) with timeout_seconds=1.5, RAY_SANDBOX_EROFS_OCI=0 failed in 1.56s while --oci blocked for 8.50s and succeeded.

Consider tracking deadline = time.monotonic() + timeout_seconds before spawning proc, passing timeout=max(0.0, deadline - time.monotonic()) to proc.wait(...), and on subprocess.TimeoutExpired killing proc and raising SandboxCreationError directly (note TimeoutExpired inherits from SubprocessError, not OSError/RuntimeError, which also avoids kicking off a fallback layer download after the caller's timeout has already expired).

Comment on lines +868 to +880
def _mkfs_erofs_supports_oci(mkfs: str) -> bool:
"""Whether ``mkfs`` can build an image straight from a registry.

``--oci`` needs erofs-utils 1.9+ built with ``--enable-oci`` (libcurl and
json-c), which distribution packages often leave out.
"""
try:
res = subprocess.run(
[mkfs, "--help"], capture_output=True, text=True, timeout=30
)
except (OSError, subprocess.TimeoutExpired):
return False
return "--oci" in res.stdout + res.stderr

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.

Non-amd64 behavior across erofs-utils 1.9.x releases

Following up on the Bugbot comment below with details from the erofs-utils C source:

  • erofs-utils 1.9.4 added ocierofs_get_platform_spec() (lib/remotes/oci.c:1112, 1176), so 1.9.4 actually defaults to "linux/amd64" on x86_64 and "linux/arm64/v8" on aarch64 (even though mkfs/main.c:230 still prints default: linux/amd64 in --help).
  • However, erofs-utils 1.9.0–1.9.3 also advertise --oci in --help while hardcoding "linux/amd64", so on an arm64 host with 1.9.0–1.9.3, _mkfs_erofs_supports_oci returns True and pulls amd64 layers alongside an arm64 .image_config.json.
  • Also on arm64 in 1.9.4, oci.c:702-712 uses an exact strcmp against "linux/arm64/v8", so multi-arch OCI indexes whose arm64 entry omits "variant": "v8" ({"os": "linux", "architecture": "arm64"}) fail with -ENOENT and fall back unless platform= is specified.

Checking mkfs.erofs -V (>= 1.9.4) when get_platform_arch() != "amd64"—or resolving the manifest index in Python first and passing --oci=f,platform=<matched_platform>—would prevent the 1.9.0–1.9.3 mismatch and avoid unnecessary arm64 fallbacks.

Comment on lines +954 to +956
for name in ("dev", "etc", "proc", "run", "sys", "tmp"):
if root.get(name, _EROFS_FT_DIR) != _EROFS_FT_DIR:
raise RuntimeError(f"the image's /{name} isn't a directory")

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.

Minor: symlinked /dev/shm or /dev/pts is overwritten into a directory

Checking root catches a symlinked top-level /dev, /etc, or /tmp, but _OCI_SEED_DIRS also unconditionally writes dev/pts and dev/shm (0o755). If an image ships /dev as a directory with /dev/shm -> /run/shm as a symlink, the incremental pass replaces /dev/shm with an empty directory instead of preserving the symlink like _seed_mountpoints does.

runsc mounts over /dev at runtime so this is benign in gVisor, though checking _erofs_listdir(dump, image_path, "/dev") for non-directory pts/shm when "dev" in root would keep exact parity.

Comment on lines +1754 to +1767
def test_pull_with_a_real_mkfs_oci(
tmp_path, fake_docker_hub, fake_mkfs_erofs, monkeypatch
):
"""With an erofs-utils built with --enable-oci, a pull from the fake
registry gives an image with the layer's files and Ray's seeds."""
mkfs = _real_mkfs(fake_mkfs_erofs, monkeypatch, "--oci")
image_dir = pull_and_extract_container_image(
"busybox:latest", images_dir=str(tmp_path / "images")
)
image = os.path.join(image_dir, ROOTFS_IMAGE)
_assert_seeded(mkfs, image)
assert _erofs_cat(mkfs, image, "/bin/busybox") == fake_docker_hub
assert _erofs_stat(mkfs, image, "/bin/busybox")[0] == 0o755
assert os.path.exists(os.path.join(image_dir, ".image_config.json"))

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.

Suggestion: add a 2-layer image test case for real mkfs.erofs --oci

fake_docker_hub serves a single-layer busybox image, so test_pull_with_a_real_mkfs_oci passes even when mkfs.erofs --oci ignores .wh.<file> / .wh..wh..opq whiteouts or overwrites a lower-layer bin -> usr/bin symlink with an upper-layer bin/ directory entry. Adding a 2-layer fixture to the fake registry covering both cases would catch these regressions directly whenever an OCI-enabled mkfs.erofs is on PATH.

pcmoritz pushed a commit that referenced this pull request Nov 11, 2026
## Description

Cache verified container-image layers per node so different images and
rebuilds can reuse layers instead of downloading them again.

Layers are stored by SHA-256 digest, verified before publication, and
protected by cross-process locks to avoid duplicate downloads. Eviction
uses the existing image-cache limits.

Tested using a **3.34 GB PyTorch/CUDA base** and two **129-byte
application layers**:

| Scenario | Downloaded before | Downloaded after |
|---|---:|---:|
| Different application on the same base | 3.34 GB | 129 bytes |
| Rebuild an extracted image | 3.34 GB | 0 bytes |

Warm rebuilds eliminated approximately **9–10 seconds of downloading**.
Median sandbox creation decreased from **111s to 103s (~7%)** across two
rebuilds per version. Extraction and EROFS construction remain unchanged
and dominate the remaining time #67810 will hopefully solve extraction
part

---------

Signed-off-by: Pawel Beza <[email protected]>
Signed-off-by: Pawel Beza <[email protected]>
Co-authored-by: Pawel Beza <[email protected]>
Co-authored-by: Copilot <[email protected]>
Copilot-Session: 21d0d11b-3c88-40fb-aefb-a2e754c71d16
Task Solver and others added 3 commits November 16, 2026 14:12
…ofs --oci

mkfs.erofs --oci (erofs-utils 1.9.4) ignores whiteouts, pulls amd64 on
older 1.9.x releases whatever the host, and runs outside the pull's
timeout, auth and mirror handling. Instead, each layer now downloads
straight into its own EROFS image: Ray resolves and fetches it as before,
verifies its digest, decompresses it and streams the tar into
mkfs.erofs --tar=f --aufs --sort=none. One mkfs.erofs --clean=data
--ovlfs-strip=1 pass merges the layer images and applies the whiteouts,
and the existing incremental pass seeds the result.

The tar headers are read on the way through, and layers whose merge
would differ from extraction (a path without its parent's entry, or a
directory over a symlink such as UsrMerge's bin) are extracted instead,
as are images whose /dev/pts or /dev/shm is a symlink. This needs only
erofs-utils 1.8+, not an --enable-oci build.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…box-erofs-oci-pull

# Conflicts:
#	python/ray/experimental/sandbox/_internal/image_utils.py
Rebuild the merged-image path on master's layer cache (#67874): the
cache downloads, verifies and keeps each layer, so the PR's own
streaming download, digest check and decompression sniffing go away.
Each cached layer streams through tarfile (to read its headers) into
mkfs.erofs --tar=f --aufs --sort=none, a few at a time; one
mkfs.erofs --clean=data --ovlfs-strip=1 pass merges them.

Seeding no longer needs dump.erofs: the mount points go in as a layer
below the image's, so the image's own entries win as with extraction,
and only the root and /tmp go on in an incremental pass (a merge
ignores the layers' root attributes). The header check now also
catches images that delete a seed or make /etc or /dev a symlink, and
a symlinked /dev/shm is kept rather than refused.

Co-Authored-By: Claude Opus 5.5 <[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.

dirs.add(path)
elif kind in ("sym", "file"):
(symlinks.add if kind == "sym" else symlinks.discard)(path)
dirs.discard(path)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

File at /tmp not rejected

Low Severity

_layer_merge_problem only treats a symlink at tmp as a merge mismatch. When tmp is a regular file, the above seed still writes a directory there, while _seed_tmp leaves the file in place after makedirs fails. A merged image can therefore be cached with a directory at /tmp even though extraction would keep the file.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 9c88977. Configure here.

s
for s in symlinks
if not s.startswith(prefix) and (kind == "opq" or s != path)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Same-layer whiteout order ignored

Medium Severity

_layer_merge_problem never models tar order inside a layer. Extraction applies .wh. and opaque whiteouts as members appear, so a file (or directory contents) followed by its whiteout is deleted. Merge stores both in one overlay layer, where a whiteout only hides lower layers and the same-layer file remains. That mismatch is not flagged, so a merged image can be cached that does not match extraction.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 9c88977. Configure here.

".image_config.json",
".manifest.json",
ROOTFS_IMAGE,
]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Registry merge test always falls back

Low Severity

test_pull_with_a_real_mkfs_merge claims to merge through the fake registry’s token challenge, multi-arch index, and blob redirect, but that fixture’s layer is only bin/busybox with no bin/ directory. _layer_merge_problem treats that as a missing parent and falls back to extraction, so the test can pass without the merge path ever succeeding.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 9c88977. Configure here.

The layer cache hands a layer to the build as soon as its download
starts, as a GrowingBlob over the partial file: a read past what has
arrived waits for more, and the blob ends only once the download is
verified (a failed or mismatched download raises instead). The build
of the largest layer no longer waits for its download, which takes a
cold pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime pull from 111 s to
93 s on a 4 vCPU node. Extraction still reads finished layers.

Co-Authored-By: Claude Opus 5.5 <[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.

There are 4 total unresolved issues (including 3 from previous reviews).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit a4541b4. Configure here.

end = self._size if size < 0 else min(self._size, self._pos + size)
data = os.pread(self._file.fileno(), end - self._pos, self._pos)
self._pos += len(data)
return data

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Download errors incorrectly trigger extraction fallback

Medium Severity

With growing blobs, a layer is yielded as soon as the download starts, so later fetch failures surface from GrowingBlob.read instead of _pull_errors. They are not SandboxCreationError, so _build_erofs_image_from_registry falls back to extraction. A truncated or interrupted layer is pulled twice instead of failing the pull.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit a4541b4. Configure here.

@pcmoritz pcmoritz changed the title [sandbox] Pull OCI images through mkfs.erofs [sandbox] Build EROFS images by merging per-layer images Nov 16, 2026
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]>
@pcmoritz

Copy link
Copy Markdown
Contributor Author

I found replacing this by python logic (so we can be OCI compliant) slows it down a bunch, and we can do much faster, which I implemented in #68263

@pcmoritz pcmoritz closed this Nov 18, 2026
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 sandbox

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants