Skip to content

core: merge changesets by content, not patches - #13773

Merged
vito merged 4 commits into
dagger:mainfrom
vito:changeset-content-merge
Jul 30, 2026
Merged

vito merged 4 commits into
dagger:mainfrom
vito:changeset-content-merge

Conversation

@vito

@vito vito commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Problem

Changeset.withChangeset[s] built each merge branch by git applying the changeset's patch onto a union of every input's before directory. That silently assumes all inputs share a common base. When the befores diverge — e.g. generate staging a shared dependency's codegen into each dependent's workspace — the union base already contains one side's post-state, so insertion hunks re-apply at an offset (generated code is repetitive enough for git apply to match context past an existing copy, duplicating code) and modification hunks fail outright with error: patch failed. This is what forced the go SDK's rebase workaround (dagger/go-sdk@89edf83): manufacturing a common base at the callsite, in the wrong layer. A changeset is its file-level diff — withChangeset shouldn't require callers to curate bases.

Complements #13771, which made the staging-side accumulation merge-free; this octopus merge was the last patch-based consumer.

Fix

core: ignore ctime when merging changesets — snapshots share file contents via hardlinks, so a file's ctime, inode, and device can change under a live merge workspace without the content changing. Git sees stat-dirty entries and git merge's internal git stash create fails with a bewildering fatal: stash failed. The ephemeral merge repos now run with core.checkStat=minimal and core.trustctime=false.

fix(layercopy): unwrap hardlink fallback errors — os.Link wraps errnos in *os.LinkError, so the EXDEV/EMLINK comparisons never matched and the content-copy fallback was dead code. Nobody hit this while every copy targeted the snapshot filesystem itself, but copying into a mounted view (a different superblock) trips it immediately.

fix(core): merge changesets by content — each merge branch is now built from the changeset's file-level content instead of a patch: materialize Before.diff(After) (the same content Directory.withChanges and Changeset.export already apply), delete the removed paths, overlay the diff onto the checked-out base, recreate empty added directories, and commit. Content the base already contains becomes a no-op, so inputs no longer need a common base, while genuinely common-base inputs produce the same branches the patches did. The merge step itself is unchanged: git re-derives line-level hunks against the merge base, so same-file edits in different regions still compose textually and overlapping edits still conflict per the onConflict strategy. asPatch stays (API-visible); the patch-apply plumbing is deleted.

Two constraints baked into the implementation: the copier writes through the mounted view rather than the snapshot upperdir (git must see the files it stages; mutating an overlay's layers behind a live mount leaves the view incoherent), and source hardlinks are disabled (they always cross superblocks into the view).

fix(core): touch merge-applied paths so git sees them — snapshot contents carry normalized timestamps and the copier preserves them, so a same-size edit leaves a file's mtime and size identical to its index entry. With core.checkStat=minimal, git add skipped re-hashing such files and silently dropped the edit from the branch commit; the worktree still carried the content, so the last-applied changeset's version leaked into the merge result and modify/modify conflicts "merged" cleanly, clobbering one side. Every applied path's mtime is bumped after the overlay. Adds TestSameFileRegionMerge, pinning that same-file different-region edits compose in both two-way and octopus merges and that overlapping edits still conflict — the case that caught this.

Compatibility

No API changes. For changesets sharing a common base, branch content is identical to the patch-applied result, so existing merges behave the same. Empty added directories now survive merges (patches couldn't represent them). Once this lands, the go SDK's rebase workaround can be reverted: generate output against the pre-workaround go-sdk is byte-identical to output with it.

Verification (dagger repo, dev engine)

  • Full dagger generate dagger-go-sdk against the pre-workaround go-sdk (dagger/go-sdk@0c04581): applies cleanly where it previously duplicated AsVolume bindings or failed hunks, output is byte-identical to the known-good regen, every toolchain compiles, and rerunning is a no-op.
  • TestChangeset integration suite passes, including the new TestSameFileRegionMerge and all TestChangesetMerge / TestWithChangesets conflict flows.
  • go test ./core/schema ./core/workspace ./util/layercopy pass; polyfill's e2e module-source checks (including the generate-merge-check disjointness pin) pass 4/4.

🤖 Generated with Claude Code

vito added 4 commits July 29, 2026 14:43
Snapshots share file contents via hardlinks, so a file's ctime, inode and
device can change out from under a merge workspace when a concurrent
snapshot links the same inode, even though the content is untouched. git
then sees hundreds of stat-dirty entries, and `git merge` fails during
its internal `git stash create`: that call reports changes from a
stat-only check, finds none after refreshing the index, and exits
non-zero with no output, leaving merge to die with the bewildering
"fatal: stash failed".

Configure the ephemeral merge repositories with core.checkStat=minimal
and core.trustctime=false so git compares only mtime and size, which is
all we can trust across snapshot mounts.

Signed-off-by: Alex Suraci <[email protected]>
os.Link reports failures as *os.LinkError wrapping the errno, so comparing
the error directly against EXDEV/EMLINK never matched and the content-copy
fallback was unreachable; cross-device link attempts failed the whole copy.
Nobody hit this while every copy targeted the snapshot filesystem itself,
but copying into a mounted view (a different superblock) trips it
immediately.

Signed-off-by: Alex Suraci <[email protected]>
Changeset.withChangeset[s] built each merge branch by git-applying the
changeset's patch onto a union of every input's before directory. When the
befores diverge -- e.g. generate staging a shared dependency's codegen into
each dependent's before -- the union already contains one side's post-state,
so insertion hunks double-apply at an offset and modification hunks fail
outright, forcing callers to manufacture a common base.

Build each branch from the changeset's file-level content instead: overlay
the materialized Before.diff(After) directory onto the base (the same
content Directory.withChanges applies), delete the removed paths, recreate
empty added directories, and commit. Content the base already contains
becomes a no-op, so inputs no longer need a common base, while genuinely
common-base inputs produce the same branches the patches did. Same-file
edits still merge textually through git's ordinary 3-way merge, and the
conflict flows are untouched.

The overlay writes through the mounted view rather than the snapshot
upperdir since git has to see the files it stages, and skips source
hardlinks since they always cross devices there.

Signed-off-by: Alex Suraci <[email protected]>
Snapshot contents carry normalized timestamps and layercopy preserves them,
so overlaying a same-size edit leaves a file's mtime and size identical to
its index entry. With core.checkStat=minimal the branch's git add skipped
re-hashing such files and silently dropped the edit from the commit; the
worktree still carried the content, so the last-applied changeset's version
leaked into the merge result and modify/modify conflicts merged cleanly,
clobbering one side. The patch flow never hit this because git apply wrote
files with fresh mtimes. Bump every applied path's mtime after the overlay.

Also add TestSameFileRegionMerge, which pins that changesets editing
different regions of the same file all survive two-way and octopus merges,
and that overlapping edits still conflict -- the case that caught this.

Signed-off-by: Alex Suraci <[email protected]>
@sipsma

sipsma commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

fix(layercopy): unwrap hardlink fallback errors — os.Link wraps errnos in *os.LinkError, so the EXDEV/EMLINK comparisons never matched and the content-copy fallback was dead code. Nobody hit this while every copy targeted the snapshot filesystem itself, but copying into a mounted view (a different superblock) trips it immediately.

The fix itself SGTM, but curious what situation you were hitting it in? The goal of layercopy is to detect bind mounts, overlay mounts, etc. and then find the underlying "real" path so that hardlinks can be made. This is supposed to be always possible in theory since the engine's state is just /var/lib/dagger and thus a single underlying filesystem. But I could easily be missing a legit case where we actually can't do that and need to fallback to the slower copy.

@vito

vito commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

@sipsma The way this PR uses layercopy is a little different: it copies between a snapshot upper dir and a live overlay mount.

Normally we're copying into the overlays upper dir which resides in /var/lib/dagger, but copying directly into the upper dir while its overlay mount is live caused cryptic errors from git when trying to read those files:

git add -A: fatal: unable to stat 'newfile.txt': No such file or directory

The fix was to copy into the overlay mount instead, which will write through to the upper dir and not leave git confused in the end.

But that led to errors trying to hard-link between the overlay mount and /var/lib/dagger:

apply ours changes: copy changed paths: link /var/lib/dagger/worker/snapshots/N/fs/filea.txt
  /tmp/dagger-mountNNN/filea.txt: invalid cross-device link

After all that it looks like 🤖 just disabled hard links altogether. Not ideal, but we're only copying the delta each time and not entire directory trees so it's probably not too bad.

LLM explanations
  ▎ tl;dr we hit a cryptic error from git (add -A: unable to stat) triggered by layercopy writing to the overlay upperdir behind the live mount git
  ▎ was running in; fixing that by writing through the mounted view then exposed a second error — hardlinking from snapshots into the view crosses
  ▎ filesystems, and layercopy's EXDEV fallback turned out to be dead code (it compared errnos that os.Link always wraps). We ended up disabling
  ▎ source-hardlinks for this path anyway (they'd always cross devices, so every attempt is a wasted syscall), which makes the fallback fix redundant
  ▎ here — but we kept it because it's the function's advertised behavior finally working, and without it the next caller that copies into a mounted
  ▎ view hits a hard failure instead of the intended fallback-to-copy.

❯ Huh. Do we have to solve it that way? It's a shame we can't do hard-links. Do we _have_ to copy into upper dir while the mount is active?

● Short version: yes, it's forced — not by layercopy, but by the shape of the merge loop. Git and the copier take turns mutating the same tree inside
  one live mount: git checks out a branch, the copier overlays the changeset's diff onto whatever git just materialized, git stages and commits it,
  then checks out the next branch, repeat, then merge. Each copy's destination state depends on git's previous move and vice versa, so there's no
  window where you can batch the writes into the upperdir "offline" — the mount has to be live and coherent the whole time, and overlayfs forbids
  touching layers behind a live mount.

  The escape hatches exist but none are attractive:

  - Unmount → write upperdir with real paths (hardlinks work) → remount, per branch. Legal, but that's ~2N mount cycles per merge, MountRef has no
  such dance, and layercopy's overlay mode itself stats through the live view to make replace/whiteout decisions — so it also assumes an active
  mount. Real plumbing for marginal gain.
  - Build each branch tree as a snapshot (WithChanges-style, hardlinked, upperdir writes fine there) and commit it via git --work-tree=<branch-mount>
  without copying into the workspace at all. Actually plausible! But the content then round-trips through git's object store (zlib in, zlib out at
  checkout/merge) — likely slower than the direct copy it saves.

  And the thing that makes me not mourn the hardlinks much:

  - We only copy diff-sized data — each changeset's added+modified files, not the base tree. The base is already shared via the snapshot parent
  (overlay lowerdir), untouched.
  - The old patch-based flow had zero hardlinks too — git apply writes file content into the worktree. So this isn't a regression; it's the same data
  movement with a different pen.
  - The "slow copy" isn't that slow — Go's io.Copy between files uses copy_file_range, so it's an in-kernel copy (reflink where the filesystem
  supports it).
  - Bonus safety: not aliasing immutable snapshot inodes into a mutable git worktree sidesteps the shared-inode weirdness we already pay for
  elsewhere — the core.checkStat=minimal git config in this very file exists because snapshot hardlink-sharing makes ctimes/inodes shift under git.
  Fewer shared inodes in a tree git actively rewrites is a feature.

  So: we could get hardlinks back with either restructuring, but we'd be spending real complexity to avoid copying a few MB of diffs per merge that
  every previous version of this code also copied. If merge workspaces ever start ingesting huge changesets, the git --work-tree variant is the one
  I'd revisit first.

@sipsma

sipsma commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

@vito I see, yeah it's not as trivial in that case if you need to run git before and after. And also not a regression for this case so definitely not a blocker. I think claude is somewhat underestimating the cost of repeated copies in the case of big shared engines that are already disk bandwidth starved, but I otherwise agree with it in this case 🦾

@vito
vito merged commit 4574a49 into dagger:main Jul 30, 2026
87 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants