Skip to content

worktree: copy-on-write creation and shared-branch worktrees#2317

Open
nevion wants to merge 2 commits into
git:masterfrom
nevion:worktree-reflink-cow
Open

worktree: copy-on-write creation and shared-branch worktrees#2317
nevion wants to merge 2 commits into
git:masterfrom
nevion:worktree-reflink-cow

Conversation

@nevion

@nevion nevion commented May 29, 2026

Copy link
Copy Markdown

When many worktrees share one repository -- e .g. a fleet of agents each
needing an isolated checkout -- "git worktree add" is costly at scale.
Objects are shared via the common dir, but the working tree is not: each
add rewrites every tracked file, so N worktrees cost N full checkouts of
disk and I/O. And a branch can only be checked out in one worktree.

Patch 1 adds "git worktree add --reflink": on a copy-on-write filesystem
it populates the new worktree by reflinking the current worktree's files
and index, then "git reset --hard" rewrites only the paths that differ
from . A reflink_file() helper in copy.c uses FICLONE (Linux)
and clonefile() (macOS); elsewhere (other filesystems, Windows) it is
probed up front and falls back to a normal checkout. Defaulting is via
the worktree.reflink config (true/false/auto); --no-reflink overrides.

Patch 2 lets a branch be checked out in several worktrees, for parallel
work on one checkout. A branch mid-rebase or mid-bisect elsewhere is
still refused.

Benchmark (Linux-kernel fork, 93k files, ~33 GB tree incl. build output,
btrfs): a normal add allocates ~0.9 GB of real disk per worktree (~5.3 GB
for four, linear); --reflink allocates ~0 at any count and also carries
the untracked build tree. ("Real disk" = btrfs exclusive bytes.)

worktree-reflink-bench

Note: patch 2 changes a default (same-branch checkout now allowed); two
t2400 assertions were updated accordingly.

cc: "brian m. carlson" sandals@crustytoothpaste.net

@gitgitgadget-git

Copy link
Copy Markdown

Welcome to GitGitGadget

Hi @nevion, and welcome to GitGitGadget, the GitHub App to send patch series to the Git mailing list from GitHub Pull Requests.

Please make sure that either:

  • Your Pull Request has a good description, if it consists of multiple commits, as it will be used as cover letter.
  • Your Pull Request description is empty, if it consists of a single commit, as the commit message should be descriptive enough by itself.

You can CC potential reviewers by adding a footer to the PR description with the following syntax:

CC: Revi Ewer <revi.ewer@example.com>, Ill Takalook <ill.takalook@example.net>

NOTE: DO NOT copy/paste your CC list from a previous GGG PR's description,
because it will result in a malformed CC list on the mailing list. See
example.

Also, it is a good idea to review the commit messages one last time, as the Git project expects them in a quite specific form:

  • the lines should not exceed 76 columns,
  • the first line should be like a header and typically start with a prefix like "tests:" or "revisions:" to state which subsystem the change is about, and
  • the commit messages' body should be describing the "why?" of the change.
  • Finally, the commit messages should end in a Signed-off-by: line matching the commits' author.

It is in general a good idea to await the automated test ("Checks") in this Pull Request before contributing the patches, e.g. to avoid trivial issues such as unportable code.

Contributing the patches

Before you can contribute the patches, your GitHub username needs to be added to the list of permitted users. Any already-permitted user can do that, by adding a comment to your PR of the form /allow. A good way to find other contributors is to locate recent pull requests where someone has been /allowed:

Both the person who commented /allow and the PR author are able to /allow you.

An alternative is the channel #git-devel on the Libera Chat IRC network:

<newcontributor> I've just created my first PR, could someone please /allow me? https://github.com/gitgitgadget/git/pull/12345
<veteran> newcontributor: it is done
<newcontributor> thanks!

Once on the list of permitted usernames, you can contribute the patches to the Git mailing list by adding a PR comment /submit.

If you want to see what email(s) would be sent for a /submit request, add a PR comment /preview to have the email(s) sent to you. You must have a public GitHub email address for this. Note that any reviewers CC'd via the list in the PR description will not actually be sent emails.

After you submit, GitGitGadget will respond with another comment that contains the link to the cover letter mail in the Git mailing list archive. Please make sure to monitor the discussion in that thread and to address comments and suggestions (while the comments and suggestions will be mirrored into the PR by GitGitGadget, you will still want to reply via mail).

