PackFS: A Coalescing Linux Filesystem for Agent Workspaces
PackFS is a Linux kernel filesystem that turns virtiofs small-file storms into packed segment writes, with overlayfs compatibility, group commit, and clean checkpoints.
Most filesystem performance bugs do not announce themselves as bandwidth bugs. They show up as npm install taking too long, git checkout getting weirdly slow inside a VM, or an AI coding agent spending more time building a workspace than editing code.
PackFS came from that exact workload: lots of isolated Linux guests, each running agent code against a private overlayfs workspace, with the real storage on the host. The slow path was not “write 200 MB.” The slow path was “do hundreds of thousands of tiny namespace and file operations over virtiofs.”
Direct virtiofs is good at many things. It is not free. A CREATE, LOOKUP, WRITE, SETXATTR, FSYNC, or RELEASE is not just a local function call. It crosses from the guest kernel into the host-backed filesystem stack. One crossing is fine. Hundreds of thousands of crossings while building node_modules is the workload.
PackFS is an in-guest Linux filesystem that changes the unit of work.
Instead of making every logical file operation become a lower virtiofs operation, PackFS presents a normal VFS surface to overlayfs and packs the resulting file data and metadata into a small number of append-only lower objects:
guest process
-> overlayfs merged workspace
-> PackFS upper
-> virtiofs store mount
-> FileKv / RedbFs / host filesystemThe design is intentionally narrow. PackFS is not trying to be ext4 or XFS. It is a coalescing upper layer for disposable or semi-durable agent workspaces. It keeps the hot namespace in the guest, lets the Linux page cache do its job, and crosses the host boundary in larger, more regular writes.
The shortest mental model is: log-structured packing, but as an overlayfs upper, tuned for virtiofs boundary economics.
direct upper
lots of small crossings
PackFS upper
few packed crossings
The three important boundaries are different, and the animation above is only about one of them:
VFS boundary: process -> overlayfs -> upper filesystem
guest/host boundary: guest kernel -> virtiofs daemon / host backend
durability boundary: dirty guest state -> lower store objects forced durableDirect overlay-on-virtiofs makes the VFS boundary and guest/host boundary line up. PackFS separates them. Overlayfs still gets a normal upper filesystem. The lower virtiofs store sees PackFS’s packed physical objects instead of every logical file.
The Problem: Crossing Count, Not Bytes
The direct layout is simple:
overlayfs upperdir=/host-backed/virtiofs/upper
overlayfs workdir=/host-backed/virtiofs/workThat layout has one nice property: the host can see every file directly. It also has one expensive property: overlayfs upper operations become lower virtiofs operations at the exact granularity Linux tools naturally generate.
Small-file workloads are dominated by operations like:
lookup parent
create inode
write a few bytes
set xattrs
rename into place
close
maybe fsyncPackage managers, language servers, build tools, and coding agents all hit this pattern. A JavaScript dependency tree is the obvious example, but the same shape shows up in Python wheels, Rust build directories, generated code caches, and copy-up-heavy overlay workloads.
If the host boundary is cheap, direct overlayfs is good enough. If the host boundary has millisecond-scale tail latency or a write-through policy, the workload becomes crossing-bound. PackFS exists for that second regime.
The PackFS layout looks like this on the lower store:
store/
super.a
super.b
dirty
meta/
checkpoint.00000018
journal.00000019
seg/
000000000000002a.seg
000000000000002b.seg
loose/
...The guest-visible workspace can contain hundreds of thousands of files. The lower store sees segment files, journal generations, checkpoints, and a small amount of control metadata.
That is the tradeoff. PackFS takes responsibility for reconstructing the namespace, so the lower store does not have to see the workspace operation by operation.
What PackFS Guarantees
PackFS has two modes:
volatile
orderedThere is no strict mode. It existed in an earlier sketch, but it made the API promise too much for the first useful product shape. The two remaining modes are easier to reason about:
volatile is for ephemeral sandboxes. Mid-run guest crash means discard or refuse the dirty store. Clean unmount publishes a checkpoint that can be exported or remounted. fsync is effectively a no-op because the crash contract says the run is disposable until the final checkpoint.
ordered is for persistent workspaces. It uses an in-RAM journal ring, a commit worker, grouped journal writes, segment flushes, and committed-prefix replay. The goal is not “every syscall is immediately durable.” The goal is a mechanically defensible ordered recovery path for acknowledged barriers.
I like this split because it keeps the contract honest. A filesystem for AI agents should not silently inherit a database durability contract when the product contract is “throw away failed runs, publish successful runs.” But durable mode still has to be real when the user asks for it. PackFS keeps those two cases separate.
The VFS Surface Has To Be Real
A tempting design is to make this a FUSE filesystem in the guest, or to use tmpfs and copy everything out later. Those are useful baselines. They are not enough for the main target.
PackFS needs to be an overlayfs upper. That forces a real Linux filesystem surface:
create / unlink / rename / link
mkdir / rmdir / symlink
O_TMPFILE
RENAME_NOREPLACE
RENAME_EXCHANGE
RENAME_WHITEOUT
char device 0/0 whiteouts
trusted.overlay.opaque
stable readdir offsets
stable d_type
xattrs
real backing_dev_info writebackOverlayfs is unforgiving here. A small-looking omission becomes a correctness bug. If d_type comes back as DT_UNKNOWN, upperdir behavior changes. If whiteouts are represented incorrectly, lower files reappear. If O_TMPFILE creates an inode that recovery cannot replay, a later linkat can point at something that does not exist after mount.
PackFS also sits exactly at the filesystem stacking limit:
overlayfs
-> PackFS
-> virtiofsThat is already two layers. There is no spare layer to hide a mistake in.
The Write Path
PackFS uses the normal Linux page-cache and writeback machinery. The foreground write path is supposed to look boring:
write_begin
write_end
mark folio dirty
return to callerThe interesting work starts when Linux writeback asks PackFS to clean dirty folios.
Early versions packed per inode. That helped, but it still meant 200,000 one-page files could turn into roughly 200,000 lower writes. The current design has a superblock-level writeback stager so records from many inodes can be coalesced before they hit the lower store.
The shape is:
packfs_writepages()
-> lock dirty folio
-> copy folio payload into writeback staging memory
-> start folio writeback
-> queue staged record on sbi->wbstage.pending
-> wake stager worker
stager worker
-> drain pending records from many inodes
-> append records into one segment batch
-> write the batch to seg/<id>.seg
-> install logical extents
-> enqueue journal records in ordered mode
-> end folio writebackdirty folios
wbstage
seg/*.seg
The important invariant: folios stay under writeback until the staged bytes have a lower segment home.
There are two details I would not skip in a code review.
First, the folio stays under writeback while the staged record is only in RAM. That is deliberate. Once the extent map becomes reader-visible, a cold read must not race ahead and read stale bytes from the lower segment file. Keeping folios under writeback until the staged batch lands gives the kernel the usual invariant: clean and evictable means the backing store can satisfy the read.
Second, the stager is backpressured. It has a high-water and low-water budget, so a fast writer cannot accumulate unbounded staged data while the lower virtiofs store drains slowly. This is the difference between coalescing and just buffering until the VM falls over.
The concrete numbers today are intentionally small enough to reason about:
writeback batch cap: 1 MiB
records per batch cap: 256
stager high water: 16 MiB
stager low water: 4 MiB
DATA_INLINE fsync cap: 64 KiBThose values are not sacred. They are there to keep failure modes bounded while the format is still page-granular. One subtle implementation point: the high-water wait has an escape hatch for a staged record larger than the high-water mark so writeback cannot deadlock forever. That is acceptable only because the current record layout is capped by page-sized chunks. If PackFS grows wide records, that escape hatch has to become caller-side chunking or a hard -EFBIG/-ENOMEM path. Otherwise a performance feature turns into a memory-accounting bug.
The lower data path is append-only. File data becomes an extent:
logical inode + page index
-> segment id
-> byte offset in segment
-> length
-> generation
-> crc32cThe implementation currently stores extents in an xarray keyed by logical chunk index. That is simple and fast for page-granular replacement, and it makes overwrite semantics straightforward: a new page extent replaces the old page extent. It is not the final memory-optimal representation. Large sequential files would be much better represented as ranges, probably in a maple tree or a wider-record format. The xarray was the pragmatic first structure because PackFS’s first enemy was small-file churn, not multi-gigabyte streaming.
The implementation already avoids one common trap: stat(2) does not walk the full extent map to compute st_blocks. Each inode maintains an allocated-byte counter, updated when extents are born and retired, so metadata-heavy tools do not turn every getattr into an O(number of extents) walk.
Where The Kernel Complexity Lives
The visible idea is simple: pack tiny files. The kernel implementation is mostly about not breaking lock ordering, writeback, or recovery invariants while doing it.
Some of the important ordering rules are:
write(2): i_rwsem -> folio lock -> optional checkpoint read bracket
writeback: folio lock -> checkpoint_rwsem(read) -> journal ring append
checkpoint: checkpoint_publish_lock -> checkpoint_rwsem(write)
journal fsync: journal_lock serializes append and vfs_fsync(journal)
segment IO: no segment_lock held across lower FUSE round trips
GC: no freeing a segment that readers can refcount_inc_not_zero()The checkpoint_rwsem is the main correctness barrier. Normal journaled mutations take it for read while they make a change visible and enqueue the matching journal record. Checkpoint publish takes it for write, waits for the journal floor to converge, walks only in-memory state, then drops the lock before lower I/O. That last part matters. Holding the checkpoint lock across lower FUSE operations would create the kind of reclaim and writeback recursion path that is miserable to debug.
The per-directory stable offset map uses a maple_tree, because directory cookies are naturally range/slot-like. The extent map still uses an xarray keyed by logical chunk, because page-granular overwrite was the first correctness target. That asymmetry is not accidental. It is a local optimum, not a final theorem.
Raw Extents, Not Per-Page Record Headers
One performance lesson from the first passes was that over-framing the data path is expensive. The early format treated every page as a little record with its own data header. That made validation easy, but it inflated the cost of sequential data.
The newer raw writeback path writes regular-file payloads directly into segment space and journals them as raw extents. The record identity lives in the journal and checkpoint metadata; the segment stores the bytes. That removes avoidable per-page header reads from the hot fill path.
On read, PackFS resolves the logical chunk to a segment extent, reads the payload bytes, validates the checksum, and fills the folio. That is still not ideal for cold sequential reads: without enough readahead, the system pays one VFS read path per page. The next obvious read-side optimization is run-demux readahead: resolve a batch of adjacent extents, group by segment, and issue merged lower reads.
The point is not that PackFS magically beats virtiofs for large files. It usually should not. If the workload is “write one 128 MiB file sequentially,” direct virtiofs already batches that well. PackFS’s job is to get out of the way for large streaming files and win the namespace-heavy case.
Ordered Mode: The Journal Is The Contract
In ordered mode, PackFS cannot write segment bytes and hope for the best. The recovery rule has to be mechanical:
- Segment data that a journal record names must be durable before that record is treated as committed.
- Replay must apply a committed prefix.
- Torn journal tails must not poison future appends.
- Checkpoints must not claim an LSN that was not actually included in the snapshot.
The ordered writeback path uses a journal ring in memory. Filesystem operations format transaction frames and put them on the ring. A commit worker drains frames, writes them to the lower journal object, and advances durable_lsn only after the required lower durability work completes.
Small DATA_INLINE writes skip the segment half: the payload rides inside the journal and reaches the one-fsync floor.
The simplified barrier is:
dirty segments written
-> segment fsync / segment directory durability as needed
-> journal frames written
-> journal fsync
-> durable_lsn advancesThat sequence is conservative. It costs more than the direct path for per-file serial fsync, because PackFS may need both a segment fence and a journal fence where direct overlayfs pays one lower fsync. That showed up clearly in early benchmarks, and it is not something to hand-wave away.
The mitigation is to avoid touching segments for tiny fsyncs when possible. PackFS has an inline-data journal path for small dirty ranges:
DATA_INLINE {
ino,
generation,
logical_offset,
payload,
crc32c
}For a small file, ordered fsync can commit the bytes directly in the journal transaction. No segment was dirtied, so the segment fence disappears. Later background writeback can still pack the dirty folio into a segment and publish a normal extent. On replay, the inline record reconstructs the data if the checkpoint did not yet supersede it.
This is the filesystem version of a familiar storage trick: small synchronous data should ride with the journal when the alternative is two separate durable objects and two fences.
Checkpoints And A/B Superblocks
The journal is not the whole filesystem. PackFS also publishes checkpoints.
A checkpoint is a serialized namespace and extent snapshot:
inodes
directories
dirents
xattrs
symlinks
extent maps
segment table
watermarks
last checkpointed LSNPublishing a checkpoint is more delicate than “walk the tree and write a file.” If mutations race with the snapshot, the checkpoint can claim to include an LSN whose effect was not actually serialized. On the next mount, replay skips that journal record as already checkpointed. That is silent data loss.
The safe shape is:
flush dirty data that must be represented
enter checkpoint barrier
snapshot namespace and extents
write checkpoint temporary object
fsync checkpoint object
rename into final checkpoint name
fsync metadata directory
write one superblock slot
fsync superblockThe store has super.a and super.b. Mount chooses the newest valid superblock, verifies the checkpoint it names, then replays the journal after that checkpoint. If one superblock update tears, the other slot is still available.
Volatile mode uses the same checkpoint machinery for clean unmount. The difference is crash policy: a dirty volatile store is refused or discarded, not replayed as if it were ordered.
super.a
checkpoint K
checkpoint K
tree at LSN 40
journal suffix
mounted tree
checkpoint + committed suffix
If super.a tears, super.b still names the previous complete checkpoint.
Recovery Is Where Filesystem Sketches Usually Lie
The hard part of a filesystem is not writing data when everything goes well. The hard part is deciding what is true after power disappears at the worst possible instruction.
PackFS recovery has to answer questions like:
Did a checkpoint publish complete?
Is this journal tail torn or corrupt?
Does this DATA_EXTENT point at bytes that actually exist?
Was a directory create journaled before the child dirent?
Did a truncate race a pending writeback extent?
Can GC free this segment while a reader still holds it?That is why the design uses:
generation numbers
crc32c validation
refcount_inc_not_zero for segment lookup
RCU-delayed segment freeing
committed-prefix replay
A/B superblocks
dirty-store markers
mount-time live-byte recomputation
fail-closed GC accountingSome of those are not performance features at all. They are there because a coalescing filesystem that loses one lower write has a larger blast radius than a direct file-per-file layout. The implementation has to compensate for that aggregation risk.
This is where I would be skeptical of any benchmark-only claim. A PackFS number is not worth much until the same artifact survives kill-and-recover tests in ordered mode. The current engineering benchmarks are useful for direction, but the durability evaluation has to include crash injection.
Overlayfs Compatibility Details
Overlayfs upper compatibility is more about ugly edge cases than beautiful abstractions.
A few examples:
RENAME_WHITEOUT must leave a whiteout at the source while moving the old object to the destination. On Linux that whiteout is a character device with major/minor 0/0.
RENAME_EXCHANGE must atomically swap two dentries, including file-directory combinations that normal rename cannot replace.
Opaque directories are represented with overlay xattrs, usually trusted.overlay.opaque=y.
O_TMPFILE can create an inode without a name. If it later becomes linked into the namespace, recovery must either know how to create that inode or the link replay points at nothing.
readdir offsets must be stable enough that userspace can seek and continue. PackFS keeps per-directory offset state rather than assuming the dcache can be the authoritative directory store.
That is the credibility threshold for this kind of filesystem. Passing echo hello > f && cat f is not interesting. The upper has to survive real overlayfs copy-up, whiteout, xattr, tmpfile, rename, hardlink, and fsync behavior.
What The Benchmarks Currently Say
These are current engineering measurements from the PackFS development loop, not paper-ready evaluation numbers. I still want more repetitions, variance, DAX/writeback-cache baselines, crash-recovery rows, and cold-mount-at-scale rows before treating them as publication numbers. They are useful here because they separate mechanisms.
The comparison is:
overlayfs upper directly on virtiofs
vs
overlayfs upper on PackFS, with PackFS store on virtiofsRepresentative ordered-mode rows:
| Workload | Direct overlay on virtiofs | Overlay on PackFS | Directional result |
|---|---|---|---|
| 3k small files, no fsync | 2374 ms | 96 ms | 24.7x faster |
| 3k small files, fsync each file | 28909 ms | 24586 ms | near floor parity, slight win |
| 20k node_modules-shaped files, fsync every 10k | 22422 ms | 564 ms | 39.8x faster |
| 10k overlay copy-ups | 20280 ms | 371 ms | 54.7x faster |
| 3k stat-heavy lookups | 697 ms | 7 ms | in-guest namespace wins |
I care less about the exact ratio than the shape:
Small-file no-fsync workloads are crossing-bound. PackFS wins because it keeps namespace churn inside the guest and lowers the number of host-bound writes.
Sparse-fsync workloads are the product case. Agents, package managers, and build tools usually do not call fsync after every tiny file. They create a large tree and hit barriers occasionally. Group commit and packing help there.
Serial per-file fsync is close to an irreducible lower-fsync floor. PackFS can reduce metadata crossings, but it cannot make one durable lower fsync cheaper unless the lower backend itself gets cheaper or the data can ride inline in the journal.
Large sequential writes are not the win case. If direct virtiofs already emits large writes, PackFS has to avoid adding CPU copies, checksums, and per-page machinery. The right policy is spill or bypass for large files, not pretending the packer improves everything.
Why This Is A Kernel Filesystem
It is worth asking why PackFS is not just a userspace daemon.
Because the thing being optimized is not only lower storage layout. It is the Linux VFS path.
PackFS wants:
guest page cache ownership
dirty-page throttling through a real BDI
overlayfs upper compatibility
dcache participation
inode operations without FUSE re-entry
direct interaction with writeback
stable Linux credential override for lower opsIf PackFS lived behind another FUSE boundary inside the guest, the design would reintroduce the class of overhead it is trying to remove. The host boundary is the expensive one, but adding another guest boundary is still the wrong direction.
The kernel version also keeps the memory-pressure story honest. Dirty pages must be visible to the VM. A packer that buffers outside writeback accounting can look fast until the first real memory-pressure test. PackFS’s stager has to cooperate with reclaim instead of hiding from it.
Capacity And Failure Modes
Coalescing files into segments creates a temptation to lie about capacity. PackFS tries not to.
There are two different concepts:
logical dirty bytes
physical reserved bytes
lower bytes actually writtenThe foreground write path can admit data only if the system has a defensible capacity story for it. In volatile mode, that can be a bounded in-RAM and lower-reservation policy because the crash contract is discard/refuse. In ordered mode, acknowledged durability has to line up with actual lower persistence.
GC has a similar rule. Segment live-byte accounting is a performance structure, but if the implementation ever detects an underflow, duplicate segment identity, or unknown segment during accounting, GC must fail closed. It is better to leak lower space for the mount than to reap a segment based on counters the filesystem has declared untrusted.
That sounds obvious, but it is exactly the kind of bug that appears in log-structured filesystems. The compactor is where stale accounting tries to become data loss.
What I Would Change Next
PackFS is already useful as a systems experiment. It is not done.
The highest-impact performance work is range-shaped storage. The current extent map is page-indexed because that made overwrite, truncate, and replay simple. For large sequential files, a maple-tree range map or a wide-record format would reduce memory, checkpoint size, and iteration cost. The hard part is preserving page-granular overwrite and GC accounting without making recovery ambiguous.
The read path needs proper readahead. Sequential packed data is segment-contiguous by construction, but page-at-a-time reads leave performance on the table. A good implementation would resolve a readahead window, group extents by segment, issue merged lower reads, validate per-page checksums, and fill folios in one pass.
Large-file spill should be a first-class policy. If a file crosses a threshold, PackFS can put it in a dedicated lower object or a large identity-mapped extent and avoid the small-file packer. That keeps the product win without hurting tarballs, build artifacts, and model files.
The crash evaluation should be systematic. Ordered mode needs kill points around segment write, journal commit, checkpoint rename, superblock publish, GC relocation, inline-data replay, and dirty-store mount. Benchmarks without that matrix are performance anecdotes, not filesystem evidence.
The lower baseline matrix needs to be broader. Direct virtiofs in write-through mode is the worst case for boundary crossings. A fair report also needs virtiofs DAX, writeback-cache where applicable, tmpfs upper with copy-out, and the two lower backends measured separately.
Finally, test failpoints must compile out of production builds or use static branches. They are valuable in crash testing; they should not be a tax in the hot path.
The Real Claim
PackFS is not magic compression for filesystem work. It does not make fsync free. It does not beat direct virtiofs on every large sequential write. It is not a replacement for ext4.
Here is the claim I would stand behind:
For agent workspaces whose cost is dominated by small-file and namespace operations over a host boundary, an in-guest coalescing upper can turn many logical filesystem operations into a small number of packed lower writes, while still presenting the Linux semantics overlayfs expects.
That narrower claim is enough to matter.
It means the storage substrate for AI agents should not be copied blindly from container defaults. Agent workloads have a different shape: short-lived, heavily isolated, namespace-heavy, often disposable, sometimes checkpointed, and usually running on a paravirtual boundary. PackFS is the kernel-side version of taking that workload seriously.
The engineering challenge is that the old filesystem lessons still apply. Once you pack many logical files into one physical log, your correctness bugs get more interesting. You need real writeback integration, real overlay compatibility, real crash rules, and real benchmarks that include the ugly rows.
That is what makes PackFS worth building.