Keep GC off targeted deploys, always drop live marks, let exact branches win env names
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful

This commit is contained in:
2026-11-08 20:54:57 +11:00
parent e73f3c8e1f
commit 66580c9b37
2 changed files with 226 additions and 31 deletions
+80 -31
View File
@@ -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.
+146
View File
@@ -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")
}
}