From 53e78a5f75e9c58b413665e3d55fb736d41ce31b Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:29:23 +1100 Subject: [PATCH] Serialize worktree commands per repo --- internal/deploy/deploy.go | 1 + internal/deploy/deploy_test.go | 13 +++++++++++++ internal/deploy/git.go | 8 +++++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 9b8d1d8..c79851b 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -44,6 +44,7 @@ type Deployer struct { sem chan struct{} mu sync.Mutex flights map[string]*flight + wtLocks sync.Map } type flight struct { diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index c5d6cca..6466652 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -816,3 +816,16 @@ func TestPanicFailsOnlyItsEnv(t *testing.T) { t.Fatal("GC skipped after a panicking env") } } + +func TestConcurrentWorktreeAddsOneMirror(t *testing.T) { + f := newFixture(t) + for i := range 40 { + gitT(t, f.control, "checkout", "-q", "-B", fmt.Sprintf("b%d", i)) + commit(t, f.control, map[string]string{"n": fmt.Sprint(i)}) + } + d := New(f.cfg, 16, 10*time.Minute) + d.now = func() time.Time { return f.clock } + if err := d.Deploy(context.Background(), nil, false); err != nil { + t.Fatal(err) + } +} diff --git a/internal/deploy/git.go b/internal/deploy/git.go index 2bc3271..2c6cb20 100644 --- a/internal/deploy/git.go +++ b/internal/deploy/git.go @@ -8,6 +8,7 @@ import ( "os/exec" "slices" "strings" + "sync" "syscall" "time" ) @@ -29,8 +30,13 @@ func runGit(ctx context.Context, dir string, args ...string) (string, error) { return strings.TrimSpace(out.String()), nil } -// git holds a -j slot only for the subprocess itself, so callers never nest slots. +// git holds a -j slot only for the subprocess itself; worktree commands are serialized per repo since concurrent adds read each other's half-written admin dirs. func (d *Deployer) git(ctx context.Context, dir string, args ...string) (out string, err error) { + if len(args) > 0 && args[0] == "worktree" { + mu, _ := d.wtLocks.LoadOrStore(dir, &sync.Mutex{}) + mu.(*sync.Mutex).Lock() + defer mu.(*sync.Mutex).Unlock() + } err = d.limit(func() error { ctx, cancel := context.WithTimeout(ctx, d.gitTimeout) defer cancel()