If you do not want to subscribe to the Git mailing list just to be able to respond to a mail, you can download the mbox from the Git mailing list archive (click the (raw) link), then import it into your mail program. If you use GMail, you can do this via:

curl -g --user "<EMailAddress>:<Password>" \
    --url "imaps://imap.gmail.com/INBOX" -T /path/to/raw.txt

To iterate on your change, i.e. send a revised patch or patch series, you will first want to (force-)push to the same branch. You probably also want to modify your Pull Request description (or title). It is a good idea to summarize the revision by adding something like this to the cover letter (read: by editing the first comment on the PR, i.e. the PR description):

Changes since v1:
- Fixed a typo in the commit message (found by ...)
- Added a code comment to ... as suggested by ...
...

To send a new iteration, just add another PR comment with the contents: /submit.

Need help?

New contributors who want advice are encouraged to join git-mentoring@googlegroups.com, where volunteers who regularly contribute to Git are willing to answer newbie questions, give advice, or otherwise provide mentoring to interested contributors. You must join in order to post or view messages, but anyone can join.

You may also be able to find help in real time in the developer IRC channel, #git-devel on Libera Chat. Remember that IRC does not support offline messaging, so if you send someone a private message and log out, they cannot respond to you. The scrollback of #git-devel is archived, though.

@nevion

nevion commented May 29, 2026

Copy link
Copy Markdown
Author

this feature is used/reimplemented within grok build https://x.com/theskory/status/2059729539287167068 (I have nothing to do with that) but the best place for this to be done is inside git so all tools can benefit.

@nevion

nevion commented May 29, 2026

Copy link
Copy Markdown
Author

Benchmark — Linux-kernel fork (93k tracked files, ~33 GB working tree incl. build artifacts, btrfs):

worktree --reflink benchmark

Left: real disk written vs. number of worktrees (normal grows ~1.3 GB each; --reflink stays at 0). Right: one worktree — ~0 new disk, and it carries the full build tree (464k files) vs. source-only (93k). "Real disk" = btrfs exclusive bytes; shared CoW extents count as 0.

nevion added 2 commits May 29, 2026 12:00
Creating many worktrees from the same base -- for example to run a
fleet of automated agents in parallel -- is expensive today: every
"git worktree add" materializes the entire working tree by writing
each tracked file out from the object store. The objects are shared
via the common directory, but the working tree is not: N worktrees
mean N full checkouts on disk and N times the file I/O.

Add a "--reflink" option that, on copy-on-write filesystems, populates
the new worktree by reflinking the current worktree's files and index
instead. The subsequent "git reset --hard" then only rewrites the
paths that actually differ between the current worktree and
<commit-ish>; everything else (including untracked files such as build
outputs) keeps sharing storage with the source until modified. Because
the cloned index still carries the source files' stat data, it is
refreshed against the reflinked files first so that reset recognizes
the unchanged paths as up to date and leaves them sharing extents
rather than rewriting them.

The clones are made by a new reflink_file() helper in copy.c, which
uses the FICLONE ioctl on Linux and clonefile() on macOS and reports
an error otherwise so callers fall back to a normal copy. Support is
probed up front; when unavailable -- including on filesystems without
copy-on-write and on platforms such as Windows that lack a reflink
primitive -- "--reflink" transparently falls back to an ordinary
checkout, so the worst case is no slower than today rather than a
byte-for-byte copy of the source tree. The directory walk skips the
new worktree itself when it lives inside the source one, and preserves
symlinks and modes.

The behavior can be made the default with the worktree.reflink
configuration ("true", "false" or "auto", the last suppressing the
unsupported-filesystem warning), and turned off per-invocation with
--no-reflink. A configured default degrades quietly in modes that
cannot reflink (--orphan, --no-checkout) instead of erroring, so
enabling it never breaks those commands. The checkout step continues
to honor checkout.workers, so parallel checkout composes with
--reflink for the paths that do need rewriting.

Signed-off-by: Jason Newton <nevion@gmail.com>
When spinning up several worktrees on the same checkout for parallel
work (for example a fleet of agents working from one branch), git's
refusal to check out a branch that is already checked out elsewhere is
just in the way. The restriction exists to stop two worktrees from
moving the same branch underneath each other, but plain parallel
checkouts do not need that protection.

