Rudder
article 02 · storage & vfs engine 2026-12-01 · 12 min read · rust vfs · sha-256 cas · fuse

Inside Rudder's Rust VFS and Content-Addressed Store: Paged Directories, Baked Images, and Bounded Read Reservations

Local OverlayFS mounts excel when the entire warm tree already sits on one host disk. When workspaces span pre-baked VM images, lazy remote roots, and crash-recoverable checkpoints, Rudder's Rust engine serves logical workspaces directly over typed SHA-256 content-addressed objects with strict memory, file-descriptor, and SQLite cursor bounds.

source engine/src/directory.rs engine/src/vfs.rs engine/src/vfs/readdir.rs engine/src/store/baked_image.rs engine/src/store/composed.rs

Typed SHA-256 references and pin-before-publish

Most content-addressed stores key blobs by a bare 32-byte digest and trust callers to interpret the payload. In a multi-agent workspace engine where untrusted build outputs, directory shards, file descriptors, and VCS projection receipts share one store, bare digests invite type-confusion bugs and premature garbage collection.

Every immutable reference in rudder-engine is a typed four-tuple ObjectRef carrying ObjectKind (Blob, File, Directory, DirectoryShard, ActionResult, etc.), HashAlgorithm::Sha256, hex digest, and exact size_bytes. Three engine-wide storage rules govern every read and write:

  • Pin before publication: Mutation callers hold a live staging retention lease across multi-page uploads until the outer root is durably pinned; readers hold either a retained root pin or an active staging lease so concurrent CAS eviction can never strip child pages mid-traversal.
  • Schema + SHA verification on read: Verifying raw SHA-256 length and digest is necessary but insufficient for structured kinds. Both LocalStore and BakedImageCas parse typed child edges via references_from_bytes(kind, &bytes) before marking a read verified.
  • O(1) logical forks: Forking a VfsView in engine/src/vfs.rs writes a root ObjectRef, a monotonic OwnerEpoch, and an empty private SQLite namespace under FULL synchronous durability. It never visits inherited directory entries or hydrates untouched file bytes.

History-independent 64 KiB byte-radix directory trees

Flat directory manifests break down at two extremes: a monorepo root with 40,000 generated files produces multi-megabyte JSON blobs that have to be rewritten on every single-file touch, while naive B-tree split/merge heuristics make a directory's hash depend on the historical order in which files were created and deleted.

In engine/src/directory.rs, DirectoryRoot (schema version 2) points to a canonical byte-radix tree of DirectoryShard objects (schema version 1) governed by deterministic structural rules:

// engine/src/directory.rs
pub const DIRECTORY_FORMAT_VERSION: u32 = 2;
pub const SHARD_FORMAT_VERSION: u32 = 1;
pub const MAX_PAGE_BYTES: usize = 64 * 1024;
pub const LEAF_ENTRIES_BYTES: u64 = 60 * 1024;
pub const LEAF_MAX_ENTRIES: u64 = 1024;
pub const MAX_OPERATION_PAGES: u64 = 8192;
pub const MAX_PATH_DEPTH: usize = 256;
  • Canonical radix invariants: Internal nodes compress maximal raw-byte common prefixes and branch on sorted terminator/byte edges. A subtree collapses into a leaf shard if and only if its canonical encoded entries total at most LEAF_ENTRIES_BYTES = 60 KiB and LEAF_MAX_ENTRIES = 1024, with every serialized shard capped at MAX_PAGE_BYTES = 64 KiB.
  • History independence: Because split and collapse thresholds depend strictly on the current set of entries rather than prior insertion order, two agents arriving at the exact same directory contents through completely different edit sequences produce byte-identical shard graphs and identical root SHA-256 digests.
  • Bounded radix updates: Inserting or deleting a path reads only the radix spine along that filename (bounded by MAX_NAME_BYTES = 255 and MAX_OPERATION_PAGES = 8192). Deletions coalesce a sibling subtree only when child entry summaries prove the merged result fits inside a single 60 KiB / 1024-entry leaf, avoiding unbounded scans of large sibling directories.
