From cee4a1fb8d5295023cb023d205969bd3a7983c1b Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:31:06 +1100 Subject: [PATCH 1/6] Scope named deploys to their envs and complete env args --- internal/deploy/deploy.go | 53 ++++++++++++++++++++++------------ internal/deploy/deploy_test.go | 36 +++++++++++++++++++++++ main.go | 51 +++++++++++++++++++++----------- 3 files changed, 105 insertions(+), 35 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 6e3d49d..239e367 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -168,27 +168,29 @@ func (d *Deployer) Sources() []*Source { return out } +// Deploy builds every environment, or only those named by env or branch; a named deploy skips purge and GC. func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) error { ctx, end := d.phase(ctx, "run") - want := map[string]bool{} - for _, e := range only { - want[e] = true - } d.mu.Lock() clear(d.skips) clear(d.counts) d.mu.Unlock() + found := map[string]bool{} var errs []error for _, s := range d.Sources() { - if err := d.deploySource(ctx, s, want, modules); err != nil { + if err := d.deploySource(ctx, s, only, found, modules); err != nil { errs = append(errs, fmt.Errorf("source %s: %w", s.Name, err)) } } - for e := range want { - errs = append(errs, fmt.Errorf("environment %s not found", e)) + for _, e := range only { + if !found[e] { + errs = append(errs, fmt.Errorf("environment %s not found", e)) + } } - if err := d.GC(ctx); err != nil { - errs = append(errs, err) + if len(only) == 0 { + if err := d.GC(ctx); err != nil { + errs = append(errs, err) + } } d.mu.Lock() for _, e := range slices.Sorted(maps.Keys(d.skips)) { @@ -209,7 +211,17 @@ func (d *Deployer) count(outcome string) { d.mu.Unlock() } -func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]string, []error) { +// Matches reports whether arg names env, either directly or as a branch that sanitises to it. +func (s *Source) Matches(arg, env string) bool { + n, _, err := s.EnvName(arg) + return arg == env || err == nil && n == env +} + +// Environments maps env name -> sha for every branch, or only the branches only names. +func (d *Deployer) Environments(ctx context.Context, s *Source, only ...string) (map[string]string, []error) { + wanted := func(branch, name string) bool { + return len(only) == 0 || slices.ContainsFunc(only, func(a string) bool { return a == branch || name != "" && s.Matches(a, name) }) + } all, err := d.branches(ctx, d.srcMirror(s)) if err != nil { return nil, []error{err} @@ -226,6 +238,9 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]stri continue } name, corrected, err := s.EnvName(b) + if !wanted(b, name) { + continue + } if err != nil { errs = append(errs, err) continue @@ -242,7 +257,7 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]stri return envs, errs } -func (d *Deployer) deploySource(ctx context.Context, s *Source, want map[string]bool, modules bool) error { +func (d *Deployer) deploySource(ctx context.Context, s *Source, only []string, found map[string]bool, modules bool) error { fctx, end := d.phase(ctx, "source.fetch", "source", s.Name) err := d.syncMirror(fctx, d.srcMirror(s), s.Remote, envRefspecs...) end() @@ -250,22 +265,24 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want map[string] return err } bctx, end := d.phase(ctx, "source.branches", "source", s.Name) - envs, errs := d.Environments(bctx, s) + envs, errs := d.Environments(bctx, s, only...) end("envs", len(envs)) if envs == nil { return errors.Join(errs...) } - full := len(want) == 0 + for name := range envs { + for _, a := range only { + if s.Matches(a, name) { + found[a] = true + } + } + } if err := os.MkdirAll(s.Basedir, 0o755); err != nil { return err } var mu sync.Mutex var wg sync.WaitGroup for name, sha := range envs { - if !full && !want[name] { - continue - } - delete(want, name) wg.Add(1) go func() { defer wg.Done() @@ -277,7 +294,7 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want map[string] }() } wg.Wait() - if full { + if len(only) == 0 { errs = append(errs, d.purge(s, envs)) } return errors.Join(errs...) diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 77d8ba7..3c023e6 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -772,6 +772,42 @@ func TestGCKeepsModulesOfRemovedSource(t *testing.T) { } } +func TestNamedDeployTouchesOnlyNamed(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "branch", "gone") + commit(t, f.control, map[string]string{"manifests/site.pp": "node default { }\n"}) + gitT(t, f.control, "branch", "benvin/foo-bar") + f.mustDeploy(false) + gone := f.env("gone") + gitT(t, f.control, "branch", "-D", "gone") + f.mustDeploy(false) + f.clock = f.clock.Add(11 * time.Minute) + state := readFileT(t, f.cache(gcStateFile)) + + sha := commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) + gitT(t, f.control, "branch", "-f", "benvin/foo-bar", "main") + main := f.env("main") + if err := f.deploy(false, "benvin/foo-bar"); err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(filepath.Base(f.env("benvin_foo_bar")), sha+"-") { + t.Fatal("a raw branch name deploys its sanitised env") + } + if f.env("main") != main || !exists(gone) || readFileT(t, f.cache(gcStateFile)) != state { + t.Fatal("a named deploy must leave other envs, their worktrees and GC state untouched") + } + if err := f.deploy(false, "main"); err != nil || !strings.HasPrefix(filepath.Base(f.env("main")), sha+"-") { + t.Fatalf("env name deploys: %v", err) + } + if err := f.deploy(false, "main", "nope"); err == nil || !strings.Contains(err.Error(), "nope not found") { + t.Fatalf("unknown env must error: %v", err) + } + if !exists(gone) { + t.Fatal("named deploys never GC") + } +} + func TestTimingsPhases(t *testing.T) { f := newFixture(t) f.cfg.W10k.GenerateTypes = true diff --git a/main.go b/main.go index 18f7850..6efec92 100644 --- a/main.go +++ b/main.go @@ -4,10 +4,11 @@ import ( "context" "fmt" "log/slog" + "maps" "os" "os/signal" "path/filepath" - "sort" + "slices" "strings" "syscall" "time" @@ -50,6 +51,24 @@ func rootCmd() *cobra.Command { } return d, nil } + live := func() ([][3]string, error) { + d, err := load() + if err != nil { + return nil, err + } + var rows [][3]string + for _, s := range d.Sources() { + live, err := d.Live(s) + if err != nil { + return nil, err + } + for _, e := range slices.Sorted(maps.Keys(live)) { + sha, _, _ := strings.Cut(filepath.Base(live[e]), "-") + rows = append(rows, [3]string{s.Name, e, sha}) + } + } + return rows, nil + } locked := func(fn func(*deploy.Deployer) error) error { d, err := load() if err != nil { @@ -77,10 +96,20 @@ func rootCmd() *cobra.Command { var modules bool deployCmd := &cobra.Command{ Use: "deploy [env...]", - Short: "Deploy all environments, or only the named ones", + Short: "Deploy all environments, or only the named ones (env or branch names)", RunE: func(cmd *cobra.Command, args []string) error { return locked(func(d *deploy.Deployer) error { return d.Deploy(cmd.Context(), args, modules) }) }, + ValidArgsFunction: func(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) { + rows, _ := live() + var envs []string + for _, r := range rows { + if !slices.Contains(args, r[1]) && !slices.Contains(envs, r[1]) { + envs = append(envs, r[1]) + } + } + return envs, cobra.ShellCompDirectiveNoFileComp + }, } deployCmd.Flags().BoolVarP(&modules, "modules", "m", false, "re-resolve Puppetfile modules for unchanged environments") @@ -89,24 +118,12 @@ func rootCmd() *cobra.Command { Short: "List deployed environments", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - d, err := load() + rows, err := live() if err != nil { return err } - for _, s := range d.Sources() { - live, err := d.Live(s) - if err != nil { - return err - } - envs := make([]string, 0, len(live)) - for e := range live { - envs = append(envs, e) - } - sort.Strings(envs) - for _, e := range envs { - sha, _, _ := strings.Cut(filepath.Base(live[e]), "-") - _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\n", s.Name, e, sha) - } + for _, r := range rows { + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\n", r[0], r[1], r[2]) } return nil }, From 7d457a89cf962896464759600debfe503ead9276 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:32:25 +1100 Subject: [PATCH 2/6] Clear GC marks for worktrees and modules a named deploy swaps in --- internal/deploy/deploy.go | 38 ++++++++++++++++++++++- internal/deploy/deploy_test.go | 55 +++++++++++++++++++++++++++------- 2 files changed, 81 insertions(+), 12 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 239e367..beb9dcc 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -46,6 +46,7 @@ type Deployer struct { mu sync.Mutex flights map[string]*flight skips map[string]int + revived []string counts map[string]int Timings *slog.Logger } @@ -168,12 +169,13 @@ func (d *Deployer) Sources() []*Source { return out } -// Deploy builds every environment, or only those named by env or branch; a named deploy skips purge and GC. +// Deploy builds every environment, or only those named by env or branch; a named deploy skips purge and GC but unmarks what it swaps in. func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) error { ctx, end := d.phase(ctx, "run") d.mu.Lock() clear(d.skips) clear(d.counts) + d.revived = nil d.mu.Unlock() found := map[string]bool{} var errs []error @@ -191,6 +193,8 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro if err := d.GC(ctx); err != nil { errs = append(errs, err) } + } else if err := d.unmark(d.revived); err != nil { + errs = append(errs, err) } d.mu.Lock() for _, e := range slices.Sorted(maps.Keys(d.skips)) { @@ -386,6 +390,12 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, m if err != nil { return err } + d.mu.Lock() + d.revived = append(d.revived, target) + for _, m := range mods { + d.revived = append(d.revived, m.dir) + } + d.mu.Unlock() outcome = "updated" if cur == "" { outcome = "created" @@ -860,6 +870,32 @@ func (d *Deployer) GC(ctx context.Context) error { return errors.Join(append(g.errs, err)...) } +// unmark drops GC marks for paths a named deploy made live again, so they get a fresh grace period once unreferenced. +func (d *Deployer) unmark(paths []string) error { + statePath := d.path(gcStateFile) + b, err := os.ReadFile(statePath) + if os.IsNotExist(err) { + return nil + } else if err != nil { + return err + } + marks := map[string]time.Time{} + if err := json.Unmarshal(b, &marks); err != nil { + return fmt.Errorf("gc: %s: %w", statePath, err) + } + n := len(marks) + for _, p := range paths { + delete(marks, p) + } + if len(marks) == n { + return nil + } + if b, err = json.MarshalIndent(marks, "", " "); err != nil { + return err + } + return writeAtomic(statePath, b) +} + // moduleRefs returns every module dir referenced by any source's env worktree on disk or by any link in a configured basedir. func (d *Deployer) moduleRefs(liveEnv map[string]bool) (map[string]bool, error) { wts := map[string]bool{} diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 3c023e6..95db334 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -7,6 +7,7 @@ import ( "fmt" "log" "log/slog" + "maps" "net" "net/http" "net/http/httptest" @@ -774,40 +775,72 @@ func TestGCKeepsModulesOfRemovedSource(t *testing.T) { func TestNamedDeployTouchesOnlyNamed(t *testing.T) { f := newFixture(t) - commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node default {}\n"}) + old := commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node default {}\n"}) gitT(t, f.control, "branch", "gone") + commit(t, f.control, map[string]string{"manifests/site.pp": "node other {}\n"}) + gitT(t, f.control, "branch", "gone2") commit(t, f.control, map[string]string{"manifests/site.pp": "node default { }\n"}) gitT(t, f.control, "branch", "benvin/foo-bar") f.mustDeploy(false) - gone := f.env("gone") - gitT(t, f.control, "branch", "-D", "gone") + gone, gone2 := f.env("gone"), f.env("gone2") + gitT(t, f.control, "branch", "-D", "gone", "gone2") f.mustDeploy(false) f.clock = f.clock.Add(11 * time.Minute) - state := readFileT(t, f.cache(gcStateFile)) + marks := func() map[string]time.Time { + m := map[string]time.Time{} + if err := json.Unmarshal([]byte(readFileT(t, f.cache(gcStateFile))), &m); err != nil { + t.Fatal(err) + } + return m + } + before := marks() + if _, ok := before[gone2]; !ok { + t.Fatalf("gone2 must be marked: %v", before) + } - sha := commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) - gitT(t, f.control, "branch", "-f", "benvin/foo-bar", "main") + gitT(t, f.control, "branch", "-f", "benvin/foo-bar", old) main := f.env("main") if err := f.deploy(false, "benvin/foo-bar"); err != nil { t.Fatal(err) } - if !strings.HasPrefix(filepath.Base(f.env("benvin_foo_bar")), sha+"-") { - t.Fatal("a raw branch name deploys its sanitised env") + if f.env("benvin_foo_bar") != gone { + t.Fatal("a raw branch name deploys its sanitised env, reviving the matching worktree") } - if f.env("main") != main || !exists(gone) || readFileT(t, f.cache(gcStateFile)) != state { - t.Fatal("a named deploy must leave other envs, their worktrees and GC state untouched") + delete(before, gone) + if f.env("main") != main || !exists(gone2) || !maps.Equal(marks(), before) { + t.Fatalf("a named deploy must clear only the marks of what it revives: %v", marks()) } + sha := commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) if err := f.deploy(false, "main"); err != nil || !strings.HasPrefix(filepath.Base(f.env("main")), sha+"-") { t.Fatalf("env name deploys: %v", err) } if err := f.deploy(false, "main", "nope"); err == nil || !strings.Contains(err.Error(), "nope not found") { t.Fatalf("unknown env must error: %v", err) } - if !exists(gone) { + if !exists(gone2) { t.Fatal("named deploys never GC") } } +func TestNamedDeployRevivedWorktreeKeepsGrace(t *testing.T) { + f := newFixture(t) + a := commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node a {}\n"}) + f.mustDeploy(false) + wa := f.env("main") + commit(t, f.control, map[string]string{"manifests/site.pp": "node b {}\n"}) + f.mustDeploy(false) + f.clock = f.clock.Add(11 * time.Minute) + gitT(t, f.control, "reset", "-q", "--hard", a) + if err := f.deploy(false, "main"); err != nil || f.env("main") != wa { + t.Fatalf("named deploy must revive wa: %v", err) + } + commit(t, f.control, map[string]string{"manifests/site.pp": "node c {}\n"}) + f.mustDeploy(false) + if !exists(wa) { + t.Fatal("replaced worktree GC'd on a stale mark; grace skipped") + } +} + func TestTimingsPhases(t *testing.T) { f := newFixture(t) f.cfg.W10k.GenerateTypes = true From e73f3c8e1f256e378be19181c6b259c204c57e5c Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:54:57 +1100 Subject: [PATCH 3/6] Cap forge archive download and extracted size --- internal/deploy/forge.go | 30 ++++++++++++++++++++++++++---- internal/deploy/forge_test.go | 25 +++++++++++++++++++++++-- 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/internal/deploy/forge.go b/internal/deploy/forge.go index 23696e8..e89172a 100644 --- a/internal/deploy/forge.go +++ b/internal/deploy/forge.go @@ -14,7 +14,11 @@ import ( "time" ) -const defaultForge = "https://forgeapi.puppet.com" +const ( + defaultForge = "https://forgeapi.puppet.com" + maxForgeDownload = 100 << 20 + maxForgeExtracted = 512 << 20 +) var httpClient = &http.Client{Timeout: 5 * time.Minute} @@ -79,24 +83,42 @@ func forgeInstall(ctx context.Context, base, release, dir string) error { if err != nil { return err } - if err := extract(body, tmp); err != nil { + if err := extract(&capReader{r: body, n: maxForgeDownload}, tmp, maxForgeExtracted); err != nil { _ = os.RemoveAll(tmp) return fmt.Errorf("%s: %w", release, err) } return os.Rename(tmp, dir) } -func extract(r io.Reader, dst string) error { +// capReader fails once more than n bytes are read, so an oversized stream errors instead of being truncated silently. +type capReader struct { + r io.Reader + n int64 +} + +func (c *capReader) Read(p []byte) (int, error) { + if int64(len(p)) > c.n+1 { + p = p[:c.n+1] + } + n, err := c.r.Read(p) + if c.n -= int64(n); c.n < 0 { + return 0, fmt.Errorf("archive exceeds size cap") + } + return n, err +} + +func extract(r io.Reader, dst string, limit int64) error { gz, err := gzip.NewReader(r) if err != nil { return err } + cr := &capReader{r: gz, n: limit} root, err := os.OpenRoot(dst) if err != nil { return err } defer func() { _ = root.Close() }() - tr := tar.NewReader(gz) + tr := tar.NewReader(cr) for { hdr, err := tr.Next() if err == io.EOF { diff --git a/internal/deploy/forge_test.go b/internal/deploy/forge_test.go index 292ebd7..6598222 100644 --- a/internal/deploy/forge_test.go +++ b/internal/deploy/forge_test.go @@ -4,8 +4,10 @@ import ( "archive/tar" "bytes" "compress/gzip" + "io" "os" "path/filepath" + "strings" "testing" ) @@ -58,7 +60,7 @@ func TestExtractStripsTopDir(t *testing.T) { entry{name: "./puppetlabs-stdlib-9.7.0/lib/x.rb", body: "x", mode: 0o644}, entry{name: "puppetlabs-stdlib-9.7.0/bin/run", body: "#!", mode: 0o700}, entry{name: "puppetlabs-stdlib-9.7.0/link", body: "/etc/passwd", typ: tar.TypeSymlink}, - )), dst) + )), dst, maxForgeExtracted) if err != nil { t.Fatal(err) } @@ -75,7 +77,7 @@ func TestExtractStripsTopDir(t *testing.T) { func TestExtractRejectsTraversal(t *testing.T) { dst := t.TempDir() - err := extract(bytes.NewReader(tarball(t, entry{name: "m-1/../../evil", body: "x", mode: 0o644})), dst) + err := extract(bytes.NewReader(tarball(t, entry{name: "m-1/../../evil", body: "x", mode: 0o644})), dst, maxForgeExtracted) if err == nil { t.Fatal("expected traversal error") } @@ -95,3 +97,22 @@ func TestForgeURL(t *testing.T) { } } } + +func TestExtractRejectsOversize(t *testing.T) { + big := entry{name: "m/a", body: strings.Repeat("x", 4096), mode: 0o644} + if err := extract(bytes.NewReader(tarball(t, big)), t.TempDir(), 1024); err == nil { + t.Fatal("want extracted size cap error") + } + if err := extract(bytes.NewReader(tarball(t, big)), t.TempDir(), 1<<20); err != nil { + t.Fatal(err) + } +} + +func TestCapReaderErrorsAtCap(t *testing.T) { + if _, err := io.ReadAll(&capReader{r: strings.NewReader("abcdef"), n: 4}); err == nil { + t.Fatal("want cap error") + } + if b, err := io.ReadAll(&capReader{r: strings.NewReader("abc"), n: 4}); err != nil || string(b) != "abc" { + t.Fatalf("under cap: %q %v", b, err) + } +} From 66580c9b37a0fc2d42b7a7829f8601776101cf01 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:54:57 +1100 Subject: [PATCH 4/6] Keep GC off targeted deploys, always drop live marks, let exact branches win env names --- internal/deploy/deploy.go | 111 ++++++++++++++++++------- internal/deploy/deploy_test.go | 146 +++++++++++++++++++++++++++++++++ 2 files changed, 226 insertions(+), 31 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 0c1868f..0fdbb21 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -9,10 +9,12 @@ import ( "errors" "fmt" "log" + "maps" "os" "path/filepath" "regexp" "runtime/debug" + "slices" "sort" "strings" "sync" @@ -216,9 +218,7 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro errs = append(errs, fmt.Errorf("environment %s not found", e)) } } - if err := d.GC(ctx); err != nil { - errs = append(errs, err) - } + errs = append(errs, d.gc(ctx, len(only) == 0)) return errors.Join(errs...) } @@ -234,7 +234,8 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envR names = append(names, b) } sort.Strings(names) - envs := map[string]envRef{} + claims := map[string][]string{} + exact := map[string]string{} var errs []error for _, b := range names { if s.Ignored(b) { @@ -245,14 +246,31 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envR errs = append(errs, err) continue } - if corrected && s.InvalidBranches == "correct_and_warn" { - log.Printf("warning: branch %s deployed as environment %s", b, name) + if !corrected { + exact[name] = b } - if _, dup := envs[name]; dup { - errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name)) + claims[name] = append(claims[name], b) + } + envs := map[string]envRef{} + for _, name := range slices.Sorted(maps.Keys(claims)) { + bs := claims[name] + win, isExact := exact[name] + if !isExact && len(bs) == 1 { + win = bs[0] + } + if win == "" { + errs = append(errs, fmt.Errorf("branches %s all correct to environment %s, skipped", strings.Join(bs, ", "), name)) continue } - envs[name] = envRef{b, all[b]} + for _, b := range bs { + if b != win { + errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name)) + } + } + if !isExact && s.InvalidBranches == "correct_and_warn" { + log.Printf("warning: branch %s deployed as environment %s", win, name) + } + envs[name] = envRef{win, all[win]} } return envs, errs } @@ -697,26 +715,46 @@ func (g *gcRun) sweep(mirror, dir string, live map[string]bool, remove func(stri } } -func (d *Deployer) GC(ctx context.Context) error { - g := &gcRun{d: d, ctx: ctx, marks: map[string]time.Time{}, seen: map[string]bool{}} - statePath := d.path(gcStateFile) - if b, err := os.ReadFile(statePath); err == nil { - if err := json.Unmarshal(b, &g.marks); err != nil { - return fmt.Errorf("gc: %s: %w", statePath, err) +func (d *Deployer) GC(ctx context.Context) error { return d.gc(ctx, true) } + +// gc drops the mark of everything live this run; only a sweep may add marks or delete, and only where every live set it needs was computed. +func (d *Deployer) gc(ctx context.Context, sweep bool) (err error) { + g := &gcRun{d: d, ctx: ctx, marks: d.loadMarks(), seen: map[string]bool{}} + defer func() { + for p := range g.marks { + if !g.seen[p] { + delete(g.marks, p) + } } - } else if !os.IsNotExist(err) { - return err - } + err = errors.Join(append(g.errs, d.saveMarks(g.marks))...) + }() liveEnv := map[string]bool{} + var ok []*Source for _, s := range d.Sources() { live, err := d.Live(s) if err != nil { - return fmt.Errorf("gc: %w", err) + g.errs = append(g.errs, fmt.Errorf("gc: %w", err)) + continue } + ok = append(ok, s) for _, t := range live { liveEnv[t] = true } + } + if !sweep { + liveMod, err := d.moduleRefs(liveEnv) + if err != nil || len(g.errs) > 0 { + g.errs = append(g.errs, err) + return nil + } + for p := range g.marks { + g.seen[p] = !liveEnv[p] && !liveMod[p] + } + return nil + } + + for _, s := range ok { mirror := d.srcMirror(s) g.sweep(mirror, d.srcWorktrees(s), liveEnv, func(p string) error { if err := os.Remove(d.doneFile(p)); err != nil && !os.IsNotExist(err) { @@ -731,7 +769,9 @@ func (d *Deployer) GC(ctx context.Context) error { } } } - + if len(ok) < len(d.cfg.Sources) { + return nil + } liveMod, err := d.moduleRefs(liveEnv) if err != nil { g.errs = append(g.errs, err) @@ -743,20 +783,29 @@ func (d *Deployer) GC(ctx context.Context) error { } g.sweep("", d.path("forge"), liveMod, func(p string) error { return d.discard(ctx, "", p) }) } + return nil +} - for p := range g.marks { - if !g.seen[p] { - delete(g.marks, p) - } - } - b, err := json.MarshalIndent(g.marks, "", " ") +// loadMarks treats an unreadable state file as empty, which only delays deletion. +func (d *Deployer) loadMarks() map[string]time.Time { + marks := map[string]time.Time{} + b, err := os.ReadFile(d.path(gcStateFile)) if err == nil { - tmp := statePath + ".tmp" - if err = os.WriteFile(tmp, b, 0o644); err == nil { - err = os.Rename(tmp, statePath) - } + err = json.Unmarshal(b, &marks) } - return errors.Join(append(g.errs, err)...) + if err != nil && !os.IsNotExist(err) { + log.Printf("gc: discarding unreadable %s: %v", gcStateFile, err) + marks = map[string]time.Time{} + } + return marks +} + +func (d *Deployer) saveMarks(marks map[string]time.Time) error { + b, err := json.MarshalIndent(marks, "", " ") + if err != nil { + return err + } + return writeAtomic(d.path(gcStateFile), b) } // moduleRefs returns every module dir referenced by any source's env worktree on disk or by any link in a configured basedir. diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 62474c7..c9acd44 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -910,3 +910,149 @@ func TestDeployMarkerNameIsBranch(t *testing.T) { t.Fatalf("marker name %q, want branch feat/x", m.Name) } } + +func TestTargetedDeploySkipsGC(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + f.mustDeploy(false) + old := f.env("main") + commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) + f.mustDeploy(false) + f.clock = f.clock.Add(time.Hour) + if err := f.deploy(false, "main"); err != nil { + t.Fatal(err) + } + if !exists(old) { + t.Fatalf("targeted deploy ran GC and removed %s", old) + } +} + +func TestTargetedDeployDropsMarkOfReusedWorktree(t *testing.T) { + f := newFixture(t) + sha1 := commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + f.mustDeploy(false) + w1 := f.env("main") + commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) + f.mustDeploy(false) + f.clock = f.clock.Add(time.Hour) + gitT(t, f.control, "reset", "-q", "--hard", sha1) + if err := f.deploy(false, "main"); err != nil || f.env("main") != w1 { + t.Fatalf("targeted deploy did not reuse %s: %v", w1, err) + } + commit(t, f.control, map[string]string{"manifests/site.pp": "node y {}\n"}) + if err := f.deploy(false, "main"); err != nil { + t.Fatal(err) + } + f.mustDeploy(false) + if !exists(w1) { + t.Fatal("worktree live during a targeted deploy kept its earlier mark and was deleted without grace") + } +} + +func TestGCLiveErrorDropsMarkOfLiveWorktree(t *testing.T) { + root := t.TempDir() + s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")} + u := &Source{Name: "u", Basedir: filepath.Join(root, "uenvs")} + cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s, "u": u}} + clock := time.Unix(1_700_000_000, 0) + gc := func() error { + d := New(cfg, 1, 10*time.Minute) + d.now = func() time.Time { return clock } + return d.GC(context.Background()) + } + d := New(cfg, 1, 0) + old, cur := filepath.Join(d.srcWorktrees(s), "old"), filepath.Join(d.srcWorktrees(s), "cur") + mkdirs(t, old, cur, s.Basedir, filepath.Dir(d.doneFile(old))) + for _, p := range []string{old, cur} { + if err := os.WriteFile(d.doneFile(p), []byte(`{"modules":[]}`), 0o644); err != nil { + t.Fatal(err) + } + } + link := filepath.Join(s.Basedir, "develop") + if err := Swap(cur, link); err != nil { + t.Fatal(err) + } + if err := gc(); err != nil { + t.Fatal(err) + } + clock = clock.Add(time.Hour) + if err := Swap(old, link); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(u.Basedir, nil, 0o644); err != nil { + t.Fatal(err) + } + if err := gc(); err == nil { + t.Fatal("want Live error") + } + if err := os.Remove(u.Basedir); err != nil { + t.Fatal(err) + } + if err := Swap(cur, link); err != nil { + t.Fatal(err) + } + _ = gc() + if !exists(old) { + t.Fatal("worktree unreferenced this run was deleted in the same run via a mark kept by GC's early return") + } +} + +func TestGCCorruptStateTreatedAsEmpty(t *testing.T) { + root := t.TempDir() + s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")} + cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s}} + d := New(cfg, 1, 10*time.Minute) + old := filepath.Join(d.srcWorktrees(s), "old") + mkdirs(t, old, s.Basedir) + state := d.path(gcStateFile) + if err := os.WriteFile(state, []byte("{not json"), 0o644); err != nil { + t.Fatal(err) + } + if err := d.GC(context.Background()); err != nil { + t.Fatalf("corrupt state wedged GC: %v", err) + } + b, err := os.ReadFile(state) + if err != nil { + t.Fatal(err) + } + var marks map[string]time.Time + if err := json.Unmarshal(b, &marks); err != nil { + t.Fatalf("state not rewritten: %v", err) + } + if _, ok := marks[old]; !ok || !exists(old) { + t.Fatal("unreferenced worktree must be freshly marked, not deleted") + } +} + +func TestExactBranchWinsEnvName(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "feature_x") + legit := commit(t, f.control, map[string]string{"manifests/site.pp": "node legit {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "feature-x") + commit(t, f.control, map[string]string{"manifests/site.pp": "node evil {}\n"}) + err := f.deploy(false) + if got := f.env("feature_x"); !strings.HasPrefix(filepath.Base(got), legit+"-") { + t.Fatalf("env feature_x -> %s, want branch feature_x (%s); a pushed feature-x took it over", filepath.Base(got), legit) + } + if err == nil || !strings.Contains(err.Error(), "feature-x") { + t.Fatalf("want collision error naming feature-x, got %v", err) + } +} + +func TestCorrectedBranchCollisionSkipsAll(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "branch", "feature-x") + gitT(t, f.control, "branch", "feature.x") + err := f.deploy(false) + if exists(filepath.Join(f.basedir, "feature_x")) { + t.Fatal("colliding corrected branches must not deploy feature_x") + } + if err == nil || !strings.Contains(err.Error(), "feature-x") || !strings.Contains(err.Error(), "feature.x") { + t.Fatalf("want collision error naming both branches, got %v", err) + } + if f.env("main") == "" { + t.Fatal("collision must not block other envs") + } +} From 503db52306a797cf599f1d585dbea935793ed653 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 21:04:45 +1100 Subject: [PATCH 5/6] Resolve named deploys over all branches and sources before filtering - pick env winners over every branch, then select, so a named deploy matches a full deploy - match env names across sources first, raw branch names only when no env matches - report collision and invalid-name errors only for the named args - add tests for collision losers, all-corrected collisions, prefixed sources and unrelated invalid branches --- internal/deploy/deploy.go | 138 +++++++++++++++++++++++++-------- internal/deploy/deploy_test.go | 71 +++++++++++++++++ 2 files changed, 175 insertions(+), 34 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 9c9aed2..65accc5 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -225,25 +225,26 @@ func (d *Deployer) Sources() []*Source { // Deploy builds every environment, or only those named by env or branch; a named deploy skips purge and GC. func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) error { ctx, end := d.phase(ctx, "run") - want := map[string]bool{} - for _, e := range only { - want[e] = true - } d.mu.Lock() clear(d.flights) clear(d.skips) clear(d.counts) d.mu.Unlock() - found := map[string]bool{} var errs []error + var plans []*srcPlan for _, s := range d.Sources() { - if err := d.deploySource(ctx, s, want, found, modules); err != nil { + p, err := d.planSource(ctx, s) + if err != nil { + d.count("failed") errs = append(errs, fmt.Errorf("source %s: %w", s.Name, err)) + continue } + plans = append(plans, p) } - for e := range want { - if !found[e] { - errs = append(errs, fmt.Errorf("environment %s not found", e)) + errs = append(errs, d.selectEnvs(plans, only)...) + for _, p := range plans { + if err := d.deploySource(ctx, p, modules); err != nil { + errs = append(errs, fmt.Errorf("source %s: %w", p.s.Name, err)) } } errs = append(errs, d.gc(ctx, len(only) == 0)) @@ -260,6 +261,68 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro return errors.Join(errs...) } +// srcPlan is a source's resolved envs, the branches that got none and why, and the envs to build (nil = all). +type srcPlan struct { + s *Source + envs map[string]envRef + skipped map[string]error + want map[string]bool +} + +// selectEnvs resolves args to envs as a full deploy would: env names in any source first, else raw branch names. +func (d *Deployer) selectEnvs(plans []*srcPlan, only []string) []error { + if len(only) == 0 { + return nil + } + var errs []error + for _, p := range plans { + p.want = map[string]bool{} + } + for _, a := range only { + isEnv := slices.ContainsFunc(plans, func(p *srcPlan) bool { _, ok := p.envs[a]; return ok }) + hit := false + var why []error + for _, p := range plans { + if isEnv { + if _, ok := p.envs[a]; ok { + p.want[a], hit = true, true + } + continue + } + for name, ref := range p.envs { + if ref.branch == a { + p.want[name], hit = true, true + } + } + for _, err := range p.skipErrs(func(b string) bool { + name, _, _ := p.s.EnvName(b) + return b == a || name == a + }) { + d.count("failed") + why = append(why, fmt.Errorf("source %s: %w", p.s.Name, err)) + } + } + if !hit && len(why) == 0 { + why = append(why, fmt.Errorf("environment %s not found", a)) + } + errs = append(errs, why...) + } + return errs +} + +// skipErrs returns the distinct reasons, in branch order, for skipped branches match accepts. +func (p *srcPlan) skipErrs(match func(string) bool) []error { + var out []error + seen := map[error]bool{} + for _, b := range slices.Sorted(maps.Keys(p.skipped)) { + if err := p.skipped[b]; match(b) && !seen[err] { + seen[err] = true + out = append(out, err) + } + } + return out +} + func (d *Deployer) count(outcome string) { d.mu.Lock() d.counts[outcome]++ @@ -268,11 +331,11 @@ func (d *Deployer) count(outcome string) { type envRef struct{ branch, sha string } -// Environments maps env name -> branch and sha for every branch, or only those want names by branch or env. -func (d *Deployer) Environments(ctx context.Context, s *Source, want map[string]bool) (map[string]envRef, []error) { +// Environments maps env name -> branch and sha, and each branch that gets no env to why. +func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envRef, map[string]error, error) { all, err := d.branches(ctx, d.srcMirror(s)) if err != nil { - return nil, []error{err} + return nil, nil, err } names := make([]string, 0, len(all)) for b := range all { @@ -281,17 +344,14 @@ func (d *Deployer) Environments(ctx context.Context, s *Source, want map[string] sort.Strings(names) claims := map[string][]string{} exact := map[string]string{} - var errs []error + skipped := map[string]error{} for _, b := range names { if s.Ignored(b) { continue } name, corrected, err := s.EnvName(b) - if len(want) > 0 && !want[b] && (name == "" || !want[name]) { - continue - } if err != nil { - errs = append(errs, err) + skipped[b] = err continue } if !corrected { @@ -307,12 +367,15 @@ func (d *Deployer) Environments(ctx context.Context, s *Source, want map[string] win = bs[0] } if win == "" { - errs = append(errs, fmt.Errorf("branches %s all correct to environment %s, skipped", strings.Join(bs, ", "), name)) + err := fmt.Errorf("branches %s all correct to environment %s, skipped", strings.Join(bs, ", "), name) + for _, b := range bs { + skipped[b] = err + } continue } for _, b := range bs { if b != win { - errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name)) + skipped[b] = fmt.Errorf("branch %s collides with environment %s, skipped", b, name) } } if !isExact && s.InvalidBranches == "correct_and_warn" { @@ -320,33 +383,40 @@ func (d *Deployer) Environments(ctx context.Context, s *Source, want map[string] } envs[name] = envRef{win, all[win]} } - return envs, errs + return envs, skipped, nil } -func (d *Deployer) deploySource(ctx context.Context, s *Source, want, found map[string]bool, modules bool) error { +func (d *Deployer) planSource(ctx context.Context, s *Source) (*srcPlan, error) { fctx, end := d.phase(ctx, "source.fetch", "source", s.Name) err := d.syncMirror(fctx, d.srcMirror(s), s.Remote, nil, envRefspecs) end() if err != nil { - d.count("failed") - return err + return nil, err } bctx, end := d.phase(ctx, "source.branches", "source", s.Name) - envs, errs := d.Environments(bctx, s, want) + envs, skipped, err := d.Environments(bctx, s) end("envs", len(envs)) - for range errs { - d.count("failed") - } - if envs == nil { - return errors.Join(errs...) + return &srcPlan{s: s, envs: envs, skipped: skipped}, err +} + +func (d *Deployer) deploySource(ctx context.Context, p *srcPlan, modules bool) error { + s, full := p.s, p.want == nil + var errs []error + if full { + errs = p.skipErrs(func(string) bool { return true }) + for range errs { + d.count("failed") + } } if err := os.MkdirAll(s.Basedir, 0o755); err != nil { - return err + return errors.Join(append(errs, err)...) } var mu sync.Mutex var wg sync.WaitGroup - for name, ref := range envs { - found[name], found[ref.branch] = true, true + for name, ref := range p.envs { + if !full && !p.want[name] { + continue + } wg.Add(1) go func() { defer wg.Done() @@ -358,8 +428,8 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want, found map[ }() } wg.Wait() - if len(want) == 0 { - errs = append(errs, d.purge(s, envs)) + if full { + errs = append(errs, d.purge(s, p.envs)) } return errors.Join(errs...) } diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 1463534..68c9856 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -844,6 +844,77 @@ func TestNamedDeployTouchesOnlyNamed(t *testing.T) { } } +func TestNamedDeployCollisionLoserKeepsOut(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "a_b") + win := commit(t, f.control, map[string]string{"manifests/site.pp": "node a {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "a-b") + commit(t, f.control, map[string]string{"manifests/site.pp": "node b {}\n"}) + _ = f.deploy(false) + err := f.deploy(false, "a-b") + if !strings.HasPrefix(filepath.Base(f.env("a_b")), win+"-") { + t.Fatalf("named deploy of collision loser a-b took env a_b: %s", f.env("a_b")) + } + if err == nil || !strings.Contains(err.Error(), "a-b collides") { + t.Fatalf("want collision error for a-b, got %v", err) + } + if err := f.deploy(false, "a_b"); err != nil || !strings.HasPrefix(filepath.Base(f.env("a_b")), win+"-") { + t.Fatalf("named deploy of a_b must keep the full-deploy winner: %v", err) + } +} + +func TestNamedDeployCorrectedCollisionSkipsAll(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "branch", "a-b") + gitT(t, f.control, "branch", "a.b") + for _, arg := range []string{"a.b", "a_b"} { + err := f.deploy(false, arg) + if exists(filepath.Join(f.basedir, "a_b")) { + t.Fatalf("deploy %s built a_b, which a full deploy skips", arg) + } + if err == nil || !strings.Contains(err.Error(), "a-b") || !strings.Contains(err.Error(), "a.b") { + t.Fatalf("deploy %s: want collision error naming both branches, got %v", arg, err) + } + } +} + +func TestNamedDeployPrefixedSources(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "branch", "benvin/x") + pbase := filepath.Join(f.root, "code", "penvs") + p := &Source{Name: "p", Remote: f.control, Basedir: pbase, Prefix: "p", InvalidBranches: "correct_and_warn"} + f.cfg.Sources["p"] = p + penv := func(name string) string { return f.deployer().owned(p, filepath.Join(pbase, name)) } + if err := f.deploy(false, "main"); err != nil || f.env("main") == "" { + t.Fatalf("deploy main: %v", err) + } + if penv("p_main") != "" { + t.Fatal("env name main also deployed branch main of source p as p_main") + } + if err := f.deploy(false, "p_main"); err != nil || penv("p_main") == "" { + t.Fatalf("deploy p_main: %v", err) + } + if err := f.deploy(false, "benvin/x"); err != nil || f.env("benvin_x") == "" || penv("p_benvin_x") == "" { + t.Fatalf("raw branch benvin/x must deploy in every source: %v", err) + } +} + +func TestNamedDeployIgnoresUnrelatedInvalid(t *testing.T) { + f := newFixture(t) + f.cfg.Sources["unkin"].InvalidBranches = "error" + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "branch", "bad-name") + if err := f.deploy(false, "main"); err != nil { + t.Fatalf("unrelated invalid branch failed named deploy: %v", err) + } + if err := f.deploy(false, "bad-name"); err == nil || !strings.Contains(err.Error(), "not a valid environment name") { + t.Fatalf("named invalid branch must error: %v", err) + } +} + func timingLines(s string) []map[string]string { var out []map[string]string for line := range strings.Lines(s) { From 260dd4fc78ad236783d05bb43bdbbc3d47edec2c Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 21:06:28 +1100 Subject: [PATCH 6/6] Warn about corrected branch names only for envs being deployed --- internal/deploy/deploy.go | 9 +++++---- internal/deploy/deploy_test.go | 6 ++++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 65accc5..cc35f6e 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -378,9 +378,6 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envR skipped[b] = fmt.Errorf("branch %s collides with environment %s, skipped", b, name) } } - if !isExact && s.InvalidBranches == "correct_and_warn" { - log.Printf("warning: branch %s deployed as environment %s", win, name) - } envs[name] = envRef{win, all[win]} } return envs, skipped, nil @@ -413,10 +410,14 @@ func (d *Deployer) deploySource(ctx context.Context, p *srcPlan, modules bool) e } var mu sync.Mutex var wg sync.WaitGroup - for name, ref := range p.envs { + for _, name := range slices.Sorted(maps.Keys(p.envs)) { + ref := p.envs[name] if !full && !p.want[name] { continue } + if _, corrected, _ := s.EnvName(ref.branch); corrected && s.InvalidBranches == "correct_and_warn" { + log.Printf("warning: branch %s deployed as environment %s", ref.branch, name) + } wg.Add(1) go func() { defer wg.Done() diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 68c9856..0ec941b 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -888,9 +888,15 @@ func TestNamedDeployPrefixedSources(t *testing.T) { p := &Source{Name: "p", Remote: f.control, Basedir: pbase, Prefix: "p", InvalidBranches: "correct_and_warn"} f.cfg.Sources["p"] = p penv := func(name string) string { return f.deployer().owned(p, filepath.Join(pbase, name)) } + var logs bytes.Buffer + log.SetOutput(&logs) + defer log.SetOutput(os.Stderr) if err := f.deploy(false, "main"); err != nil || f.env("main") == "" { t.Fatalf("deploy main: %v", err) } + if strings.Contains(logs.String(), "benvin/x") { + t.Fatalf("named deploy warned about a branch it did not deploy:\n%s", logs.String()) + } if penv("p_main") != "" { t.Fatal("env name main also deployed branch main of source p as p_main") }