Drop the restriction: "git worktree add <branch>" now checks out a
branch even if it is in use by another worktree. The genuinely
dangerous case is kept -- a branch that another worktree is in the
middle of rebasing or bisecting is still refused, because a second
checkout could corrupt that operation. die_if_branch_busy() performs
that narrower check in place of the old die_if_checked_out(). The
separate guard against force-updating (e.g. with -B) a branch in use
elsewhere is left untouched.

Signed-off-by: Jason Newton <nevion@gmail.com>
@nevion

nevion commented Jun 1, 2026

Copy link
Copy Markdown
Author

The non-Linux CI failures here are unrelated to this change (which only touches worktree, copy, and t2400):

  • win test (4)t3070.966 iwildmatch (via ls-files): this is in wildmatch/pathspec matching, untouched by this series. It is already failing on git/git's own master CI, independent of this PR — e.g. run #11454 (1666c126) and run #11420 (c69baaf5, "The 9th batch" — the very commit this branch is based on) both show win test (4) = failure, whereas it still passed at run #11401 (56a4f3c3). So it's a recent base regression on the Windows shard, not introduced here; t3070-wildmatch.sh and wildmatch.c are byte-identical to v2.54.0, so rebasing onto a release would not avoid it. It'll be resolved on master independently of this topic.

  • osx-gcc / osx-meson (macos-14): intermittent. These passed on the first CI run for this exact commit and failed only on a re-run (failing step: ci/run-build-and-tests.sh, no specific test reported). This is macOS-runner flakiness; a re-run clears it.

  • linux-TEST-vars (ubuntu:20.04) (now green): the earlier failure was a runner infrastructure error — System.IO.IOException: No space left on device — not a test failure. The linux32/osx "cancelled" entries were fail-fast cancellations from that run. A re-run brought all linux-* jobs green.

Every job that actually exercises this change (all linux-*, almalinux, debian, fedora, and win test 0-3/5-9) passes.

@dscho

dscho commented Jun 3, 2026

Copy link
Copy Markdown
Member

/allow

@dscho

dscho commented Jun 3, 2026

Copy link
Copy Markdown
Member

Yes, sadly Git's CI is not always in a pristine shape :-(

@gitgitgadget-git

Copy link
Copy Markdown

User nevion is now allowed to use GitGitGadget.

@nevion

nevion commented Jun 5, 2026

Copy link
Copy Markdown
Author

@dscho do I do anything else?

@dscho

dscho commented Jun 5, 2026

Copy link
Copy Markdown
Member

Why, yes, you /submit (or maybe first /preview).

@nevion

nevion commented Jun 5, 2026

Copy link
Copy Markdown
Author

/preview

@gitgitgadget-git

Copy link
Copy Markdown

Preview email sent as pull.2317.git.git.1780684356.gitgitgadget@gmail.com

@nevion

nevion commented Jun 5, 2026

Copy link
Copy Markdown
Author

/submit

@gitgitgadget-git

Copy link
Copy Markdown

Submitted as pull.2317.git.git.1780685368.gitgitgadget@gmail.com

To fetch this version into FETCH_HEAD:

git fetch https://github.com/gitgitgadget/git/ pr-git-2317/nevion/worktree-reflink-cow-v1

To fetch this version to local tag pr-git-2317/nevion/worktree-reflink-cow-v1:

git fetch --no-tags https://github.com/gitgitgadget/git/ tag pr-git-2317/nevion/worktree-reflink-cow-v1

@gitgitgadget-git

Copy link
Copy Markdown

"brian m. carlson" wrote on the Git mailing list (how to reply to this email):

On 2026-06-05 at 18:49:26, Jason Newton via GitGitGadget wrote:
> When many worktrees share one repository -- e .g. a fleet of agents each
> needing an isolated checkout -- "git worktree add" is costly at scale.
> Objects are shared via the common dir, but the working tree is not: each add
> rewrites every tracked file, so N worktrees cost N full checkouts of disk
> and I/O. And a branch can only be checked out in one worktree.
> 
> Patch 1 adds "git worktree add --reflink": on a copy-on-write filesystem it
> populates the new worktree by reflinking the current worktree's files and
> index, then "git reset --hard" rewrites only the paths that differ from . A
> reflink_file() helper in copy.c uses FICLONE (Linux) and clonefile()
> (macOS); elsewhere (other filesystems, Windows) it is probed up front and
> falls back to a normal checkout. Defaulting is via the worktree.reflink
> config (true/false/auto); --no-reflink overrides.

