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.
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
LocalStoreandBakedImageCasparse typed child edges viareferences_from_bytes(kind, &bytes)before marking a read verified. - O(1) logical forks: Forking a
VfsViewinengine/src/vfs.rswrites a rootObjectRef, a monotonicOwnerEpoch, and an empty private SQLite namespace underFULLsynchronous 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 KiBandLEAF_MAX_ENTRIES = 1024, with every serialized shard capped atMAX_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 = 255andMAX_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.
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:
- 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 untillookuporopenactually touches it. - Batched sequence commits (
IdentityBatch): Updating SQLite'ssqlite_sequenceandreaddir_identity_totalsrow-by-row for 256 inherited filenames would turn every page read into 512 internal B-tree writes.IdentityBatchreads 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_retainingaccepts pre-opened read-onlyOwnedFdhandles (verified viafcntl(F_GETFL) == O_RDONLYandFD_CLOEXEC) plus an expected inventoryObjectRefand anImageImportFencedeadline. openatwithO_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 vialibc::openatwithO_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK.- Kernel
Stampverification before and after I/O: Directories must match mode0555and expected owner UID/GID; regular object leaves must match mode0444and hardlink countnlink == 1. Before streaming 64 KiBread_atchunks 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 freshopenatlookup match the original captured catalog stamp. - Absorbing physical failure latch: If any physical custody or checksum invariant ever trips,
physical_failed: AtomicBoollatchestrueimmediately 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:
ComposedImageStorecaps simultaneous active readers atMAX_READS = 8and simultaneous in-flight read buffers atMAX_BYTES = 32 MiB(64 MiBinsideBakedImageCasto 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 kernelStampagainst the parent shard directory before returning bytes. - Retained unwind slots (
ComposedReadSession): Standard Rust traits likeDirectoryStore::read(&self, ...) -> Result<Vec<u8>>return owned vectors and cannot pass back half-settled state on error.ComposedReadSessionstages each read into an internalMutex<SessionState>slot first; if an error or panic occurs mid-read, the session transitions toComposedSessionState::Retained(orPoisoned) and preserves the exact file descriptors and byte reservation until explicit recovery transfers it viatake_retained_read().
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