diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 5c9f718..d03229b 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -226,7 +226,14 @@ func (d *Deployer) Sources() []*Source { func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) error { ctx, end := d.phase(ctx, "run") d.mu.Lock() - clear(d.flights) + maps.DeleteFunc(d.flights, func(_ string, f *flight) bool { + select { + case <-f.done: + return true + default: + return false + } + }) clear(d.skips) clear(d.counts) d.mu.Unlock() diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 3824aa6..d899796 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -15,9 +15,11 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "slices" "strings" "sync" + "sync/atomic" "testing" "time" ) @@ -976,6 +978,9 @@ func TestTimingsPhases(t *testing.T) { labels := map[string][]string{} for _, kv := range timingLines(buf.String()) { labels[kv["phase"]] = append(labels[kv["phase"]], kv["cache"]+kv["outcome"]+kv["reason"]) + if strings.HasPrefix(kv["phase"], "module.") && (kv["source"] != "unkin" || kv["env"] != "main") { + t.Errorf("run %d: module phase lacks inherited source/env: %v", i, kv) + } } got := map[string]string{} for k, v := range labels { @@ -1801,3 +1806,127 @@ func TestCorrectedBranchCollisionKeepsLiveEnv(t *testing.T) { t.Fatal("live feature_x worktree must survive GC past grace") } } + +func TestConcurrentDeploySharesInFlightFetch(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()}) + d := f.deployer() + var srcFetches, modFetches atomic.Int32 + bStarted := make(chan struct{}) + var once sync.Once + d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) { + if slices.Contains(args, "fetch") { + switch { + case slices.Contains(args, f.control): + if srcFetches.Add(1) == 2 { + once.Do(func() { close(bStarted) }) + } + case slices.Contains(args, f.mod): + if modFetches.Add(1) == 1 { + <-bStarted + } + } + } + return runGit(ctx, dir, args...) + } + errc := make(chan error, 2) + go func() { errc <- d.Deploy(context.Background(), nil, false) }() + for modFetches.Load() == 0 { + runtime.Gosched() + } + go func() { errc <- d.Deploy(context.Background(), nil, false) }() + <-errc + <-errc + if n := modFetches.Load(); n != 1 { + t.Fatalf("module mirror fetched %d times; the second Deploy dropped the first's in-flight fetch", n) + } +} + +func TestTimingsRemovalCounts(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "x") + commit(t, f.control, map[string]string{"manifests/site.pp": "# x\n"}) + gitT(t, f.control, "checkout", "-q", "main") + f.mustDeploy(false) + gitT(t, f.control, "branch", "-D", "x") + run := func() map[string]map[string]string { + t.Helper() + var buf bytes.Buffer + d := f.deployer() + d.Timings = slog.New(slog.NewTextHandler(&buf, nil)) + if err := d.Deploy(context.Background(), nil, false); err != nil { + t.Fatal(err) + } + got := map[string]map[string]string{} + for _, kv := range timingLines(buf.String()) { + got[kv["phase"]] = kv + } + return got + } + got := run() + if got["run"]["removed"] != "1" || got["gc.mark"]["marked"] != "1" || got["gc.delete"]["removed"] != "0" { + t.Errorf("removal run: run=%v gc.mark=%v gc.delete=%v", got["run"], got["gc.mark"], got["gc.delete"]) + } + f.clock = f.clock.Add(11 * time.Minute) + got = run() + if got["run"]["removed"] != "0" || got["gc.mark"]["marked"] != "0" || got["gc.delete"]["removed"] != "1" { + t.Errorf("past grace: run=%v gc.mark=%v gc.delete=%v", got["run"], got["gc.mark"], got["gc.delete"]) + } +} + +func TestTimingsPanickingFlightIsMiss(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()}) + d := f.deployer() + d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) { + if slices.Contains(args, "fetch") && slices.Contains(args, f.mod) { + panic("boom") + } + return runGit(ctx, dir, args...) + } + var buf bytes.Buffer + d.Timings = slog.New(slog.NewTextHandler(&buf, nil)) + if err := d.Deploy(context.Background(), nil, false); err == nil || !strings.Contains(err.Error(), "panic: boom") { + t.Fatalf("panic not reported: %v", err) + } + var got []string + for _, kv := range timingLines(buf.String()) { + if kv["phase"] == "module.fetch" { + got = append(got, kv["cache"]) + } + } + slices.Sort(got) + if !slices.Equal(got, []string{"miss", "shared"}) { + t.Errorf("panicking fetch cache labels %v, want [miss shared]\n%s", got, buf.String()) + } +} + +func TestTimingsWorktreeLockWait(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "\n"}) + d := f.deployer() + var buf bytes.Buffer + d.Timings = slog.New(slog.NewTextHandler(&buf, nil)) + d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) { + if slices.Contains(args, "remove") { + mu := &sync.Mutex{} + mu.Lock() + d.wtLocks.Store(dir, mu) + time.AfterFunc(50*time.Millisecond, mu.Unlock) + } + return runGit(ctx, dir, args...) + } + if err := d.Deploy(context.Background(), nil, false); err != nil { + t.Fatal(err) + } + for _, kv := range timingLines(buf.String()) { + if kv["phase"] == "env.worktree" { + if w, err := time.ParseDuration(kv["wait"]); err != nil || w < 25*time.Millisecond { + t.Errorf("env.worktree wait=%s, want the worktree lock wait", kv["wait"]) + } + return + } + } + t.Fatalf("no env.worktree line:\n%s", buf.String()) +} diff --git a/internal/deploy/git.go b/internal/deploy/git.go index 10d03a0..145f10b 100644 --- a/internal/deploy/git.go +++ b/internal/deploy/git.go @@ -30,11 +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; worktree commands are serialized per repo since concurrent adds read each other's half-written admin dirs. +// 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, and both waits count as wait. 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{}) + t := time.Now() mu.(*sync.Mutex).Lock() + addWait(ctx, time.Since(t)) defer mu.(*sync.Mutex).Unlock() } err = d.limit(ctx, func() error { diff --git a/internal/deploy/timing.go b/internal/deploy/timing.go index 7d51f5e..271f80b 100644 --- a/internal/deploy/timing.go +++ b/internal/deploy/timing.go @@ -28,7 +28,7 @@ func addWait(ctx context.Context, w time.Duration) { } } -// phase times one unit of work; nested phases inherit attrs, and leaf phases report their -j slot waits as wait. +// phase times one unit of work; nested phases inherit attrs, and leaf phases report their -j slot and worktree lock waits as wait. func (d *Deployer) phase(ctx context.Context, name string, attrs ...any) (context.Context, func(more ...any)) { if d.Timings == nil { return ctx, func(...any) {} diff --git a/main_test.go b/main_test.go index adb41cd..3282dcb 100644 --- a/main_test.go +++ b/main_test.go @@ -2,11 +2,41 @@ package main import ( "bytes" + "fmt" + "log/slog" "os" "path/filepath" + "strings" "testing" ) +func TestTimingsFlag(t *testing.T) { + root := t.TempDir() + cfg := filepath.Join(root, "r10k.yaml") + body := fmt.Sprintf("cachedir: %s\nsources:\n s:\n remote: %s\n basedir: %s\n", filepath.Join(root, "cache"), filepath.Join(root, "control"), filepath.Join(root, "envs")) + if err := os.WriteFile(cfg, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + prev := slog.Default() + defer slog.SetDefault(prev) + for _, on := range []bool{false, true} { + var buf bytes.Buffer + slog.SetDefault(slog.New(slog.NewTextHandler(&buf, nil))) + args := []string{"gc", "-c", cfg} + if on { + args = append(args, "--timings") + } + cmd := rootCmd() + cmd.SetArgs(args) + if err := cmd.Execute(); err != nil { + t.Fatal(err) + } + if got := strings.Contains(buf.String(), "phase=gc.mark"); got != on { + t.Errorf("--timings=%v: gc.mark emitted=%v\n%s", on, got, buf.String()) + } + } +} + func TestListShowsAliasRows(t *testing.T) { root := t.TempDir() cache, base := filepath.Join(root, "cache"), filepath.Join(root, "code")