Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8525 fix(daemon): recover checkouts orphaned by a cancelled worktree add (#9838)

Flavien Darche06601fb2db73
diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.go
index f727c2aa22..c391abe152 100644
--- a/server/internal/daemon/repocache/cache.go
+++ b/server/internal/daemon/repocache/cache.go
@@ -19,6 +19,7 @@ import (
"time"
"github.com/multica-ai/multica/server/internal/daemon/processtree"
+ "github.com/multica-ai/multica/server/internal/util"
"github.com/multica-ai/multica/server/pkg/redact"
)
@@ -896,6 +897,19 @@ func (c *Cache) CreateWorktreeContext(ctx context.Context, params WorktreeParams
dirName := repoNameFromURL(params.RepoURL)
worktreePath := filepath.Join(params.WorkDir, dirName)
+ if reason := orphanedWorktreeReason(worktreePath); reason != "" {
+ movedTo, err := moveAside(worktreePath)
+ if err != nil {
+ return nil, fmt.Errorf("move orphaned worktree aside: %w", err)
+ }
+ c.logger.Warn("repo checkout: moved orphaned worktree aside",
+ "url", params.RepoURL,
+ "path", worktreePath,
+ "reason", reason,
+ "moved_to", movedTo,
+ )
+ }
+
// Once a workdir has moved to isolated metadata, keep using that safer
// shape even if a later task comes from an older CLI or a different runtime
// that omits the mode hint. This also makes provider transitions on a reused
@@ -1503,11 +1517,117 @@ func createWorktreeContext(ctx context.Context, gitRoot, worktreePath, branchNam
err = runWorktreeAddContext(ctx, gitRoot, worktreePath, branchName, baseRef)
}
if err != nil {
+ // A cancelled git is killed before it can clean up, and the leftover
+ // tree would otherwise be reused by every later checkout of this
+ // workdir. Any other failure leaves the path alone: the pre-check only
+ // holds under this repo's lock, and a repo from another cache with the
+ // same basename may have created the path since (see
+ // createIsolatedCheckoutContext).
+ if ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
+ removePartialWorktree(gitRoot, worktreePath)
+ }
return "", err
}
return branchName, nil
}
+// removePartialWorktree removes a checkout a cancelled `git worktree add` left
+// behind, with its registration in gitRoot. A tree whose .git file points into
+// another bare cache belongs to someone else and is kept.
+func removePartialWorktree(gitRoot, worktreePath string) {
+ if adminDir, ok := worktreeAdminDir(worktreePath); !ok || samePath(filepath.Dir(adminDir), filepath.Join(gitRoot, "worktrees")) {
+ _ = os.RemoveAll(worktreePath)
+ }
+ adminDirs, _ := filepath.Glob(filepath.Join(gitRoot, "worktrees", "*"))
+ for _, adminDir := range adminDirs {
+ if owner, ok := worktreeRegistrationOwner(adminDir); ok && samePath(owner, worktreePath) {
+ _ = os.RemoveAll(adminDir)
+ }
+ }
+}
+
+// orphanedWorktreeReason reports why a linked worktree's .git file no longer
+// leads back to it, or "" when it does (or the path is not a linked worktree).
+// A checkout killed mid-add can lose its registration in the bare cache, and
+// git then gives the registration's name, taken from the directory basename,
+// to the next checkout with the same basename. Git commands in the orphan
+// then read, and can rewrite, that other checkout's index and HEAD.
+func orphanedWorktreeReason(worktreePath string) string {
+ adminDir, ok := worktreeAdminDir(worktreePath)
+ if !ok {
+ return ""
+ }
+ owner, ok := worktreeRegistrationOwner(adminDir)
+ if !ok {
+ return "registration " + adminDir + " is missing"
+ }
+ if !samePath(owner, worktreePath) {
+ return "registration " + adminDir + " belongs to " + owner
+ }
+ return ""
+}
+
+// worktreeAdminDir returns the registration a linked worktree's .git file
+// points at.
+func worktreeAdminDir(worktreePath string) (string, bool) {
+ data, err := os.ReadFile(filepath.Join(worktreePath, ".git"))
+ if err != nil {
+ return "", false
+ }
+ gitdir, ok := strings.CutPrefix(strings.TrimSpace(string(data)), "gitdir:")
+ if !ok {
+ return "", false
+ }
+ return resolveGitPath(worktreePath, strings.TrimSpace(gitdir)), true
+}
+
+// worktreeRegistrationOwner returns the worktree directory a registration in
+// <bare>/worktrees/ points back to.
+func worktreeRegistrationOwner(adminDir string) (string, bool) {
+ data, err := os.ReadFile(filepath.Join(adminDir, "gitdir"))
+ if err != nil {
+ return "", false
+ }
+ return filepath.Dir(resolveGitPath(adminDir, strings.TrimSpace(string(data)))), true
+}
+
+// resolveGitPath resolves a path git recorded, which is relative to base when
+// worktree.useRelativePaths is set.
+func resolveGitPath(base, path string) string {
+ if filepath.IsAbs(path) {
+ return filepath.Clean(path)
+ }
+ return filepath.Join(base, path)
+}
+
+// samePath compares paths after resolving symlinks (git records /private/var
+// for macOS's /var) and Windows junctions, including paths that no longer
+// exist.
+func samePath(a, b string) bool {
+ canonical := func(path string) string {
+ if resolved, err := util.ResolveSymlinksBestEffort(path); err == nil {
+ return resolved
+ }
+ return filepath.Clean(path)
+ }
+ return canonical(a) == canonical(b)
+}
+
+// moveAside renames path to a sibling instead of deleting it: an orphaned tree
+// can still hold files an agent wrote. Its .git file still points at a
+// registration another checkout may now own, so it is renamed too, and git
+// run in the moved tree cannot touch that checkout.
+func moveAside(path string) (string, error) {
+ dest := fmt.Sprintf("%s.orphaned-%d", path, time.Now().UnixNano())
+ if err := os.Rename(path, dest); err != nil {
+ return "", err
+ }
+ if err := os.Rename(filepath.Join(dest, ".git"), filepath.Join(dest, ".git.orphaned")); err != nil {
+ return "", fmt.Errorf("moved to %s but could not disable its .git file: %w", dest, err)
+ }
+ return dest, nil
+}
+
func runWorktreeAdd(gitRoot, worktreePath, branchName, baseRef string) error {
return runWorktreeAddContext(context.Background(), gitRoot, worktreePath, branchName, baseRef)
}
diff --git a/server/internal/daemon/repocache/cache_test.go b/server/internal/daemon/repocache/cache_test.go
index 254709097f..1e105f1925 100644
--- a/server/internal/daemon/repocache/cache_test.go
+++ b/server/internal/daemon/repocache/cache_test.go
@@ -1783,6 +1783,160 @@ func TestCreateWorktreePathCollisionDoesNotLeakBranch(t *testing.T) {
}
}
+func worktreeRegistration(t *testing.T, worktreePath string) string {
+ t.Helper()
+ data, err := os.ReadFile(filepath.Join(worktreePath, ".git"))
+ if err != nil {
+ t.Fatalf("read .git file: %v", err)
+ }
+ return strings.TrimSpace(strings.TrimPrefix(string(data), "gitdir:"))
+}
+
+// A checkout whose registration git dropped, and later gave to another
+// checkout with the same directory name, makes `git status` read the other
+// checkout's index. CreateWorktree must replace it instead of failing on every
+// retry, and must leave the other checkout working.
+func TestCreateWorktreeReplacesCheckoutWhoseRegistrationWasReused(t *testing.T) {
+ t.Parallel()
+ sourceRepo := createTestRepo(t)
+ cache := New(t.TempDir(), testLogger())
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {
+ t.Fatalf("sync failed: %v", err)
+ }
+ checkout := func(workDir, taskID string) (*WorktreeResult, error) {
+ return cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: workDir,
+ AgentName: "agent",
+ TaskID: taskID,
+ })
+ }
+
+ orphanWorkDir := t.TempDir()
+ orphan, err := checkout(orphanWorkDir, "a1111111-0000-0000-0000-00000000000a")
+ if err != nil {
+ t.Fatalf("first checkout failed: %v", err)
+ }
+ registration := worktreeRegistration(t, orphan.Path)
+ if err := os.RemoveAll(registration); err != nil {
+ t.Fatal(err)
+ }
+ other, err := checkout(t.TempDir(), "b2222222-0000-0000-0000-00000000000b")
+ if err != nil {
+ t.Fatalf("other checkout failed: %v", err)
+ }
+ if got := worktreeRegistration(t, other.Path); got != registration {
+ t.Fatalf("git did not reuse the registration: got %s, want %s", got, registration)
+ }
+
+ result, err := checkout(orphanWorkDir, "c3333333-0000-0000-0000-00000000000c")
+ if err != nil {
+ t.Fatalf("checkout over the orphaned tree failed: %v", err)
+ }
+ if got := currentBranchName(t, result.Path); got != result.BranchName {
+ t.Errorf("replaced checkout is on %q, want %q", got, result.BranchName)
+ }
+ if got := currentBranchName(t, other.Path); got != other.BranchName {
+ t.Errorf("other checkout is on %q, want %q", got, other.BranchName)
+ }
+ moved, err := filepath.Glob(orphan.Path + ".orphaned-*")
+ if err != nil || len(moved) != 1 {
+ t.Fatalf("orphaned tree not moved aside: %v, %v", moved, err)
+ }
+ if _, err := os.Stat(filepath.Join(moved[0], ".git")); !os.IsNotExist(err) {
+ t.Errorf("moved-aside tree still has a .git file pointing at the reused registration: %v", err)
+ }
+ if _, err := os.Stat(filepath.Join(moved[0], ".git.orphaned")); err != nil {
+ t.Errorf("moved-aside tree lost its .git contents: %v", err)
+ }
+}
+
+// Two repos with the same basename have separate bare caches and locks, so a
+// checkout from one can land on the path the other just failed to create.
+// Cleanup for one cache must not delete a tree registered in the other.
+func TestRemovePartialWorktreeKeepsCheckoutOfAnotherCache(t *testing.T) {
+ t.Parallel()
+ repoA, repoB := createTestRepo(t), createTestRepo(t)
+ cache := New(t.TempDir(), testLogger())
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: repoA}, {URL: repoB}}); err != nil {
+ t.Fatalf("sync failed: %v", err)
+ }
+ other, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: repoB,
+ WorkDir: t.TempDir(),
+ AgentName: "agent",
+ TaskID: "e5555555-0000-0000-0000-00000000000e",
+ })
+ if err != nil {
+ t.Fatalf("checkout failed: %v", err)
+ }
+
+ removePartialWorktree(cache.Lookup("ws-1", repoA), other.Path)
+
+ if got := currentBranchName(t, other.Path); got != other.BranchName {
+ t.Errorf("other cache's checkout is on %q, want %q", got, other.BranchName)
+ }
+}
+
+// A `git worktree add` cancelled before it returns must not leave its tree or
+// registration behind; the next checkout then starts clean. The slow
+// post-checkout hook runs after git has written both, so this covers cleanup
+// after a cancelled add rather than a half-written tree.
+func TestCreateWorktreeContextRemovesPartialCheckoutWhenCancelled(t *testing.T) {
+ t.Parallel()
+ sourceRepo := createTestRepo(t)
+ cache := New(t.TempDir(), testLogger())
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {
+ t.Fatalf("sync failed: %v", err)
+ }
+ barePath := cache.Lookup("ws-1", sourceRepo)
+ hook := filepath.Join(barePath, "hooks", "post-checkout")
+ if err := os.MkdirAll(filepath.Dir(hook), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(hook, []byte("#!/bin/sh\nsleep 30\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ workDir := t.TempDir()
+ params := WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: workDir,
+ AgentName: "agent",
+ TaskID: "d4444444-0000-0000-0000-000000000000",
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ if _, err := cache.CreateWorktreeContext(ctx, params); !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("CreateWorktreeContext error = %v, want deadline exceeded", err)
+ }
+ worktreePath := filepath.Join(workDir, repoNameFromURL(sourceRepo))
+ if _, err := os.Stat(worktreePath); !os.IsNotExist(err) {
+ t.Fatalf("partial checkout left at %s, stat error = %v", worktreePath, err)
+ }
+ out, err := exec.Command("git", "-C", barePath, "worktree", "list", "--porcelain").Output()
+ if err != nil {
+ t.Fatalf("worktree list failed: %v", err)
+ }
+ if strings.Contains(string(out), worktreePath) {
+ t.Fatalf("registration for the partial checkout survived:\n%s", out)
+ }
+
+ if err := os.Remove(hook); err != nil {
+ t.Fatal(err)
+ }
+ result, err := cache.CreateWorktree(params)
+ if err != nil {
+ t.Fatalf("checkout after cancellation failed: %v", err)
+ }
+ if got := currentBranchName(t, result.Path); got != result.BranchName {
+ t.Errorf("checkout is on %q, want %q", got, result.BranchName)
+ }
+}
+
// TestGetRemoteDefaultBranchScansForCustomDefault verifies fallback (3) of
// getRemoteDefaultBranch: when the cache has refs/remotes/origin/<custom>
// (e.g. develop, trunk) but no refs/remotes/origin/HEAD and no main/master,