Skip to main content

Module fs_clone

Module fs_clone 

Source
Expand description

Filesystem-level copy-on-write helpers.

Heddle’s worktree materializer needs the storage win of pointing N worktrees at the same blob bytes (so checking out the same state to many sibling worktrees costs ~1× disk, not N×) without the mutation hazard that hardlinks bring. With hardlinks, an in-place write — chmod +w file && echo new > file, O_TRUNC, etc. — mutates the shared inode, corrupting every other worktree that points at the same blob.

Filesystem reflinks (a.k.a. CoW clones) solve this: the destination starts out sharing physical blocks with the source, but the first write to either side automatically forks the underlying allocation. The OS guarantees isolation even if an agent strips the read-only bit and overwrites the file in place.

Platform support:

  • macOS / APFS: clonefile(2) from <sys/clonefile.h>. True CoW.
  • Linux / btrfs / XFS-with-reflinks / ZFS: ioctl(dest_fd, FICLONE, src_fd).
  • Anywhere else (or when reflink isn’t supported by the underlying filesystem): caller falls back to a real copy.

The functions here return Ok(true) on a successful clone, Ok(false) when the kernel reported the operation isn’t supported on this filesystem (so the caller should fall back to a real copy and remember to skip future reflink attempts in this batch), and an Err for genuine I/O errors that the caller should surface.

Functions§

clonefile_or_copy
Reflink if possible, otherwise fall back to a real copy. Returns the same Ok(true)/Ok(false) discriminator as try_reflinktrue when the OS gave us a CoW clone, false when we paid the full copy cost. Either way, on Ok the destination exists and has the source’s bytes.
filesystem_supports_reflink
Test whether the filesystem at parent_dir supports reflinks by trying one against a temp source/dest pair. Returns true on success. Useful for tests that want to soft-skip on filesystems without CoW support, and for any caller that wants a runtime capability check before asserting on reflink-specific properties.
try_reflink
Try a filesystem-level reflink (copy-on-write clone) from source to dest. On success the destination has its own inode and shares physical blocks with the source until either side is modified.