fig 02 · rust vfs + composed baked/local cas pipeline engine/src/vfs/ · engine/src/store/{composed,baked_image}.rs
FUSE WIRE ADAPTER (LINUX) PrivateMountNamespace (CLONE_NEWUSER+NS) MountedVfs (fuser session) single-thread entry · flush_handle FD VfsView (OwnerEpoch + Admission) MAX_IO = 16 MiB · MAX_IMMUTABLE_FDS = 128 NAMESPACE & READDIR PAGER SQLite FULL sync + DELETE journal DIRECTORY_PAGE_ENTRIES = 256 max 32 cursors · 128 MiB cursor DB cap IdentityBatch inode allocator 1 sqlite_sequence commit per 256-page COMPOSED READ SESSION ComposedImageStore · engine/src/store/ Bounded Read Reservations MAX_READS = 8 concurrent owners MAX_BYTES = 32 MiB active flight cap Verified BlobCache (LRU) 32 entries · 64 MiB · re-checks Stamp against openat(O_NOFOLLOW) before hit Byte-Radix Directory v2 64 KiB max shard · 60 KiB / 1024 leaf canonical prefix edges (order-agnostic) Retained Unwind Slot holds pending FD/quota on panic/cancel 1. WRITABLE LOCALSTORE private UID · 0444 immutable leaves Held root + objects + GC lock FD try_lock_shared bounded by caller fence 64 KiB read_at + streaming SHA-256 verifies inode Stamp pre & post read 2. BAKED IMAGE CAS (FLOOR) /var/lib/rudder-image-cas-v1 OwnedFd custody (no path API) 0555 dirs · 0444 leaves · nlink == 1 <= 65,536 objects · <= 2 GiB total 4 MiB chunks · 32 MiB manifest cap latching physical_failed AtomicBool
VfsView serves POSIX operations via SQLite-backed private overlays and 256-entry directory cursors, delegating immutable object reads through ComposedImageStore across the writable LocalStore and descriptor-pinned BakedImageCas.

256-entry readdir cursors and rollback-journal quotas

POSIX opendir / readdir / seekdir semantics are notoriously tricky in user-space filesystems: an agent running rg or find can hold dozens of open directory handles concurrently while mutating the directory it is scanning, or abandon cursors mid-stream. Storing full merged directory listings in Rust heap memory makes a single runaway glob an OOM vector; storing them in an unbounded SQLite WAL file leaks disk space instead.

engine/src/vfs/readdir.rs solves both problems with explicit, reconstructible cursor snapshots governed by ReaddirLimits:

readdir quota parameter default cap role in engine/src/vfs/readdir.rs
DIRECTORY_PAGE_ENTRIES 256 Fixed entries returned and committed per readdir page
max_live_cursors 32 Concurrent open directory handles holding materialized cursor state
max_cookies_per_cursor 131,072 Per-handle seekdir cookie ceiling (524,288 total across cursors)
max_total_overlay_bytes 64 MiB Cap on private overlay rows snapshotted across active directory scans
max_cursor_db_bytes 128 MiB Hard SQLite page cap using DELETE rollback journal (no unbounded WAL)
max_reserved_inodes 524,288 Monotonic namespace inode identity reservations (128 MiB metadata cap)

Two subtleties keep readdir fast without violating POSIX inode stability:

  1. Listing hints reserve identity, never content: When a directory page exposes an inherited CAS entry for the first time, it allocates a permanent monotonic inode number in readdir_identities (never swept or reused for the life of the view), without reading the child's file attributes or blob bytes until lookup or open actually touches it.
  2. Batched sequence commits (IdentityBatch): Updating SQLite's sqlite_sequence and readdir_identity_totals row-by-row for 256 inherited filenames would turn every page read into 512 internal B-tree writes. IdentityBatch reads the sequence once under the namespace transaction lock, assigns contiguous inode IDs in memory across the 256-entry batch, and writes the updated sequence and byte totals back in a single statement at page commit.

Descriptor-pinned BakedImageCas and O_NOFOLLOW custody stamps

On Rudder Cloud workers, pre-warmed toolchain and repository layers ship pre-populated at /var/lib/rudder-image-cas-v1 (up to MAX_BAKED_OBJECTS = 65_536 and MAX_BAKED_BYTES = 2 GiB, chunked into CHUNK = 4 MiB blobs plus a single <= 32 MiB root manifest). Copying 2 GiB of baked objects into each workspace's writable LocalStore on boot would defeat instant launch; trusting a raw filesystem path at runtime without checking descriptor custody would violate store isolation if anything ever mutated or symlink-swapped the backing directory.

BakedImageCas in engine/src/store/baked_image.rs eliminates path-based races altogether:

  • No path constructor: BakedImageCas::capture_retaining accepts pre-opened read-only OwnedFd handles (verified via fcntl(F_GETFL) == O_RDONLY and FD_CLOEXEC) plus an expected inventory ObjectRef and an ImageImportFence deadline.
  • openat with O_NOFOLLOW | O_DIRECTORY: Every shard directory (digest[..2], bounded to 256 open shard FDs) and leaf object (digest[2..]) is traversed strictly relative to held parent descriptors via libc::openat with O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK.
  • Kernel Stamp verification before and after I/O: Directories must match mode 0555 and expected owner UID/GID; regular object leaves must match mode 0444 and hardlink count nlink == 1. Before streaming 64 KiB read_at chunks into SHA-256 and again after EOF, Rudder checks that (dev, ino, len, mode, uid, gid, links, mtime, ctime) on both the open leaf FD and a fresh openat lookup match the original captured catalog stamp.
  • Absorbing physical failure latch: If any physical custody or checksum invariant ever trips, physical_failed: AtomicBool latches true immediately at the point of observation so a concurrent caller cancellation during error unwind can never disguise a backing store fault as a benign timeout.

ComposedImageStore and 32 MiB bounded read reservations

Above BakedImageCas and the writable LocalStore sits ComposedImageStore (engine/src/store/composed.rs). It resolves objects from the private writable store first (taking a non-blocking shared lock on the verified GC lock inode, sleeping in bounded 1 ms increments up to the caller's ImageImportFence rather than blocking indefinitely on GC) and falls through to the immutable baked floor on NotFound.

To guarantee that a burst of parallel FUSE reads or VCS tree projections cannot spike engine RSS, every in-flight object read must acquire an atomic RAII Reservation before allocating its payload buffer:

// engine/src/store/baked_image.rs (mirrored in composed.rs with MAX_BYTES = 32 MiB)
struct Reservation {
    source: Arc<BakedImageCas>,
    active: bool,
    bytes: usize,
}
impl Drop for Reservation {
    fn drop(&mut self) {
        if self.active {
            self.source.active.fetch_sub(1, Ordering::AcqRel);
        }
        if self.bytes > 0 {
            self.source.bytes.fetch_sub(self.bytes, Ordering::AcqRel);
        }
    }
}
  • Dual concurrency gates: ComposedImageStore caps simultaneous active readers at MAX_READS = 8 and simultaneous in-flight read buffers at MAX_BYTES = 32 MiB (64 MiB inside BakedImageCas to accommodate the one-time 32 MiB manifest verification).
  • Custody-verified BlobCache: Hot ordinary blobs from the baked floor are cached in a 32-entry, 64 MiB LRU (BlobCache). Even on a cache hit, VerifiedBakedBlob::current() re-verifies the held leaf FD's kernel Stamp against the parent shard directory before returning bytes.
  • Retained unwind slots (ComposedReadSession): Standard Rust traits like DirectoryStore::read(&self, ...) -> Result<Vec<u8>> return owned vectors and cannot pass back half-settled state on error. ComposedReadSession stages each read into an internal Mutex<SessionState> slot first; if an error or panic occurs mid-read, the session transitions to ComposedSessionState::Retained (or Poisoned) and preserves the exact file descriptors and byte reservation until explicit recovery transfers it via take_retained_read().
invariant · single-threaded namespace entry

In engine/src/vfs/linux.rs, PrivateMountNamespace::enter_for_current_user() verifies /proc/self/task has exactly 1 thread before calling unshare(CLONE_NEWUSER), writing setgroups = "deny" and 1-to-1 self UID/GID maps, and entering CLONE_NEWNS. Linux refuses CLONE_NEWUSER in multithreaded processes with EINVAL, so mounting happens in a dedicated single-thread bootstrap before spawning fuser::BackgroundSession.

Fence-safe FUSE teardown

When an agent finishes or its run epoch is fenced, unmounting and flushing a live FUSE view has a classic ordering trap: if cleanup tries to open a marker path through the mounted view after the view's OwnerEpoch has already been revoked by admission control, the flush itself fails with EACCES. MountedVfs acquires and holds a pre-authorized flush_handle: Option<File> while the view is initially admitted, ensuring clean FUSE session drain and unmount even after attempt authority has been fenced.

With fast copy-on-write workspaces on disk and content-addressed directory trees in Rust, the next bottleneck is version control itself: how ten parallel agents record commits, observe VFS trees without scanning files, and integrate back into a user's Git repository without fighting over .git/index.lock. That is the job of rudder-vcs-bridge in Article 03.

Fast workspaces backed by real systems engineering.

Rudder isolates parallel Claude Code, Codex, Gemini Antigravity, and OpenCode runs locally on macOS and on Linux Cloud homes, with native Mac and iPhone apps to review diffs and steer agents live.

$ npm install -g @exla/rudder@latest