Windows apparently has CoW functionality if you use ReFS.  I believe Git
LFS has code to do this and you may be interested in checking it out.

Also, how does this work if worktree A is dirty (but `git update-index`
and `git status` have not been run) when the reflink occurs?  Does B
have stale files from the working tree?  If not, how do we plan on
detecting that?  (While I'm curious, this should also be explained in
your commit message because we want to know that you have thought about
this problem and have a good answer for it.)

I was curious as to how this would work with containers, which typically
use overlayfs, but some searching reveals that overlayfs does indeed
support reflinks.  Thanks for the opportunity to learn something new
today.

> Patch 2 lets a branch be checked out in several worktrees, for parallel work
> on one checkout. A branch mid-rebase or mid-bisect elsewhere is still
> refused.

So how does this work if you have two worktrees for the same branch, A
and B, and A commits, and then B does?  What we don't want to happen is
that because B's worktree is not up to date, it effectively reverts the
changes that A made when adding objects to the index to commit.  (Again,
this is a good thing to explain in your commit message, since reviewers
will be curious.)

My personal approach, if I needed many worktrees of the same commit,
would be to create many refs pointing to the same object ID and check
those out.  `git update-ref` can perform a single ref transaction with
many refs, which is especially efficient with reftable.  That would
avoid the need for multiple checkout support, although I could still see
the utility of reflinking if it can be done safely.  If that's a
solution that you think would be valuable, you could propose it as a FAQ
entry or an edit to the manual page, since I'm sure there are other
people with your use case.
-- 
brian m. carlson (they/them)
Toronto, Ontario, CA

@gitgitgadget-git

Copy link
Copy Markdown

User "brian m. carlson" <sandals@crustytoothpaste.net> has been added to the cc: list.

@gitgitgadget-git

Copy link
Copy Markdown

Junio C Hamano wrote on the Git mailing list (how to reply to this email):

"Jason Newton via GitGitGadget" <gitgitgadget@gmail.com> writes:

> When many worktrees share one repository -- e .g. a fleet of agents each
> needing an isolated checkout -- "git worktree add" is costly at scale.
> Objects are shared via the common dir, but the working tree is not: each add
> rewrites every tracked file, so N worktrees cost N full checkouts of disk
> and I/O.

Are the "CoW" semantics offered by these underlying mechanisms,
which may differ per operating system and possibly filesystem type,
all meant as mere storage-space optimization, or do some of them
trade potential space saving with some limitation of the features,
i.e., what you can do in the CoW copy and original, or increased
runtime cost, either at the clone time or the time of first
modification?

What I am trying to get at is why should this be even an opt-in
feature.  If "cp treeA treeB" at the shell level would make all the
files in treeA under identical names and contents in treeB, and let
you edit/update/delete copies in either tree without affecting the
other tree, then in practice you would not even be able to _tell_ if
CoW is in use, no?

It may tilt the scale if there is a downside associated with the use
of CoW, like at the first modification of one copy, the system may
need to do real copies of other copies, but even such a cost should
not be outrageously worse than the cost of copying everything once
at the worktree creation time.

So I would understand "whenever we say git_copy_file(A, B), we
always use CoW facility under the hood if available, regardless of
the purpose of the operation to copy one file to another location---
it may include, but does not have to be limited to, populating
working file trees in a new worktree", and I think it is a welcome
change.

But I do not quite get "... only if the user gives --reflink
option".  Why is it even necessary to offer a choice?  Especially
since you seem to have auto-probe, we should be able to implement a
low-level operation to materialize contents identified by a_hash at
a_path in the working tree in two different ways, switching on the
availablity of CoW, e.g.,

	if (CoW available && we can find existing path with a_hash) {
	        copy-cow the found path to a_path;
	} else {
		write object identified by a_hash to a_path;
	}

>  And a branch can only be checked out in one worktree.

This is a safety feature that has nothing to do with shared files
across worktrees, no?  Your two worktrees may think they have a
checkout of the same branch (thus the same commit), one worktree
makes changes and commits, the other worktree suddenly starts seeing
a totally different output from its "git diff HEAD" that mixes what
it did relative to where it started (which is what we want) plus the
reversion of what was done in the other worktree (which is definitely
not what we want).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants