Repository navigation
Conversation
erofs-pull (src/ray/sandbox/erofs_pull) builds a registry image's EROFS root filesystem in one pass: - downloads each layer into the layer cache over parallel HTTP range requests (or one stream, where storage ignores ranges), under the cache's own locks and file names; - decompresses the layers with rapidgzip while they download, all layers at once, each on all cores; - writes each file's data once, into the image, and applies the layers as extract_tar_layer does, then seeds the image as _seed_tmp and _seed_mountpoints do. _extract_image_layers hands a resolved registry image to it before extracting anything, and extracts as before when there is no binary (RAY_SANDBOX_EROFS_PULL=0 turns it off, or names another binary), the manifest has no layer sizes, or the build fails. The registry token reaches it on stdin; it trusts the CA certificates Python's ssl does. Cold pulls on a 32 vCPU node with NVMe storage: python:3.12 22.8 s -> 2.3 s, pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime 88.1 s -> 5.8 s. The images match extraction's entry for entry. Build: rules_rust 0.70.0 (the last release with WORKSPACE support) and crate_universe pin the crates; rapidgzip's C++ builds with rules_foreign_cc, without ISA-L (no nasm) and without LTO (see thirdparty/patches/rapidgzip-sys-bazel.patch). platforms goes to 0.0.11, which rules_rust needs. Linux wheels ship the binary (3.8 MB) at ray/core/src/ray/sandbox/erofs_pull/erofs_pull. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces erofs-pull, a Rust-based image builder for Ray Sandbox that constructs gVisor-ready EROFS images directly from container registry layers. It integrates this tool into the Bazel build system, Python packaging, and image utility scripts, while adding comprehensive integration tests. Feedback on the changes highlights critical compilation errors in fetch.rs due to an invalid match guard and a missing file-locking method, as well as a correctness bug in erofs.rs where incorrect byte offsets are used when writing EROFS extended inode metadata.
| .append(true) | ||
| .create(true) | ||
| .open(PathBuf::from(blob_dir).join(format!("{hex}.lock")))?; | ||
| lock.lock()?; |
There was a problem hiding this comment.
The std::fs::File struct does not have a lock method in Rust's standard library, and no extension trait providing it is imported. This will cause a compilation error. Since this builder is only compatible with Linux, you can use rustix::fs::flock (from the rustix crate, which is already in the dependency tree) to perform advisory file locking.
| lock.lock()?; | |
| rustix::fs::flock(&lock, rustix::fs::FlockOperation::LockExclusive).map_err(io::Error::from)?; |
| .open(PathBuf::from(blob_dir).join(format!("{hex}.lock")))?; | ||
| lock.lock()?; | ||
| let (file, cached) = match File::open(&final_path) { | ||
| Ok(f) if f.metadata()?.len() == size => { |
There was a problem hiding this comment.
Using the ? operator inside a match guard is not allowed in Rust and will result in a compilation error. You should rewrite this guard to avoid using ? by mapping the result or handling it outside.
| Ok(f) if f.metadata()?.len() == size => { | |
| Ok(f) if f.metadata().map(|m| m.len() == size).unwrap_or(false) => { |
| ino[32..40].copy_from_slice(&node.mtime.to_le_bytes()); | ||
| ino[44..48].copy_from_slice(&nlink[id as usize].to_le_bytes()); |
There was a problem hiding this comment.
In the EROFS extended inode structure (struct erofs_inode_extended), the i_nlink field is located at offset 40 (4 bytes), right after i_mtime_nsec (offset 36, 4 bytes). Writing nlink to ino[44..48] actually writes into i_reserved2 and leaves i_nlink as 0, which is invalid and can cause traversal/verification tools to fail. Additionally, node.mtime is a u64 seconds timestamp; writing it directly as 8 bytes into ino[32..40] will leak the upper 32 bits of the timestamp into i_mtime_nsec (which should be 0). Explicitly cast mtime to u32 and write nlink to the correct offset.
| ino[32..40].copy_from_slice(&node.mtime.to_le_bytes()); | |
| ino[44..48].copy_from_slice(&nlink[id as usize].to_le_bytes()); | |
| ino[32..36].copy_from_slice(&(node.mtime as u32).to_le_bytes()); | |
| ino[40..44].copy_from_slice(&nlink[id as usize].to_le_bytes()); |
pull_and_extract_container_image checked for mkfs.erofs before anything else, so a node without erofs-utils failed every pull, even though erofs-pull builds registry images without it. The check now runs where mkfs.erofs is used: before extracting a local archive, and before downloading a registry image's layers for extraction when erofs-pull didn't build it. Without either, a registry pull still fails before downloading any layer; when erofs-pull failed and there's no mkfs.erofs to fall back on, the error says erofs-pull failed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
…ulls erofs-pull locked every layer of an image in manifest order and held the locks until the pull ended, so two pulls of images sharing layers in opposite orders could each hold a lock the other waited for, forever. Now it locks layers in digest order, the same order in every pull, and commits and unlocks each layer as soon as its digest checks out, as the Python layer cache does; other pulls then wait only for that layer's download, not for the whole pull. test_concurrent_erofs_pulls_sharing_layers runs two erofs-pulls with opposite layer orders five times; before this change it hung on the first. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
CI's core build failed in rapidgzip's bundled rpmalloc: rpmalloc.c:582:14: error: '__builtin_thread_pointer' is not supported on this target rpmalloc uses the builtin with GCC 5 and later, but GCC only has it on x86_64 from GCC 11, and CI's manylinux toolchain is GCC 10. The patch now sends older GCCs down rpmalloc's inline-assembly path, which reads the same thread pointer. Built with GCC 10.4 outside Bazel, rapidgzip's native library now compiles and installs without errors. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
gVisor restores a checkpoint only onto an EROFS image whose superblock matches the one it was taken on (#67484 makes mkfs.erofs's images match). For erofs-pull's images that isn't enough: the checkpoint also records where each open file's data is in the image, and erofs-pull placed file data in whatever order its parallel layers wrote it, so two builds of an image differed, superblock included (it carried the build time). Now two builds of an image are byte for byte the same: - each layer writes its file data into the image only after the layer before it is done, so data goes in manifest order; layers still download and decompress in parallel, and downloads go in that order too, so the next layer is in when its turn comes; - entries the build creates (missing parents, seeds) get the layers' newest mtime, not the build time; - the superblock's build time is 0, as mkfs.erofs -T0 --mkfs-time writes it; its UUID was already zero and its inodes already extended. Cold pulls on a 32 vCPU NVMe node: pytorch/pytorch:2.5.1-cuda12.4- cudnn9-runtime 5.7-5.9 s as before, python:3.12 2.6 s (was 2.3 s). test_erofs_pull_builds_reproducible_images pulls an image twice with its layers arriving in different orders and compares the bytes; it failed with the previous binary. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
erofs-pull named layer cache files after a manifest digest with only its sha256: prefix stripped, so a digest like sha256:../../x made .lock and partial files outside the cache, and could take a host file of the layer's size for a cached layer. It now takes only what the layer cache does (layer_cache._DIGEST): sha256: and 64 lowercase hex digits, every digest checked before any file is touched. Such a pull falls back to extraction, which refuses the digest too. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
erofs-pull ignored HTTPS_PROXY and friends, so behind an egress proxy every cold pull failed in erofs-pull first, after up to timeout_seconds if the network drops packets, and then fell back to extraction. ureq's own environment detection doesn't match urllib (one proxy for every URL, no NO_PROXY), so Python now passes urllib.request.getproxies() in the spec, and erofs-pull picks a proxy per request as urllib does: the URL scheme's proxy, unless no_proxy names the host (proxy_bypass_environment, ported), for the registry and the storage it redirects to alike. Like urllib, it talks plain HTTP to the proxy, tunnels HTTPS with CONNECT, and sends the proxy URL's percent-decoded credentials; on plain HTTP requests it adds Proxy-Authorization itself, as ureq sends credentials only in CONNECT. Tested with a pull of python:3.12 from Docker Hub through an authenticating CONNECT proxy (every connection tunnelled, no fallback), and new tests for an authenticating HTTP proxy and no_proxy. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
A path component too long for a directory block made erofs-pull's directory writer loop forever while its buffer grew (a 4,090-byte file name took the binary to a 2 GB allocation failure), and names of 256 to 4,084 bytes were written although EROFS, like Linux, takes at most 255. Tree::apply now fails where extraction does: on a file, directory or parent directory it would create with a name longer than 255 bytes (os.open and os.makedirs raise ENAMETOOLONG); a symlink or hard link of such a name is skipped, as extraction ignores the error there. The pull then falls back to extraction, which fails on it too. The directory writer also returns an error, instead of looping, on an entry that fits in no block. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
Since "Make erofs-pull's images reproducible", a layer is decompressed and written only after the layer before it is done; only downloads run in parallel across layers. That commit's message, a comment in main.rs and the docstring of _build_image_with_erofs_pull still said layers decompress in parallel. The comment and docstring now say decoding is serial across layers, with rapidgzip decoding each layer on all cores. No change in behavior. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
CI's core build failed linking erofs_pull: rapidgzip's C++ code had undefined references to operator delete(void*, unsigned long), std::runtime_error(const char*), std::thread::_State and the like. rustc names rapidgzip's static libraries twice, and the copy the link actually uses comes after the toolchain's -lstdc++. devtoolset's libstdc++ (CI's manylinux image) is a linker script over the system's libstdc++.so.6 and a static libstdc++_nonshared.a holding the newer symbols, and a static archive resolves only references made before it. Ubuntu's libstdc++.so has everything, so the order didn't matter locally. rapidgzip_native now lists -lstdc++ and -lc as its linkopts, so they follow its libraries. Locally, linking against a static libstdc++.a, which is order-sensitive in the same way, reproduces CI's undefined references without this and links with it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
rpmalloc keeps freed memory cached per thread, and rapidgzip decodes a layer on every core. On a 32-core node erofs-pull peaked at 2.5 GB pulling pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime, and eight pulls at once at 4.8 GB, where master's extraction stays under 0.7 GB. With the system allocator instead (a new RAPIDGZIP_NO_RPMALLOC option in the rapidgzip-sys patch), on the same node: - pytorch/pytorch: 1.2 GB instead of 2.5 GB; cold pull 5.8 s instead of 5.6 s (two runs each), from cache 4.0 s either way; - python:3.12: about 0.8 GB instead of 1.0 GB, at the same speed; - eight images pulled at once: 3.2 GB instead of 4.8 GB, 7.7 s instead of 7.5 s. Capping rapidgzip at 16 threads would save another third, but costs pytorch/pytorch about 0.5 s, so the thread count stays one per core. rpmalloc's GCC 10 fix leaves the patch, as rpmalloc is no longer built. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
The long-name check lived in Tree::apply, but seed() creates directories on a path resolved through symlinks: an image with tmp -> /<300-byte name> got that directory at the root, written into the image, where extraction's os.makedirs fails with ENAMETOOLONG and the seeding skips it. makedirs now stops, as os.makedirs does, at a missing name longer than 255 bytes, keeping the directories before it, and seed() skips that seed. As a backstop on every path, the directory writer rejects any name over 255 bytes, not just one that fits in no block. dump.erofs leaves such names out of its listings, so the new test counts the name's bytes in the image as well as comparing it with extraction's; it fails with the previous binary. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
xyuzh
left a comment
There was a problem hiding this comment.
Thanks for this. The speedup is real, and since the description lists aarch64 as untested I tried it there. I built the binary with cargo, using the patch's CMake options, on Ubuntu 22.04 (GCC 11) at e5f90fa.
test_image_utils.py: 71 passed with the binary, 58 passed and 13 skipped without.python:3.12(arm64, 401 MB compressed): the image matches extraction's on all 33,086 paths (type, mode, owner, link count, size and SHA-256, symlink target, hard-link sets, file mtime), passesfsck.erofs, and boots under runsc release-20261026.0 withsslandsqlite3importing. From a warm layer cache the build takes about a second.- I also wrote a differential fuzzer: random layer stacks through both builders, then the two images compared entry by entry. Over about 40,000 stacks the tree logic held up. It found one case where erofs-pull is laxer than extraction, noted inline. The other differences were corner cases of malformed layers or quirks of extraction itself, which are separate from this PR.
- 400 corrupted downloads all failed with the digest error and left nothing in the cache.
The inline comments are what I'd look at before merging. The three that matter most are the zero UUID, where the gzip decoder comes from, and memory per pull.
Two things with no line to attach to:
- The table in the description was last edited before f9f4576, which made layers decode one at a time and download in manifest order. Could you re-run it?
doc/source/core/sandboxes.mdstill listsmkfs.erofsas required for every pull and doesn't mentionRAY_SANDBOX_EROFS_PULL.
Nits: the new tests sit below the if __name__ == "__main__": block in test_image_utils.py, and the zstd error still says "this prototype".
I'm happy to share the fuzzer if it's useful.
| // Build time 0 and a zero UUID, as `mkfs.erofs -T0 --mkfs-time | ||
| // -U00000000-0000-0000-0000-000000000000` writes: gVisor restores a | ||
| // checkpoint only onto an image with the superblock it was taken on. | ||
| sb[24..32].copy_from_slice(&0u64.to_le_bytes()); |
There was a problem hiding this comment.
With a zero UUID and build time, the only superblock fields left to vary are the inode count, the block count and meta_blkaddr. Two different images can agree on all three, and then nothing tells them apart on restore: gVisor's check and Ray's image_fingerprint both compare only the superblock.
Two cases I tried with this build:
- A tag that moved, with one source file edited in place at the same size: same fingerprint, different file contents.
- Two files that swap sizes (5,000 and 3,000 bytes): same fingerprint, and the second file's data moves from block 3 to block 2.
So a checkpoint can restore onto an image that has other bytes at the offsets it recorded. On master the random UUID from mkfs.erofs rules that out, since even the same layer built twice gets two fingerprints.
Deriving the UUID from what determines the bytes would keep builds reproducible and close the gap. For example, the first 16 bytes of a SHA-256 over the layer digests in order, the block size and a layout version. The version also covers a later change to how erofs-pull lays data out. #67484 picks the same zero UUID for mkfs.erofs, so it would want the same.
| # set by the caller) instead of a bundled copy of Mozilla's roots. | ||
| ureq = { version = "2", default-features = false, features = ["tls", "native-certs"] } | ||
| tar = "0.4" | ||
| rapidgzip = "1.2.1" |
There was a problem hiding this comment.
The description links to mxmlnkn/rapidgzip, but these crates aren't from that project. rapidgzip and rapidgzip-sys are a third-party wrapper, alekseizarubin/rapidgzip-rs: first published 2026-03-25, last release 2026-04-01, one owner, about 9,000 downloads. It vendors rapidgzip's C++ with rpmalloc and zlib-ng and adds its own C API shim. Its stock build doesn't link on Linux with GCC, which is what the patch works around. I hit the same undefined rpmalloc symbols on aarch64, so I doubt it has seen much use on Linux.
This is the code that now reads layers a sandbox user picked, on the node, outside gVisor, in a process that holds the registry token. It also reads them before the digest is checked, which extraction never did. It behaved in my runs, but I'd like a plan for who keeps it current. Could Ray own the shim and build upstream rapidgzip at a pinned commit instead of depending on the wrapper?
| result = subprocess.run( | ||
| [binary], input=json.dumps(spec).encode(), capture_output=True, env=env |
There was a problem hiding this comment.
If the worker dies during a pull, erofs-pull carries on without it. I sent SIGKILL to the pulling process mid-download: the child ran to the end and left a complete rootfs.erofs in <name>.tmp.<uuid>/, which nothing sweeps or counts against the cache cap. For a 6 GB image that's a lot of network, CPU and disk for a pull nobody is waiting on.
prctl(PR_SET_PDEATHSIG, SIGKILL) at the top of main would tie it to the worker. PDEATHSIG follows the spawning thread, which is fine here because subprocess.run blocks that thread until the child exits.
| EntryType::Symlink => Kind::Sym(entry.link_name_bytes().map(|l| l.into_owned()).unwrap_or_default()), | ||
| EntryType::Link => Kind::Hard(entry.link_name_bytes().map(|l| l.into_owned()).unwrap_or_default()), | ||
| EntryType::Char | EntryType::Block | EntryType::Fifo => Kind::Other, | ||
| _ => continue, |
There was a problem hiding this comment.
This skips more than it should. A layer made with tar --sparse builds without an error and comes out wrong:
- GNU format (
Sentries): the file is missing from the image. - PAX format: the file appears as
GNUSparseFile.<pid>/<name>and holds the sparse map plus the data, 4,612 bytes for an 8 MiB file.
Extraction gets both right because tarfile understands them. They're rare in registries, though a rootfs tarball that goes in through docker import can carry them. I'd return an error for any entry type this doesn't model, and for GNU.sparse.* PAX records, so that extraction takes over, the same way bbae46b treats long names.
| _ => Err(too_long()), | ||
| }; | ||
| } | ||
| let Some(p) = self.makedirs(&parent) else { return Ok(()) }; |
There was a problem hiding this comment.
This is the one place the fuzzer found erofs-pull laxer than extraction. When a non-directory blocks a parent path, say a file app and then app/config.yaml with no entry that turns app into a directory, extraction raises FileExistsError or NotADirectoryError and the pull fails. Here the member is dropped and the image builds without it. Returning an error from this branch, and from the hard-link one above it, would keep the two in step.
| match req.call() { | ||
| Ok(r) => Ok(r), | ||
| Err(ureq::Error::Status(code, r)) => Err(format!("HTTP {code}: {}", r.into_string().unwrap_or_default())), | ||
| Err(e) => Err(e.to_string()), |
There was a problem hiding this comment.
ureq's transport errors include the request URL, which for a redirected blob is the presigned storage URL, and it ends up in the fallback warning. I pointed a redirect at a closed port and the log line had the whole ?X-Amz-Credential=...&X-Amz-Signature=.... urllib's errors on the extraction path don't carry the URL. Dropping the query string before formatting would be enough.
With a zero UUID and a zero build time, only the inode count, block count and metadata address told erofs-pull's superblocks apart. A tag moved to an image where a small file changed, within the same blocks, got an identical superblock, so gVisor's restore check would accept a checkpoint onto different content. The superblock's UUID is now a hash of a layout version, the block size and the layer digests in manifest order (an RFC 9562 version 8 UUID). Builds of the same layers still match byte for byte, anywhere; images built from different layers, or by a writer laying them out differently (which bumps the layout version), get different superblocks. test_erofs_pull_builds_reproducible_images now also pulls a moved tag with one small file changed: with the previous binary its superblock equals the original's; now only the UUID differs. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
Review of #68263 (xyuzh, Cursor Bugbot): - rapidgzip comes from its upstream library, mxmlnkn/librapidarchive at rapidgzip-v0.16.1, through Ray's own small C API (src/gzip.cpp, Rust side src/gzip.rs), instead of the third-party rapidgzip-rs crates. It is header-only and builds as a plain cc_library against Ray's zlib, so the rules_foreign_cc build, its CMake patch, ISA-L and rpmalloc are all gone. The shim reads a layer through a FileReader that waits for the bytes to download, turns on gzip's CRC checks, and keeps C++ exceptions from crossing into Rust. Images are byte-identical to before (pytorch/pytorch and python:3.12), at the same speed and memory. - Entries erofs-pull doesn't model as tarfile does (GNU sparse files, PAX GNU.sparse.* records, global headers and the like) are an error, so extraction builds the layer, instead of being dropped or garbled. - A member whose parent is a file fails the build, as extraction fails the pull, instead of being dropped (hard links included). - Error messages drop URLs' query strings, so a presigned storage URL's signature doesn't reach the worker's log; HTTP error bodies are cut short. - erofs-pull dies with the worker that started it (PR_SET_PDEATHSIG, and an exit when the parent pid Python passes is already gone). - Decoding uses at most 16 threads (pytorch/pytorch: 1.1 GB on 32 threads, 0.8 GB on 16, same time; 8 threads cost 0.8 s), and a node runs at most max(2, CPUs / 8) builds at once, others waiting for a slot (RAY_SANDBOX_EROFS_PULL_MAX_CONCURRENT changes it). - A proxy user name with ':' is refused, as ureq can't carry it; other credentials already worked, as ureq parses the host after the last '@'. Each new test (sparse layers in GNU and PAX format, a file in the way, killing the worker mid-pull) fails with the previous binary. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
The sandbox docs still said every node needs mkfs.erofs, that images are built with it, and that a rebuilt image can't take a checkpoint. A new "Build images" section covers erofs-pull: what it does, when Ray extracts instead, and the RAY_SANDBOX_EROFS_PULL and RAY_SANDBOX_EROFS_PULL_MAX_CONCURRENT settings. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
|
@xyuzh Thanks a lot for the review, I believe everything should now be addressed: Review summaryThanks for the thorough review, the aarch64 run and the fuzzer. Everything inline is addressed below. The description's numbers are re-run on the current branch (cold pulls of erofs.rs:149 (4607250150): zero UUIDFixed in 81f9312, as you suggested: the UUID is the first 16 bytes of a SHA-256 over a layout version, the block size and the layer digests in manifest order (an RFC 9562 version 8 UUID). Builds of the same layers stay byte-identical; the reproducibility test now also pulls a moved tag with one small file changed at the same size, whose superblock equalled the original's before and now differs in the UUID. Agreed that #67484 needs the same for Cargo.toml:15 (4607250157): where rapidgzip comes fromDone in f6f3674: rapidgzip now comes from its upstream library, image_utils.py:1454 (4607250161): memory per pullTwo changes. 38b3756 builds rapidgzip without rpmalloc, which kept freed memory per thread: a PyTorch pull peaked at 2.5 GB with it and 1.1 GB without. f6f3674 caps decoding at 16 threads and limits a node to
8 threads cost PyTorch about 0.8 s here, so the cap is 16 (all cores on smaller nodes). Eight images pulled at once now peak at 1.9 GB, down from 4.8 GB; for #67493's 32 concurrent pulls on a 60-CPU node, 7 build at a time, roughly 6 GB at most. image_utils.py:1470 (4607250167): erofs-pull outliving its workerFixed in f6f3674: layer.rs:179 (4607250176): sparse files and other unmodeled entriesFixed in f6f3674: any entry type erofs-pull doesn't model is an error (GNU sparse tree.rs:273 (4607250185): a file in the way of a parentFixed in f6f3674: a member whose parent is a file fails the build, for files, directories, symlinks and hard links alike, as extraction fails the pull; the seeds keep skipping, as fetch.rs:524 (4607250193): presigned URLs in the warningFixed in f6f3674: error messages drop every URL's query string before they leave the binary, and HTTP error bodies are cut to 300 characters. A unit test feeds it ureq's message format with an |
CI's clang builds (Java, C++ worker and data jobs) failed compiling
erofs-pull's rapidgzip shim: rapidgzip computes its lookup tables at
compile time, and clang 14 stopped at its default of 1M constexpr steps
("constexpr evaluation hit maximum step limit"). GCC's default limit was
enough, so the core builds passed.
The shim now gets the limits rapidgzip's own build sets: clang's
-fconstexpr-steps or GCC's -fconstexpr-ops-limit, 99000100, picked by
the toolchain's compiler. clang 14 reproduces the failure without the
flag and compiles the shim with it.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Philipp Moritz <[email protected]>
CI's sandbox tests failed in test_erofs_baked_ownership_and_chown: its helper calls _extract_image_layers to get busybox as a tree, and with erofs-pull in the wheel the call built an EROFS image instead and left the tree empty, so the test's image had no sleep. _extract_image_layers extracts again unless its caller passes the EROFS image it builds (the new erofs_image argument), which only pull_and_extract_container_image does; it then also checks for mkfs.erofs, which only that caller needs. A new test extracts a registry image with erofs-pull available. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
test_mount_script_mounts_tmpfs_image_then_overlay[HOST-FUSE] failed in CI: the overlay's root had mode 0755, not the image root's 0751. The mount script runs erofsfuse in the background and waits until mountpoint says the image is mounted, but the fake mountpoint said so at once, so the script could copy the lower directory's attributes before the fake erofsfuse had "mounted" (chmod 751). A fake erofsfuse that sleeps half a second reproduces it. The fake mountpoint now answers yes only once the image root is in place, as the real one does, and the tests that replace the fake erofsfuse mount the image root too. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>
Resolve conflicts with #68088, which removed the readonly option and _seed_mountpoints. erofs-pull no longer seeds the mount points either, so its images still match the ones extraction builds with mkfs.erofs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-pull's registry test #68088 removed the mount-point seeds, so a pulled busybox has no /etc/resolv.conf anymore. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
❌ 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 265d05d. Configure here.
| self.fetch_whole(remote, &url, auth) | ||
| } else { | ||
| Ok(()) | ||
| }; |
There was a problem hiding this comment.
Range-ignore path downloads layers twice
Medium Severity
The probe always issues Range: bytes=0-0 and treats a 200 as “this server ignores ranges.” That response already carries the whole blob, but it is dropped and fetch_whole requests the same URL again. On registries or mirrors that ignore Range, every layer is transferred twice, which is the path this code is meant to support.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 265d05d. Configure here.
| raise SandboxCreationError( | ||
| f"erofs-pull failed to build image '{image}' (its error is " | ||
| f"logged above), and extracting it needs mkfs.erofs: {err}" | ||
| ) from None |
There was a problem hiding this comment.
Missing layer sizes blamed on erofs-pull
Low Severity
When the manifest omits layer sizes, _build_image_with_erofs_pull returns False without logging. If mkfs.erofs is also missing, the raised error still says erofs-pull failed and that its error was logged above, even though erofs-pull never ran.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 265d05d. Configure here.
andrewsykim
left a comment
There was a problem hiding this comment.
Verified this PR locally and end-to-end on a 4-node kind cluster with KubeRay (v1.7.2), including Bazel/Rust tests (12/12), Python sandbox unit tests, erofsfuse-mounted entry-for-entry parity checks on python:3.12-slim (5,575/5,575 entries, 13–15.5× local cold-pull speedup) and ubuntu:24.04 (3,444/3,444 entries, 9.1–9.9× speedup), RayJob execution, proxy/TLS/auth/redirect flows, checkpoint/restore after cache eviction, and PR_SET_PDEATHSIG + ENOSPC cleanup.
Left inline comments on the issues and edge-case discrepancies reproduced during testing.
| try: | ||
| require_mkfs_erofs() | ||
| except SandboxCreationError as err: | ||
| if _erofs_pull_binary() is None: | ||
| raise | ||
| raise SandboxCreationError( | ||
| f"erofs-pull failed to build image '{image}' (its error is " | ||
| f"logged above), and extracting it needs mkfs.erofs: {err}" | ||
| ) from None |
There was a problem hiding this comment.
Bug (misleading error when manifest omits layer size and mkfs.erofs is absent):
When a manifest lacks size on layer descriptors, _build_image_with_erofs_pull() (lines 1461–1464) returns False immediately without invoking erofs-pull or logging a warning. If mkfs.erofs is missing, require_mkfs_erofs() raises SandboxCreationError, and this except block sees _erofs_pull_binary() is not None and overwrites it with:
erofs-pull failed to build image '...' (its error is logged above), and extracting it needs mkfs.erofs: ...
even though erofs-pull never ran and nothing was logged above.
Repro: Verified with a synthetic manifest omitting layer["size"] and no mkfs.erofs on PATH.
Suggestion: Only wrap the require_mkfs_erofs() error with the erofs-pull failed... message when erofs-pull was actually invoked.
| // urllib's _splitport: a trailing ":<digits>" is the port. | ||
| let hostonly = match host.rsplit_once(':') { | ||
| Some((name, port)) if port.bytes().all(|c| c.is_ascii_digit()) => name, | ||
| _ => host.as_str(), | ||
| }; | ||
| for name in no_proxy.split(',') { | ||
| let name = name.trim().trim_start_matches('.').to_lowercase(); | ||
| if name.is_empty() { | ||
| continue; | ||
| } | ||
| if hostonly == name || host == name { | ||
| return true; | ||
| } | ||
| let suffix = format!(".{name}"); | ||
| if hostonly.ends_with(&suffix) || host.ends_with(&suffix) { | ||
| return true; | ||
| } | ||
| } | ||
| false |
There was a problem hiding this comment.
Bug (IPv6 NO_PROXY bracket mismatch):
rsplit_once(':') strips :port while leaving square brackets on [::1], so NO_PROXY="::1" does not match http://[::1]:<port> (only NO_PROXY="[::1]" matches).
Repro: Verified directly against http://[::1]:<port>: NO_PROXY="::1" routed through the proxy instead of bypassing it, whereas NO_PROXY="[::1]" bypassed it.
Suggestion: Strip surrounding [ and ] from hostonly (and name) before comparing.
| let (mut url, mut auth) = (self.url.clone(), true); | ||
| for _hop in 0..5 { | ||
| let resp = request(remote, &url, auth, Some((0, 0)))?; | ||
| match resp.status() { | ||
| 301 | 302 | 303 | 307 | 308 => { | ||
| let loc = resp.header("location").ok_or("redirect without location")?; | ||
| url = join_url(&url, loc); | ||
| auth = false; | ||
| } |
There was a problem hiding this comment.
Bug (same-host redirects unconditionally drop Authorization and registry headers):
resolve() sets auth = false on any 301/302/303/307/308 redirect, even when the redirect stays on the same scheme/host/port.
Repro: A same-host 307 redirect on a registry requiring Authorization on the redirected target failed with HTTP 401 in erofs-pull (falling back to Python extraction, which succeeded).
Suggestion: Only drop auth when the redirect changes origin (scheme/host/port), matching urllib.
| 200 => { | ||
| return Ok(Resolved { | ||
| url, | ||
| auth, | ||
| ranged: false, | ||
| }) | ||
| } | ||
| s => return Err(format!("{}: answered {s}", self.digest)), | ||
| } | ||
| } | ||
| Err(format!("{}: too many redirects", self.digest)) | ||
| }) | ||
| .clone() | ||
| } | ||
|
|
||
| /// Downloads chunk `k`: by range, or, where the server ignores ranges, | ||
| /// the whole blob in one stream (chunk 0's task; the others have nothing | ||
| /// to do). | ||
| fn fetch_chunk(&self, remote: &Remote, k: usize) -> Result<(), String> { | ||
| let Resolved { url, auth, ranged } = self.resolve(remote)?; | ||
| if !ranged { | ||
| return if k == 0 { | ||
| self.fetch_whole(remote, &url, auth) | ||
| } else { | ||
| Ok(()) | ||
| }; |
There was a problem hiding this comment.
Performance (non-Range 200 OK servers trigger two full GETs per uncached layer):
resolve() probes with Range: bytes=0-0. When a server ignores Range and replies 200 OK, resolve() drops that response (closing the connection mid-stream) and fetch_whole() issues a second GET for the entire blob.
Repro: Verified via mock registry request logs (edge/non-range:1.0 and oci-lab): every uncached layer generated 2 blob GET requests.
Suggestion: If resolve() receives 200 OK on chunk 0's probe, stream that response body directly in fetch_whole instead of dropping and re-requesting it.
| for (hash, blob) in hashes.into_iter().zip(&unique) { | ||
| match hash.map(|h| h.join().unwrap()).transpose() { | ||
| Ok(t) => hashed.push((blob.digest.clone(), t)), | ||
| Err(e) => { | ||
| error.get_or_insert(format!("{}: {e}", blob.digest)); | ||
| } | ||
| } | ||
| } | ||
| let mut layers = Vec::new(); | ||
| let mut timings = Vec::new(); | ||
| for (build, blob) in workers.into_iter().zip(&blobs) { | ||
| let h = Ok(hashed.iter().find(|(d, _)| *d == blob.digest).and_then(|(_, t)| *t)); | ||
| match (h, build.join().unwrap()) { | ||
| (Ok(h), Ok((entries, t))) => { | ||
| timings.push(serde_json::json!({ | ||
| "digest": blob.digest, "size": blob.size, "cached": blob.cached(), | ||
| "downloaded_ms": h.map(ms), "built_ms": ms(t), "entries": entries.len(), | ||
| })); | ||
| layers.push(entries); | ||
| } | ||
| (Err::<_, io::Error>(e), _) | (_, Err(e)) => { | ||
| error.get_or_insert(format!("{}: {e}", blob.digest)); | ||
| } | ||
| } | ||
| } | ||
| for d in downloads { | ||
| d.join().unwrap(); | ||
| } | ||
| if let Some(e) = error { | ||
| unique.iter().for_each(|b| b.discard()); | ||
| let _ = std::fs::remove_file(&spec.out); | ||
| return Err(e); |
There was a problem hiding this comment.
Performance (early-layer fallback still downloads all remaining layers before exiting):
When layer 0 fails read_layer() (e.g., PAX global header 'g' or a >255B name), main() still joins all hashes and downloads for subsequent layers before returning Err and falling back to Python extraction.
Repro: Verified with a multi-layer image where layer 0 had a PAX global header: erofs-pull downloaded and cached layer 1 to completion before exiting 1.
Suggestion: Signal cancellation (e.g., an AtomicBool checked in fetch_chunk/fetch_whole and worker threads) as soon as any read_layer() returns an unrecoverable fallback error.
| let Some(target) = self.lookup(&ldir).and_then(|d| self.child(d, &lbase)) else { | ||
| return Ok(()); | ||
| }; | ||
| if self.is_dir(target) { | ||
| return Ok(()); | ||
| } | ||
| if parent.iter().any(|c| c.len() > MAX_NAME) { | ||
| return Err(too_long()); | ||
| } | ||
| if base.len() > MAX_NAME { | ||
| return Ok(()); | ||
| } | ||
| let Some(p) = self.makedirs(&parent) else { | ||
| return Err(not_a_directory()); | ||
| }; | ||
| self.children(p).unwrap().insert(base, target); | ||
| return Ok(()); |
There was a problem hiding this comment.
Minor parity difference (hardlink owner mismatch):
If a tar layer adds a hardlink with a different uid/gid than its target, erofs-pull keeps the target entry's uid/gid, whereas extract_tar_layer + _stream_tree takes whichever hardlink path sorts first alphabetically (reproduced locally and in KubeRay).
| if base.len() > MAX_NAME { | ||
| return match kind { | ||
| NodeKind::Sym(_) => Ok(()), | ||
| _ => Err(too_long()), | ||
| }; | ||
| } | ||
| let Some(p) = self.makedirs(&parent) else { | ||
| return Err(not_a_directory()); | ||
| }; |
There was a problem hiding this comment.
Minor parity differences (>255B symlink parent dir & . regular file):
- For a symlink with a
>255Bbasename in a missing parent directory, returningOk(())at line 276 skipsself.makedirs(&parent)(line 280), whereas Python extraction creates the parent directory beforeos.symlinkfails. - At lines 177–186, a
REGTYPEentry named.is silently ignored here, whereas Pythonextract_tar_layerraisesIsADirectoryError.
| * **gVisor (`runsc`)**: Install the `runsc` binary on worker nodes and make it reachable from the system `$PATH`. | ||
| * **Ray**: version 2.58.0 or later, which includes the `ray.experimental.sandbox` package. | ||
| * **erofs-utils**: `mkfs.erofs` 1.7 or later on the `$PATH`. Ray caches each image as an EROFS file that gVisor mounts inside its own kernel, so files in the sandbox keep the image's real owners and `chown` works for any uid, with no privileges or id mappings on the node. Sandbox creation fails without it. | ||
| * **erofs-utils**: `mkfs.erofs` 1.7 or later on the `$PATH`, for local image archives and for registry images that Ray's own image builder hands back. Ray caches each image as an EROFS file that gVisor mounts inside its own kernel, so files in the sandbox keep the image's real owners and `chown` works for any uid, with no privileges or id mappings on the node. On Linux, Ray builds registry images with erofs-pull, which ships with Ray and needs no erofs-utils, so a node without `mkfs.erofs` can still run most images. For details, see [Build images](#build-images). Sandbox creation fails when Ray needs `mkfs.erofs` and can't find it. |
There was a problem hiding this comment.
Doc vs. runtime mismatch (overlayfs mode still requires mkfs.erofs):
This states a node without mkfs.erofs "can still run most images", but in overlayfs mode overlayfs._probe_mount() (python/ray/experimental/sandbox/_internal/overlayfs.py#L810-L811) calls image_utils.build_erofs_image(empty, {}, image) → require_mkfs_erofs() and raises SandboxCreationError when mkfs.erofs is missing—even with erofs-pull present.
Repro: Calling _probe_mount(UserNamespaceType.HOST, ImageMountMode.FUSE) with mkfs_erofs_path = lambda: None raised SandboxCreationError.
Suggestion: Clarify here that mkfs.erofs is still required when overlayfs mode probes mounts, or build the empty probe EROFS image without mkfs.erofs.
| * **Egress allowlist:** a checkpoint saves the allowlist in force when it's taken, including changes from `set_egress_allowlist()`. | ||
| * **Checkpoint path:** `checkpoint()` replaces an earlier checkpoint at the same path, but refuses a non-empty directory that doesn't hold one. | ||
| * **Image builds:** gVisor restores only onto the same build of the sandbox's image. If the image was evicted from the cache and rebuilt, or its tag moved, since the checkpoint, restore fails with an error that says so. | ||
| * **Image builds:** gVisor restores only onto the same build of the sandbox's image. erofs-pull builds the same image identically on every node, so a checkpoint restores onto a rebuild of it, after eviction or on another node. If the image's tag moved since the checkpoint, or the image was built a different way, by extraction or by another Ray version, restore fails with an error that says so. |
There was a problem hiding this comment.
Doc vs. runtime mismatch (cross-node checkpoint restore):
This notes "a checkpoint restores onto a rebuild of it, after eviction or on another node", while python/ray/experimental/sandbox/backend/gvisor.py#L2057-L2069 still enforces checkpoint_node_id == current_node_id ("Checkpoints are node-local").
Suggestion: Clarify this phrasing so it aligns with gvisor.py and line 569 above.
| linkopts = [ | ||
| "-lstdc++", | ||
| "-lc", | ||
| ], |
There was a problem hiding this comment.
Packaging note (dynamic libc/libstdc++ symbol versions):
Because erofs_pull links libc and libstdc++ dynamically, the build host's GLIBC/GLIBCXX version constrains target OS compatibility: building on Debian (GLIBC 2.43) produced a binary requiring GLIBC_2.39 / GLIBCXX_3.4.32 that failed to run on Ubuntu 22.04 (GLIBC 2.35), whereas building inside Ubuntu 22.04 required max GLIBC_2.34 / GLIBCXX_3.4.30 and worked. Ensure release wheels build erofs_pull inside the manylinux/lowest-supported GLIBC environment.
|
|
||
| Ray verifies downloaded image layers against their digests and stores them in `/tmp/ray/sandbox/images/.blobs/sha256/<digest>`. Images and tags that share layers reuse these files. Rebuilding an evicted image downloads only layers the node no longer has. Concurrent pulls of the same layer, from any process on the node, download it once. A cached image's EROFS file doesn't depend on its layers, so evicting layers doesn't affect a running sandbox. | ||
|
|
||
| ### Build images |
There was a problem hiding this comment.
Is it really "building images" though, wouldn't "Pulling images" still be more accurate?
| url = "https://github.com/bazelbuild/rules_foreign_cc/archive/refs/tags/0.9.0.tar.gz", | ||
| ) | ||
|
|
||
| # Rust, for //src/ray/sandbox/erofs_pull (Ray Sandbox's image builder). |
There was a problem hiding this comment.
Is this the first Rust build target introduced in Ray 2.0?
| fn join_url(base: &str, location: &str) -> String { | ||
| if location.contains("://") { | ||
| return location.to_string(); | ||
| } |
There was a problem hiding this comment.
Bug: relative redirect Location containing :// in query string fails to resolve
join_url treats any location containing "://" anywhere in the string as an absolute URL. A relative redirect whose query string embeds a URL—for example Location: /storage/blob?next=http://example.com&d=<digest>—returns the un-joined relative path and fails with:
Bad URL: failed to parse URL: RelativeUrlWithoutBase: relative URL without a base
Reproduced both locally and in KubeRay (rel-redirect-query/busybox:v1), where it forced fallback to extraction + mkfs.erofs (and failed on workers-no-erofs). Parsing url::Url::parse(base)?.join(location) (or checking for a valid RFC 3986 scheme prefix before : instead of contains("://")) fixes this.
| let loc = resp.header("location").ok_or("redirect without location")?; | ||
| url = join_url(&url, loc); | ||
| auth = false; | ||
| } |
There was a problem hiding this comment.
Bug: same-origin redirects unconditionally drop Authorization and registry headers
Blob::resolve sets auth = false on every 301/302/303/307/308 redirect even when the redirect stays on the same scheme/host/port. Reproduced locally and in KubeRay (bearer-samehost/busybox:v1): a same-host 307 redirect stripped the Bearer token and failed with HTTP 401 (missing/bad auth after same-host redirect: None). Dropping auth only when scheme/host/port changes preserves cross-host credential stripping while fixing same-origin redirects.
| return true; | ||
| } | ||
| } | ||
| false |
There was a problem hiding this comment.
Bug: IPv6 NO_PROXY entries without brackets fail to match bracketed URLs
proxy_bypass strips :port via rsplit_once(':'), leaving [::1] with square brackets. Consequently, NO_PROXY="::1" fails to bypass http://[::1]:<port> (routed through the proxy and failed with HTTP 502 locally), whereas NO_PROXY="[::1]" bypasses it. Stripping surrounding [ and ] on both hostonly and name resolves this.
| self.fetch_whole(remote, &url, auth) | ||
| } else { | ||
| Ok(()) | ||
| }; |
There was a problem hiding this comment.
Bug / performance: non-Range (200 OK) servers trigger two GET requests per uncached layer
Blob::resolve probes with Range: bytes=0-0. When the server ignores Range and returns 200 OK, resolve drops that response and fetch_chunk(0) calls fetch_whole, issuing a second un-ranged GET. Reproduced locally and in KubeRay (non-range-200/busybox:v1: Range headers observed were ['bytes=0-0', None]). Reusing the 200 OK response stream from resolve avoids downloading/re-requesting twice.
| if user.contains(':') { | ||
| return Err("a proxy user name with ':' isn't supported".into()); | ||
| } | ||
| let authorization = format!("Basic {}", base64(format!("{user}:{password}").as_bytes())); |
There was a problem hiding this comment.
Compatibility note: ureq/2.12.1 emits lowercase Proxy-Authorization: basic ...
During KubeRay HTTPS_PROXY CONNECT testing, ureq sent Proxy-Authorization: basic <token> on the wire (observed via socket capture), whereas urllib sends Basic <token>. RFC 7617 schemes are case-insensitive, though proxies doing a strict case-sensitive check for Basic reject erofs-pull with 407 (Provided proxy credentials are incorrect) while accepting urllib.
| if let Some(e) = error { | ||
| unique.iter().for_each(|b| b.discard()); | ||
| let _ = std::fs::remove_file(&spec.out); | ||
| return Err(e); |
There was a problem hiding this comment.
Resource waste / leftover partials on failure or SIGKILL:
- Early-layer fallback: When layer 0 fails (e.g.,
>255Bregfile name),main()still joins all remaininghashesanddownloads, downloading and committing later layers toblob_dirbefore returningErr. SIGKILLmid-pull: Killing a pulling Ray worker (ray.kill(..., no_restart=True)in KubeRay) terminateserofs-pullviaPR_SET_PDEATHSIGwithout deadlocking subsequent pulls, but leaves.blobs/sha256/.partial-<digest>-erofs-pull-<pid>behind on disk.
| layers = manifest["layers"] | ||
| if binary is None or not all( | ||
| isinstance(layer.get("size"), int) for layer in layers | ||
| ): |
There was a problem hiding this comment.
Bug: isinstance(True, int) lets boolean layer["size"] pass pre-check
In Python isinstance(True, int) is True. A manifest with "size": true passes this check and fails inside erofs-pull with bad spec: invalid type: boolean true, expected u64. Using isinstance(size, int) and not isinstance(size, bool) (and size >= 0) avoids spawning erofs-pull.
| raise SandboxCreationError( | ||
| f"erofs-pull failed to build image '{image}' (its error is " | ||
| f"logged above), and extracting it needs mkfs.erofs: {err}" | ||
| ) from None |
There was a problem hiding this comment.
Bug: misleading error when manifest omits layer["size"] and mkfs.erofs is absent
When layer["size"] is missing, _build_image_with_erofs_pull returns False immediately without invoking erofs-pull or logging a warning. Because _erofs_pull_binary() is not None, this handler raises erofs-pull failed to build image '...' (its error is logged above), and extracting it needs mkfs.erofs: ... even though erofs-pull never ran and nothing was logged above.
| * **gVisor (`runsc`)**: Install the `runsc` binary on worker nodes and make it reachable from the system `$PATH`. | ||
| * **Ray**: version 2.58.0 or later, which includes the `ray.experimental.sandbox` package. | ||
| * **erofs-utils**: `mkfs.erofs` 1.7 or later on the `$PATH`. Ray caches each image as an EROFS file that gVisor mounts inside its own kernel, so files in the sandbox keep the image's real owners and `chown` works for any uid, with no privileges or id mappings on the node. Sandbox creation fails without it. | ||
| * **erofs-utils**: `mkfs.erofs` 1.7 or later on the `$PATH`, for local image archives and for registry images that Ray's own image builder hands back. Ray caches each image as an EROFS file that gVisor mounts inside its own kernel, so files in the sandbox keep the image's real owners and `chown` works for any uid, with no privileges or id mappings on the node. On Linux, Ray builds registry images with erofs-pull, which ships with Ray and needs no erofs-utils, so a node without `mkfs.erofs` can still run most images. For details, see [Build images](#build-images). Sandbox creation fails when Ray needs `mkfs.erofs` and can't find it. |
There was a problem hiding this comment.
Doc accuracy: overlayfs mode still requires mkfs.erofs even when erofs-pull is present
Verified on a worker node with erofs-pull and no erofs-utils (workers-no-erofs): default runsc EROFS sandboxes succeed, but sandboxes that trigger kernel overlayfs (e.g., an _oci_spec_transform_fn prestart hook) fail in overlayfs._probe_mount(), which calls image_utils.build_erofs_image → require_mkfs_erofs() even when KERNEL loop mount would otherwise be used.
| * **Egress allowlist:** a checkpoint saves the allowlist in force when it's taken, including changes from `set_egress_allowlist()`. | ||
| * **Checkpoint path:** `checkpoint()` replaces an earlier checkpoint at the same path, but refuses a non-empty directory that doesn't hold one. | ||
| * **Image builds:** gVisor restores only onto the same build of the sandbox's image. If the image was evicted from the cache and rebuilt, or its tag moved, since the checkpoint, restore fails with an error that says so. | ||
| * **Image builds:** gVisor restores only onto the same build of the sandbox's image. erofs-pull builds the same image identically on every node, so a checkpoint restores onto a rebuild of it, after eviction or on another node. If the image's tag moved since the checkpoint, or the image was built a different way, by extraction or by another Ray version, restore fails with an error that says so. |
There was a problem hiding this comment.
Doc mismatch: gvisor.py still enforces node-local checkpoints
Line 574 states that erofs-pull allows a checkpoint to restore "on another node", whereas GVisorSandboxBackend.restore_sandbox (backend/gvisor.py) still raises SandboxError whenever checkpoint_node_id != current_node_id ("Checkpoints are node-local: restore on the node that took it", verified in KubeRay Suite 3).
|
@pcmoritz This is very useful. Thanks. Besides the speedup, I would not discount the reduction in node resources (CPU / IO). This generally gives resources back to do more work (i.e. reduces infra overhead). The one caveat, of course, is the increased memory pressure; there are workloads where node memory is the limiting factor. So limits / caps would be important to use this feature reliably.
Can we plug erofs-pull into cgroup limits that can be adjusted dynamically? Running erofs-pull in its own cgroup under RAY_SANDBOX_CGROUP_PATH (low cpu.weight, adjustable memory.max/memory.high), with its decode threads and concurrency derived from that cgroup's limits rather than fixed numbers? |
…probe, docs
- Keep the registry's credentials on redirects that stay on its origin
(scheme, host and port); drop them only when a redirect leaves it.
- Treat a redirect's Location as absolute only if it starts with a
scheme, so "/blob?next=http://..." resolves against the registry.
- Match IPv6 hosts in no_proxy with or without brackets ("::1" now
matches "[::1]:5000").
- When a server ignores Range and answers the probe with the whole blob,
read that response instead of requesting the blob a second time.
- Don't blame erofs-pull for a failed pull it never ran (a manifest
without layer sizes), and don't take a bool as a layer size.
- Docs: overlayfs root filesystems still need mkfs.erofs; checkpoints
stay node-local; "Build images" is now "Pull images".
- Move test_image_utils.py's __main__ block to the end of the file.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Philipp Moritz <[email protected]>
…est it under umask 022
Two changes in the previous commit broke erofs-pull's parity with
extraction, whose urllib requests it is meant to match:
- Drop the registry's credentials on every redirect again, same host or
not, as `_registry_request` does. Keeping them on same-origin
redirects failed the fake Docker Hub tests, whose storage refuses a
second auth; extraction gets the same 401 where same-host storage
wants the token.
- Keep IPv6 hosts' brackets in no_proxy matching, as urllib does
("[::1]" matches "[::1]:5000", "::1" doesn't), so erofs-pull goes
through the proxy exactly where Ray's own registry requests do.
Tests:
- The erofs_pull fixture sets umask 022: extraction makes missing parent
directories 0o777 & ~umask, erofs-pull 0o755 on every node, so the
comparisons failed under umask 002.
- Check that storage ignoring Range gets one request per layer.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Philipp Moritz <[email protected]>
|
@andrewsykim Thanks for your review, I addressed the applicable comments now! Can you have another look / approve the PR? |
| let (address, authorization) = parse_proxy(url)?; | ||
| let proxy = ureq::Proxy::new(address) | ||
| .map_err(|e| format!("unsupported {scheme} proxy {:?}: {e}", redact(url)))?; | ||
| proxied.insert(scheme.to_string(), (agent(timeout, Some(proxy)), authorization)); |
There was a problem hiding this comment.
Bug: bracketed IPv6 proxy URLs (http://[::1]:<port>) fail in erofs-pull while succeeding in urllib
ureq 2.12.1's Proxy::parse_address splits the proxy host on ':' without bracketed IPv6 handling, turning "[::1]:40567" into server = "[" and port = 80. When http_proxy=http://[::1]:<port> or https_proxy=http://[::1]:<port> is set, Proxy::new succeeds, and every HTTP / HTTPS CONNECT request then fails at connect time with:
Dns Failed: resolve dns name '[:80': failed to lookup address information: Name or service not known
Repro: Verified in fresh worker subprocesses locally and in KubeRay against a local AF_INET6 HTTP/CONNECT proxy (http://[::1]:40567): Python extraction (RAY_SANDBOX_EROFS_PULL=0) succeeded (rc=0) for both HTTP and HTTPS pulls, whereas erofs-pull failed every request (failing the pull outright when mkfs.erofs is absent).
Suggestion: Since a proxied ureq::Agent only invokes its Resolver on format!("{}:{}", proxy.server, proxy.port) (ureq/src/stream.rs), parse_proxy / agent() can support bracketed IPv6 proxy literals directly by passing a placeholder hostname + port to ureq::Proxy::new and configuring AgentBuilder::resolver(...) to resolve that netloc via ToSocketAddrs on the bracketed "[v6]:port".
| (f, false) | ||
| } | ||
| }; | ||
| let nchunks = if cached { 0 } else { size.div_ceil(chunk) as usize }; |
There was a problem hiding this comment.
Bug: zero-byte manifest layer descriptors ("size": 0) skip HTTP requests entirely and diverge from extraction
When a manifest lists a layer descriptor with "size": 0 and "digest": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" (SHA-256 of b""), size.div_ceil(chunk) is 0. As a result, download_all issues zero HTTP requests to the registry (never checking whether the blob exists or is authorized), hash_blob hashes 0 bytes and calls commit() (publishing an unrequested 0-byte file in .blobs/sha256/), and tar::Archive accepts 0 bytes as an empty archive (rc=0).
Repro: Verified against a local OCI registry in two modes (zero404 returning 404 on /blobs/sha256:e3b0... and zero200 returning an empty 200 OK body): in both modes erofs-pull made 0 blob HTTP requests and succeeded (rc=0), whereas Python extraction (RAY_SANDBOX_EROFS_PULL=0) requested the blob URL and failed (HTTP Error 404 and tarfile.ReadError('empty file'), respectively, since valid empty tar archives are at least two 512-byte zero blocks).
Suggestion: Reject size == 0 in erofs-pull (or require size > 0 in _build_image_with_erofs_pull's layer-size pre-check) so 0-byte descriptors go through extraction and fail consistently after checking the registry.
| let host_end = base[scheme_end..].find('/').map_or(base.len(), |i| scheme_end + i); | ||
| if location.starts_with('/') { | ||
| return format!("{}{location}", &base[..host_end]); | ||
| } | ||
| let path = &base[..host_end.max(base.rfind('/').map_or(0, |i| i + 1))]; | ||
| let sep = if path.ends_with('/') { "" } else { "/" }; | ||
| format!("{path}{sep}{location}") |
There was a problem hiding this comment.
Bug: join_url mis-resolves relative and query-only Location redirects when base has a query string
f910f63db9 fixed :// inside location's query string, but join_url still searches base for '/' without stripping base's ?query / #fragment first (find('/') on line 553 and rfind('/') on line 557), and doesn't handle RFC 3986 query-only Location (?...).
Repro: Verified three cases locally and in KubeRay where Python urllib (RAY_SANDBOX_EROFS_PULL=0) succeeds (rc=0) while erofs-pull fails (HTTP 404 / too many redirects, failing pulls on nodes without mkfs.erofs):
- Redirect hop with
/inbase's query string + relative pathLocation(common in S3/CDN URLs whereX-Amz-Credential=AKIA.../20261124/us-east-1/s3/aws4_requestcontains/):base = "http://.../cdn/dir/hop1?X-Amz-Credential=AKIAEXAMPLE/20261124/us-east-1/s3/aws4_request"withLocation: final.blobmatchesbase.rfind('/')inside the query string and requests/cdn/dir/hop1?X-Amz-Credential=AKIAEXAMPLE/20261124/us-east-1/s3/final.blobinstead of/cdn/dir/final.blob. - Root-relative
Locationwhenbasehas no/before?and/in query:base = "http://127.0.0.1:<port>?next=/a/b"withLocation: /final_blobmatchesfind('/')inside?next=/a/band requestshttp://127.0.0.1:<port>?next=/final_blobinstead ofhttp://127.0.0.1:<port>/final_blob. - Query-only
Location: ?signed=1onbase = "http://.../storage/hop-qonly/<digest>": drops the final path segment and requests/storage/hop-qonly/?signed=1(404) instead of/storage/hop-qonly/<digest>?signed=1(200).
Suggestion: Strip ? and # from base first (let base_path = base.split(['?', '#']).next().unwrap_or(base);), compute host_end and rfind('/') on base_path, and handle location.starts_with('?') as format!("{base_path}{location}").
| for e in entries { | ||
| tree.apply(e)?; | ||
| } | ||
| } | ||
| tree.seed(); | ||
| let t_tree = Instant::now(); | ||
| let digests: Vec<&str> = spec.layers.iter().map(|l| l.digest.as_str()).collect(); | ||
| let uuid = erofs::image_uuid(out.block, &digests); | ||
| let inodes = erofs::write(&tree, &out, uuid).map_err(|e| e.to_string())?; |
There was a problem hiding this comment.
Bug: erofs-pull leaves an incomplete/corrupt spec.out file on disk when run() errors outside lines 236–240
Lines 236–240 discard partial blobs and remove &spec.out on layer download/read errors, but early returns via ? at tree.apply(e)? (line 249, e.g. a file-in-the-way app + app/cfg.yaml or a >255-byte entry name) or erofs::write(&tree, &out, uuid)? (line 256, e.g. ENOSPC writing metadata) exit 1 without removing &spec.out—leaving a corrupt file containing raw file blocks and an all-zero superblock. (Similarly, lines 140–152 create/truncate &spec.out before validating block_size and return on error without removing &spec.out or calling unique.iter().for_each(|b| b.discard()).)
Repro: Running erofs-pull on a cached layer containing app (regular file) followed by app/cfg.yaml exited with returncode=1 (erofs-pull: a parent of "app/cfg.yaml" isn't a directory), leaving an 8,195-byte leftover.erofs on disk that fails fsck.erofs (rc=1).
Suggestion: While Python's _build_image_with_erofs_pull unlinks its temp out_path in finally, cleaning up spec.out (and discarding unique partials) on any Err from run() keeps erofs-pull self-cleaning if invoked directly or if the parent is interrupted right after erofs-pull exits.
erofs-pull's memory was almost all decoded data that rapidgzip holds: its 16-chunk access cache (never cleared, as ParallelGzipReader's FetchMultiStream isn't sequential), 2P prefetched and P in-flight chunks, each up to 20 times its 4 MiB of compressed input. A highly compressible layer peaked at 3.9 GB, ~54 times extraction's. - Patch rapidgzip to cache only the chunk being read: erofs-pull reads each layer once, front to back. - 1 MiB chunks, split where they decode to more than 8 MiB, and no seek index (setKeepIndex(false)), as erofs-pull never seeks. - At most 8 decoding threads instead of 16, and 4 decoded buffers queued for the tar reader instead of 16. Peak memory of a pull, before / after (16-core box, layers cached): python:3.12 ~470 MiB -> ~110 MiB PyTorch (6 GB image) ~770 MiB -> ~180 MiB 15:1-compressible ~3.9 GB -> ~370 MiB Extraction plus mkfs.erofs peaks at ~100-160 MiB on these. Images are byte for byte the same. Decoding is slower: PyTorch's layers decode at ~800 MB/s instead of ~980 MB/s, which only shows where the registry delivers faster than that (a fast node downloaded them at ~540 MB/s). Test: a 1 GiB file that compresses 15:1 builds in under 512 MiB (the previous settings peaked at 1.2 GB). Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Philipp Moritz <[email protected]>


Description
A cold image pull spends nearly all its time outside Python's control: one HTTP connection per layer, gzip decoded on one core, and every file written twice, once into an extracted tree and again into the EROFS image. This PR adds erofs-pull, a small Rust binary that builds the EROFS image straight from the registry's layers in one pass, and has
_extract_image_layersuse it when it can.Cold pulls through
pull_and_extract_container_image, each into an empty cache, from Docker Hub, on a 32 vCPU node with NVMe storage (two runs each):python:3.12pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime(6.3 GB)Eight images that share base layers (
python:3.12,python:3.11,python:3.12-slim,node:20,golang:1.23,ubuntu:22.04,ubuntu:24.04and PyTorch), pulled at once into one cache by eight processes:The images match extraction's entry for entry (type, mode, owner, size, content, symlink target, link count, file mtime), for all eight images; only the files the build seeds itself differ, in mtime. PyTorch's largest layer (3.3 GB gzipped) finishes downloading about 4 s into the pull, so the pull is limited by the network.
What erofs-pull does
Python resolves the image as before (mirrors, credential helpers, token auth, multi-arch index) and hands erofs-pull a JSON spec on stdin. erofs-pull then:
Range, a layer comes in one stream. Layers go into Ray's layer cache under its own conventions: the sameflockon<hex>.lock(taken in digest order and released as soon as that layer is verified, so concurrent pulls can't deadlock),.partial-<hex>-...files the cache cleans up when abandoned, an mtime refresh on cache hits, and a blob that takes its cache name only once its SHA-256 matches.extract_tar_layer's rules, and seeded as_seed_tmpand_seed_mountpointsdo. Last comes the metadata: uncompressed, flat-plain inodes, no inline data, block size = page size, the layout gVisor's EROFS reader supports.Builds are reproducible: two builds of the same layers are the same bytes, on any node. The superblock's build time is 0, and its UUID is a hash of a layout version, the block size and the layer digests, so a checkpoint restores onto a rebuild of its image, and never onto different content.
A pull uses erofs-pull when the binary is there (Linux wheels ship it). It extracts as before when:
RAY_SANDBOX_EROFS_PULL=0is set, or the binary is missing;tarfiledoes, such as a sparse file, a PAX global header, or a name longer than 255 bytes;Nodes without
mkfs.erofscan still pull registry images: Ray checks for it only before extracting.Other details:
max(2, CPUs / 8)erofs-pull builds at once (RAY_SANDBOX_EROFS_PULL_MAX_CONCURRENTchanges it); other pulls wait for a slot. A build takes up to about 0.8 GB (pytorch/pytorch), 0.5 GB forpython:3.12.PR_SET_PDEATHSIG).urllibuses (urllib.request.getproxies(), includingNO_PROXY), and trusts the CA certificates Python'sssldoes (SSL_CERT_FILE/SSL_CERT_DIRfromssl.get_default_verify_paths()).sha256:digests of 64 hex digits, as the layer cache does, before touching any file.Why not a merge of per-layer images (#67810)
#67810 builds one EROFS image per layer with
mkfs.erofsand merges them. Its description reports about 2× over master, but it still decodes gzip on one core per layer, writes the data twice (layer images, then the merge), and has to fall back to extraction for layers thatmkfs.erofswould merge differently from extraction: a directory over a symlink, members without their parent's entry, deleted or symlinked seeds. erofs-pull applies the layers the way extraction does, so those layers need no special case; the tests check all six against extraction. It also needs no erofs-utils on the node. If both land, the second should order them: erofs-pull, then the merge, then extraction.Build
erofs-pull is Ray's first Rust code. It builds with Bazel:
rules_rust0.70.0, the last release that supports WORKSPACE (0.71 removed it). Moving past it will need bzlmod.crate_universepins the crates (ureq, tar, sha2, serde, libc) fromsrc/ray/sandbox/erofs_pull/Cargo.lock;cargo-bazel-lock.jsonis generated (repin withCARGO_BAZEL_REPIN=1 bazel sync --only=erofs_pull_crates).mxmlnkn/librapidarchiveatrapidgzip-v0.16.1(@rapidgzip). It's header-only, so it builds as a plaincc_libraryagainst Ray's zlib, without ISA-L or rpmalloc. erofs-pull talks to it through its own small C API (src/gzip.cpp, Rust sidesrc/gzip.rs). Without rpmalloc, a PyTorch pull peaks at 1.1 GB instead of 2.5 GB, at the same speed.platforms0.0.9 → 0.0.11, becauserules_rustrefers to@platforms//os:uefi. 0.0.11 only adds constraint values.panic=abort), links only glibc, libgcc and libstdc++ dynamically, and builds for Linux only. The C++ shim lists-lstdc++ -lcas link options, which devtoolset's split libstdc++ on the manylinux images needs. Linux wheels ship the binary atray/core/src/ray/sandbox/erofs_pull/erofs_pull.Building fetches the Rust toolchain from static.rust-lang.org, the crates from crates.io,
cargo-bazelfrom GitHub, and librapidarchive from GitHub.Known limits
ubuntu:22.04comes out at 89 MB, against 86 MB from [sandbox] Build EROFS images by merging per-layer images #67810'smkfs.erofsmerge.python:3.12there; the Bazel build hasn't run on aarch64 yet (CI's aarch64 builds are manual).Related issues
Part of the Ray Sandboxing effort (#65352). Not a duplicate of #67810, the open PR on the same pull path: it takes a different approach (see above), and this PR doesn't build on it.
Additional information
Tests
On an Anyscale workspace (32 vCPU, NVMe), with this checkout's
ray.experimental.sandboxon top of an installed Ray 3.0.0.dev0, erofs-utils 1.9.4 and runsc release-20261109.0:The new tests in
test_image_utils.pyneed a real erofs-utils and the binary. They compare erofs-pull's images with extraction's, entry for entry: whiteouts, an opaque directory, hard links, owners, a directory over UsrMerge'sbin -> usr/bin, a member without its parent's entry, a symlinked/dev/shm, a repeated layer, the six layer shapes #67810's merge gets wrong, names of 255 bytes, from storage that servesRangeand storage that ignores it. Others cover the fake Docker Hub flow, proxies (an authenticating HTTP proxy,no_proxy), reproducible images and their UUIDs, bad layers and digests, sparse layers (GNU and PAX), a file in the way, names over 255 bytes, concurrent pulls sharing layers, killing the worker mid-pull, the build slots, and a node withoutmkfs.erofs. Rust unit tests coverno_proxymatching, proxy URLs, redirects, digests and error messages. Each test of a fix fails with the binary before it.By hand: the eight images above compared with extraction's;
python:3.12pulled through an authenticatingCONNECTproxy from Docker Hub; apython:3.12image booted under runsc, withsslandsqlite3importing. CI's x86_64 core builds pass.Ray's pre-commit hooks pass on the changed files.
AI assistance
This change was developed with AI assistance (Claude Code).
🤖 Generated with Claude Code