From 1d4b995e1ca68c964814c232ff405ac0e38c28b7 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:18:44 +1100 Subject: [PATCH 01/11] Add --timings phase logs and scope named deploys to their environments --- internal/deploy/deploy.go | 231 ++++++++++++++++++++++------- internal/deploy/forge.go | 17 ++- internal/deploy/git.go | 2 +- internal/deploy/timing.go | 74 +++++++++ internal/gentypes/generate.go | 72 +++++---- internal/gentypes/generate_test.go | 28 ++-- main.go | 60 +++++--- 7 files changed, 363 insertions(+), 121 deletions(-) create mode 100644 internal/deploy/timing.go diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 8cc92fa..e8425b4 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "log" + "log/slog" "maps" "os" "path/filepath" @@ -45,6 +46,8 @@ type Deployer struct { mu sync.Mutex flights map[string]*flight skips map[string]int + counts map[string]int + Timings *slog.Logger } type flight struct { @@ -66,9 +69,11 @@ type deployResult struct { } type resolved struct { + name string path string dir string key string + hit bool } func New(cfg *Config, jobs int, grace time.Duration) *Deployer { @@ -79,7 +84,7 @@ func New(cfg *Config, jobs int, grace time.Duration) *Deployer { if cfg.W10k.GitTimeout != nil { gt = *cfg.W10k.GitTimeout } - return &Deployer{runGit: runGit, cfg: cfg, grace: grace, gitTimeout: gt, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}, skips: map[string]int{}} + return &Deployer{runGit: runGit, cfg: cfg, grace: grace, gitTimeout: gt, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}, skips: map[string]int{}, counts: map[string]int{}} } func (d *Deployer) once(key string, fn func() (string, error)) (string, error) { @@ -98,8 +103,10 @@ func (d *Deployer) once(key string, fn func() (string, error)) (string, error) { return f.val, f.err } -func (d *Deployer) limit(fn func() error) error { +func (d *Deployer) limit(ctx context.Context, fn func() error) error { + t := time.Now() d.sem <- struct{}{} + addWait(ctx, time.Since(t)) defer func() { <-d.sem }() return fn() } @@ -136,6 +143,8 @@ func (d *Deployer) complete(worktree string) bool { // Lock takes an exclusive flock on the cachedir, released by the returned func. func (d *Deployer) Lock() (func(), error) { + _, end := d.phase(context.Background(), "lock") + defer end() if err := os.MkdirAll(d.cfg.Cachedir, 0o755); err != nil { return nil, err } @@ -159,35 +168,60 @@ 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 { - want := map[string]bool{} - for _, e := range only { - want[e] = true - } + ctx, end := d.phase(ctx, "run") 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)) { log.Printf("environment %s: %d types skipped", e, d.skips[e]) } + var summary []any + for _, k := range []string{"created", "updated", "unchanged", "failed", "removed"} { + summary = append(summary, k, d.counts[k]) + } d.mu.Unlock() + end(summary...) return errors.Join(errs...) } -func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]string, []error) { +func (d *Deployer) count(outcome string) { + d.mu.Lock() + d.counts[outcome]++ + d.mu.Unlock() +} + +// 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} @@ -204,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 @@ -220,25 +257,32 @@ 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 { - if err := d.syncMirror(ctx, d.srcMirror(s), s.Remote, envRefspecs...); err != nil { +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() + if err != nil { return err } - envs, errs := d.Environments(ctx, s) + bctx, end := d.phase(ctx, "source.branches", "source", s.Name) + 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() @@ -250,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...) @@ -282,14 +326,31 @@ func (d *Deployer) worktreePrefix(sha string) string { return sha + "-" } -func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, modules bool) error { +func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, modules bool) (err error) { + start := time.Now() + ctx, total := d.phase(ctx, "env.total", "source", s.Name, "env", name) + outcome := "unchanged" + defer func() { + if err != nil { + outcome = "failed" + } + d.count(outcome) + total("outcome", outcome) + }() link := filepath.Join(s.Basedir, name) + _, end := d.phase(ctx, "env.resolve", "sha", sha) cur := d.owned(s, link) prefix := d.worktreePrefix(sha) - if base := filepath.Base(cur); cur != "" && !modules && strings.HasPrefix(base, prefix) && len(base) == len(prefix)+12 && d.complete(cur) { + base := filepath.Base(cur) + unchanged := cur != "" && !modules && strings.HasPrefix(base, prefix) && len(base) == len(prefix)+12 && d.complete(cur) + end() + if unchanged { + d.emit(ctx, "env.skip", time.Since(start), "reason", "unchanged") return nil } - pf, checksum, err := d.puppetfile(ctx, d.srcMirror(s), sha) + pctx, end := d.phase(ctx, "env.puppetfile") + pf, checksum, err := d.puppetfile(pctx, d.srcMirror(s), sha) + end() if err != nil { return err } @@ -303,6 +364,7 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, m } target := filepath.Join(d.srcWorktrees(s), prefix+hex.EncodeToString(h.Sum(nil))[:12]) if cur == target && d.complete(cur) { + d.emit(ctx, "env.skip", time.Since(start), "reason", "modules_unchanged") return nil } skipped, err := d.once("env:"+target, func() (string, error) { @@ -313,14 +375,21 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, m if err := d.checkout(ctx, s, sha, target, mods); err != nil { return "", err } - return d.prepare(s, name, sha, checksum, target, mods, started) + return d.prepare(ctx, s, name, sha, checksum, target, mods, started) }) if err != nil { return err } - if err := Swap(target, link); err != nil { + _, end = d.phase(ctx, "env.swap") + err = Swap(target, link) + end() + if err != nil { return err } + outcome = "updated" + if cur == "" { + outcome = "created" + } if n, _ := strconv.Atoi(skipped); n > 0 { d.mu.Lock() d.skips[name] = n @@ -374,9 +443,14 @@ func (d *Deployer) installModules(ctx context.Context, pf *Puppetfile) ([]resolv func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) { key := urlKey(m.Git) mirror := d.path("git", key+".git") - if _, err := d.once("fetch:"+mirror, func() (string, error) { - return "", d.syncMirror(ctx, mirror, m.Git, modRefspecs...) - }); err != nil { + pctx, end := d.phase(ctx, "module.fetch", "module", m.Name) + fetched := false + _, err := d.once("fetch:"+mirror, func() (string, error) { + fetched = true + return "", d.syncMirror(pctx, mirror, m.Git, modRefspecs...) + }) + end("cache", cache(!fetched)) + if err != nil { return resolved{}, err } var cands []string @@ -392,37 +466,52 @@ func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) { default: cands = []string{"refs/w10k/HEAD"} } - sha, err := d.revParse(ctx, mirror, cands...) + pctx, end = d.phase(ctx, "module.resolve", "module", m.Name) + sha, err := d.revParse(pctx, mirror, cands...) + dir := d.path("modules", key, sha) + end("cache", cache(err == nil && present(dir))) if err != nil { return resolved{}, err } - dir := d.path("modules", key, sha) + pctx, end = d.phase(ctx, "module.worktree", "module", m.Name) + added := false _, err = d.once("mod:"+dir, func() (string, error) { - if _, err := os.Stat(dir); err == nil { + if present(dir) { return "", nil } + added = true tmp := dir + ".tmp" - if err := d.removeWorktree(ctx, mirror, tmp); err != nil { + if err := d.removeWorktree(pctx, mirror, tmp); err != nil { return "", err } - if _, err := d.git(ctx, mirror, "worktree", "add", "--detach", "-q", "--", tmp, sha); err != nil { + if _, err := d.git(pctx, mirror, "worktree", "add", "--detach", "-q", "--", tmp, sha); err != nil { return "", err } - _, err := d.git(ctx, mirror, "worktree", "move", "--", tmp, dir) + _, err := d.git(pctx, mirror, "worktree", "move", "--", tmp, dir) return "", err }) - return resolved{dir: dir, key: "git " + m.Git + " " + sha}, err + end("cache", cache(!added)) + return resolved{name: m.Name, dir: dir, key: "git " + m.Git + " " + sha, hit: !added}, err +} + +func present(p string) bool { + _, err := os.Stat(p) + return err == nil } func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (resolved, error) { slug := m.Owner + "-" + m.Name version := m.Version if version == "" { + pctx, end := d.phase(ctx, "module.resolve", "module", slug) + called := false v, err := d.once("latest:"+base+" "+slug, func() (string, error) { + called = true var v string - err := d.limit(func() (err error) { v, err = forgeLatest(ctx, base, slug); return err }) + err := d.limit(pctx, func() (err error) { v, err = forgeLatest(ctx, base, slug); return err }) return v, err }) + end("cache", cache(!called)) if err != nil { return resolved{}, err } @@ -430,13 +519,30 @@ func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (reso } release := slug + "-" + version dir := d.path("forge", release+"-"+shortHash(base)) + start := time.Now() + var dl, ex, wait time.Duration + installed := false _, err := d.once("forge:"+dir, func() (string, error) { - if _, err := os.Stat(dir); err == nil { + if present(dir) { return "", nil } - return "", d.limit(func() error { return forgeInstall(ctx, base, release, dir) }) + installed = true + q := time.Now() + return "", d.limit(ctx, func() error { + wait = time.Since(q) + t := time.Now() + var err error + dl, err = forgeInstall(ctx, base, release, dir) + ex = time.Since(t) - dl + return err + }) }) - return resolved{dir: dir, key: "forge " + base + " " + release}, err + if !installed { + dl = time.Since(start) + } + d.emit(ctx, "module.download", dl, "module", slug, "cache", cache(!installed), "wait", wait) + d.emit(ctx, "module.extract", ex, "module", slug, "cache", cache(!installed)) + return resolved{name: slug, dir: dir, key: "forge " + base + " " + release, hit: !installed}, err } func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string, mods []resolved) error { @@ -450,7 +556,10 @@ func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string, if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { return err } - if _, err := d.git(ctx, mirror, "worktree", "add", "--detach", "-q", "--", target, sha); err != nil { + wctx, end := d.phase(ctx, "env.worktree") + _, err := d.git(wctx, mirror, "worktree", "add", "--detach", "-q", "--", target, sha) + end() + if err != nil { return err } root, err := os.OpenRoot(target) @@ -459,7 +568,10 @@ func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string, } defer func() { _ = root.Close() }() for _, mod := range mods { - if err := linkModule(root, mod.path, mod.dir); err != nil { + _, end := d.phase(ctx, "module.link", "module", mod.name, "cache", cache(mod.hit)) + err := linkModule(root, mod.path, mod.dir) + end() + if err != nil { return err } } @@ -481,17 +593,22 @@ func linkModule(root *os.Root, rel, dir string) error { } // prepare runs last before a worktree can be swapped in; its out-of-tree done file marks the worktree complete. -func (d *Deployer) prepare(s *Source, name, sha, checksum, target string, mods []resolved, started time.Time) (string, error) { +func (d *Deployer) prepare(ctx context.Context, s *Source, name, sha, checksum, target string, mods []resolved, started time.Time) (string, error) { var skipped []error if d.cfg.W10k.GenerateTypes { - var err error - if skipped, err = gentypes.Generate(target, d.path("modules"), d.path("forge")); err != nil { + _, end := d.phase(ctx, "env.generate_types") + st, err := gentypes.Generate(target, d.path("modules"), d.path("forge")) + end("generated", st.Generated, "skipped", len(st.Skipped), "up_to_date", st.UpToDate) + if err != nil { return "", fmt.Errorf("generate types: %w", err) } + skipped = st.Skipped for _, e := range skipped { log.Printf("error: environment %s: generate types: skipped %v", name, e) } } + _, end := d.phase(ctx, "env.marker") + defer end() r := deployResult{ Name: name, Signature: sha, @@ -590,6 +707,7 @@ func (d *Deployer) purge(s *Source, envs map[string]string) error { if err := os.Remove(link); err != nil { return err } + d.count("removed") log.Printf("environment %s removed", e.Name()) } return nil @@ -614,11 +732,14 @@ func (d *Deployer) Live(s *Source) (map[string]string, error) { } type gcRun struct { - d *Deployer - ctx context.Context - marks map[string]time.Time - seen map[string]bool - errs []error + d *Deployer + ctx context.Context + marks map[string]time.Time + seen map[string]bool + errs []error + marked int + removed int + delDur time.Duration } // collect marks p on first sight and removes it only once a previous run's mark is older than the grace period. @@ -627,16 +748,21 @@ func (g *gcRun) collect(p string, remove func() error) { t, ok := g.marks[p] if !ok { g.marks[p] = g.d.now() + g.marked++ log.Printf("gc: marked %s", p) return } if g.d.now().Sub(t) < g.d.grace { return } - if err := remove(); err != nil { + rt := time.Now() + err := remove() + g.delDur += time.Since(rt) + if err != nil { g.errs = append(g.errs, err) return } + g.removed++ delete(g.marks, p) log.Printf("gc: removed %s", p) } @@ -666,6 +792,7 @@ func (g *gcRun) sweep(mirror, dir string, live map[string]bool, remove func(stri } func (d *Deployer) GC(ctx context.Context) error { + start := time.Now() 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 { @@ -727,6 +854,8 @@ func (d *Deployer) GC(ctx context.Context) error { err = os.Rename(tmp, statePath) } } + d.emit(ctx, "gc.mark", time.Since(start)-g.delDur, "marked", g.marked, "pending", len(g.marks)) + d.emit(ctx, "gc.delete", g.delDur, "removed", g.removed) return errors.Join(append(g.errs, err)...) } diff --git a/internal/deploy/forge.go b/internal/deploy/forge.go index 23696e8..7c1fb2a 100644 --- a/internal/deploy/forge.go +++ b/internal/deploy/forge.go @@ -66,24 +66,27 @@ func forgeLatest(ctx context.Context, base, slug string) (string, error) { return r.CurrentRelease.Version, nil } -func forgeInstall(ctx context.Context, base, release, dir string) error { +// forgeInstall returns the time spent reading the download, so the rest of the call is extraction. +func forgeInstall(ctx context.Context, base, release, dir string) (time.Duration, error) { + start := time.Now() body, err := forgeGet(ctx, base+"/v3/files/"+release+".tar.gz") if err != nil { - return err + return 0, err } defer func() { _ = body.Close() }() if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil { - return err + return 0, err } tmp, err := os.MkdirTemp(filepath.Dir(dir), ".tmp-") if err != nil { - return err + return 0, err } - if err := extract(body, tmp); err != nil { + tr := &timedReader{r: body, d: time.Since(start)} + if err := extract(tr, tmp); err != nil { _ = os.RemoveAll(tmp) - return fmt.Errorf("%s: %w", release, err) + return tr.d, fmt.Errorf("%s: %w", release, err) } - return os.Rename(tmp, dir) + return tr.d, os.Rename(tmp, dir) } func extract(r io.Reader, dst string) error { diff --git a/internal/deploy/git.go b/internal/deploy/git.go index 9d166b3..1384721 100644 --- a/internal/deploy/git.go +++ b/internal/deploy/git.go @@ -30,7 +30,7 @@ func runGit(ctx context.Context, dir string, args ...string) (string, error) { // git holds a -j slot only for the subprocess itself, so callers never nest slots. func (d *Deployer) git(ctx context.Context, dir string, args ...string) (out string, err error) { - err = d.limit(func() error { + err = d.limit(ctx, func() error { ctx, cancel := context.WithTimeout(ctx, d.gitTimeout) defer cancel() out, err = d.runGit(ctx, dir, args...) diff --git a/internal/deploy/timing.go b/internal/deploy/timing.go new file mode 100644 index 0000000..74cf417 --- /dev/null +++ b/internal/deploy/timing.go @@ -0,0 +1,74 @@ +package deploy + +import ( + "context" + "io" + "slices" + "sync/atomic" + "time" +) + +type spanKey struct{} + +type span struct { + parent *span + attrs []any + wait atomic.Int64 +} + +func spanOf(ctx context.Context) *span { + s, _ := ctx.Value(spanKey{}).(*span) + return s +} + +func addWait(ctx context.Context, w time.Duration) { + for s := spanOf(ctx); s != nil; s = s.parent { + s.wait.Add(int64(w)) + } +} + +// phase times one unit of work; nested phases inherit attrs, and -j slot waits are reported apart 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) {} + } + s := &span{parent: spanOf(ctx), attrs: attrs} + if s.parent != nil { + s.attrs = append(slices.Clip(s.parent.attrs), attrs...) + } + start := time.Now() + ctx = context.WithValue(ctx, spanKey{}, s) + return ctx, func(more ...any) { + d.emit(ctx, name, time.Since(start), append(more, "wait", time.Duration(s.wait.Load()).Round(time.Microsecond))...) + } +} + +func (d *Deployer) emit(ctx context.Context, name string, dur time.Duration, args ...any) { + if d.Timings == nil { + return + } + line := []any{"phase", name, "dur", dur.Round(time.Microsecond)} + if s := spanOf(ctx); s != nil { + line = append(line, s.attrs...) + } + d.Timings.Info("timing", append(line, args...)...) +} + +func cache(hit bool) string { + if hit { + return "hit" + } + return "miss" +} + +type timedReader struct { + r io.Reader + d time.Duration +} + +func (t *timedReader) Read(p []byte) (int, error) { + s := time.Now() + n, err := t.r.Read(p) + t.d += time.Since(s) + return n, err +} diff --git a/internal/gentypes/generate.go b/internal/gentypes/generate.go index e0e8b4b..c86843b 100644 --- a/internal/gentypes/generate.go +++ b/internal/gentypes/generate.go @@ -42,9 +42,14 @@ type gen struct { roots []string } +// Stats counts Generate's inputs; Skipped holds inputs that failed to parse and keep any previous output. +type Stats struct { + Generated, UpToDate int + Skipped []error +} + // Generate writes /.resource_types; every file it reads must resolve inside env or one of roots. -// Inputs that fail to parse are returned as skipped and keep any previous output. -func Generate(env string, roots ...string) (skipped []error, err error) { +func Generate(env string, roots ...string) (st Stats, err error) { g := &gen{} for i, r := range append([]string{env}, roots...) { real, err := filepath.EvalSymlinks(r) @@ -52,31 +57,31 @@ func Generate(env string, roots ...string) (skipped []error, err error) { continue } if err != nil { - return nil, err + return st, err } g.roots = append(g.roots, real) } g.env = g.roots[0] mods, err := g.modules() if err != nil { - return nil, err + return st, err } var inputs []string providers := map[string][]string{} for _, m := range mods { files, err := g.glob(filepath.Join(m, "lib", "puppet", "type")) if err != nil { - return nil, err + return st, err } inputs = append(inputs, files...) dirs, err := g.list(filepath.Join(m, "lib", "puppet", "provider")) if err != nil { - return nil, err + return st, err } for _, d := range dirs { files, err := g.glob(d) if err != nil { - return nil, err + return st, err } for _, f := range files { typ, name := filepath.Base(d), strings.TrimSuffix(filepath.Base(f), ".rb") @@ -89,7 +94,7 @@ func Generate(env string, roots ...string) (skipped []error, err error) { sort.Strings(inputs) out, err := openOut(g.env) if err != nil { - return nil, err + return st, err } defer func() { _ = out.Close() }() keep := map[string]bool{} @@ -98,32 +103,35 @@ func Generate(env string, roots ...string) (skipped []error, err error) { } dir, err := out.Open(".") if err != nil { - return nil, err + return st, err } entries, err := dir.ReadDir(-1) _ = dir.Close() if err != nil { - return nil, err + return st, err } for _, e := range entries { if !keep[e.Name()] && (e.Type().IsRegular() || e.Type()&fs.ModeSymlink != 0) { if err := out.Remove(e.Name()); err != nil { - return nil, err + return st, err } } } var errs []error for _, in := range inputs { - if err := generateOne(in, out, providers, g.mixins(mods)); err != nil { - err = fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err) - if errors.As(err, new(skipErr)) { - skipped = append(skipped, err) - } else { - errs = append(errs, err) - } + wrote, err := generateOne(in, out, providers, g.mixins(mods)) + switch { + case err == nil && wrote: + st.Generated++ + case err == nil: + st.UpToDate++ + case errors.As(err, new(skipErr)): + st.Skipped = append(st.Skipped, fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err)) + default: + errs = append(errs, fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err)) } } - return skipped, errors.Join(errs...) + return st, errors.Join(errs...) } // openOut returns an os.Root on /.resource_types, refusing anything but a real directory there. @@ -147,23 +155,23 @@ func openOut(env string) (*os.Root, error) { return root.OpenRoot(OutDir) } -func generateOne(in string, out *os.Root, providers map[string][]string, resolve Resolver) error { +func generateOne(in string, out *os.Root, providers map[string][]string, resolve Resolver) (bool, error) { ifi, err := os.Stat(in) if err != nil { - return err + return false, err } name := strings.TrimSuffix(filepath.Base(in), ".rb") dst := name + ".pp" if ofi, err := out.Lstat(dst); err == nil && ofi.Mode().IsRegular() && ofi.ModTime().Equal(ifi.ModTime()) { - return nil + return false, nil } src, err := os.ReadFile(in) if err != nil { - return err + return false, err } types, err := parseFile(string(src), resolve) if err != nil { - return unparsed(err) + return false, unparsed(err) } var t *rtype for _, c := range types { @@ -172,32 +180,32 @@ func generateOne(in string, out *os.Root, providers map[string][]string, resolve } } if t == nil { - return skipErr{fmt.Errorf("custom type %q was not defined", name)} + return false, skipErr{fmt.Errorf("custom type %q was not defined", name)} } body, err := render(t, providers[name], time.Now()) if err != nil { - return unparsed(err) + return false, unparsed(err) } tmp := "." + dst + ".tmp" if err := out.RemoveAll(tmp); err != nil { - return err + return false, err } f, err := out.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) if err != nil { - return err + return false, err } defer func() { _ = out.Remove(tmp) }() if _, err := f.WriteString(body); err != nil { _ = f.Close() - return err + return false, err } if err := f.Close(); err != nil { - return err + return false, err } if err := out.Chtimes(tmp, ifi.ModTime(), ifi.ModTime()); err != nil { - return err + return false, err } - return out.Rename(tmp, dst) + return true, out.Rename(tmp, dst) } var camel = regexp.MustCompile(`([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])`) diff --git a/internal/gentypes/generate_test.go b/internal/gentypes/generate_test.go index 77b36b3..558f5ef 100644 --- a/internal/gentypes/generate_test.go +++ b/internal/gentypes/generate_test.go @@ -327,17 +327,21 @@ func TestGenerateFiles(t *testing.T) { if err := os.Chtimes(bar, in.ModTime(), in.ModTime()); err != nil { t.Fatal(err) } - if _, err := Generate(env, cache); err != nil { + st, err := Generate(env, cache) + if err != nil { t.Fatal(err) } + if st.Generated != 0 || st.UpToDate != 2 { + t.Fatalf("unchanged inputs must count as up to date: %+v", st) + } if readFile(t, bar) != "edited" { t.Fatal("output with the input's mtime is up to date and must be kept") } if err := os.Chtimes(bar, in.ModTime(), in.ModTime().Add(-time.Hour)); err != nil { t.Fatal(err) } - if _, err := Generate(env, cache); err != nil { - t.Fatal(err) + if st, err = Generate(env, cache); err != nil || st.Generated != 1 || st.UpToDate != 1 { + t.Fatalf("got %v, %+v", err, st) } if readFile(t, bar) == "edited" { t.Fatal("output with a different mtime must be regenerated") @@ -368,9 +372,9 @@ func TestGenerateErrors(t *testing.T) { if err := os.Chtimes(filepath.Join(env, OutDir, "bad.pp"), old, old); err != nil { t.Fatal(err) } - skipped, err := Generate(env) - if err != nil || len(skipped) != 1 || !strings.Contains(skipped[0].Error(), "modules/m/lib/puppet/type/bad.rb: line 2:") { - t.Fatalf("got %v, skipped %v", err, skipped) + st, err := Generate(env) + if err != nil || len(st.Skipped) != 1 || !strings.Contains(st.Skipped[0].Error(), "modules/m/lib/puppet/type/bad.rb: line 2:") { + t.Fatalf("got %v, skipped %v", err, st.Skipped) } if !exists(filepath.Join(env, OutDir, "good.pp")) || readFile(t, filepath.Join(env, OutDir, "bad.pp")) != "previous" { t.Fatal("good inputs still generate; a failing input's old output is kept") @@ -379,22 +383,22 @@ func TestGenerateErrors(t *testing.T) { t.Run("wrong type name", func(t *testing.T) { env := t.TempDir() writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/a.rb"), strings.ReplaceAll(simpleType, "%s", "b")) - if skipped, err := Generate(env); err != nil || len(skipped) != 1 || !strings.Contains(skipped[0].Error(), `"a" was not defined`) { - t.Fatalf("got %v, skipped %v", err, skipped) + if st, err := Generate(env); err != nil || len(st.Skipped) != 1 || !strings.Contains(st.Skipped[0].Error(), `"a" was not defined`) { + t.Fatalf("got %v, skipped %v", err, st.Skipped) } }) t.Run("parser limit fails the env", func(t *testing.T) { env := t.TempDir() writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/deep.rb"), "Puppet::Type.newtype(:deep) do\nend\n"+strings.Repeat("module A\n", 300)+strings.Repeat("end\n", 300)) - if skipped, err := Generate(env); !errors.Is(err, errLimit) || len(skipped) != 0 { - t.Fatalf("got %v, skipped %v", err, skipped) + if st, err := Generate(env); !errors.Is(err, errLimit) || len(st.Skipped) != 0 { + t.Fatalf("got %v, skipped %v", err, st.Skipped) } }) t.Run("missing mixin is skipped", func(t *testing.T) { env := t.TempDir() writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/mix.rb"), "Puppet::Type.newtype(:mix) do\n include PuppetX::Nope\nend\n") - if skipped, err := Generate(env); err != nil || len(skipped) != 1 { - t.Fatalf("got %v, skipped %v", err, skipped) + if st, err := Generate(env); err != nil || len(st.Skipped) != 1 { + t.Fatalf("got %v, skipped %v", err, st.Skipped) } }) t.Run("output dir symlink", func(t *testing.T) { diff --git a/main.go b/main.go index d5f5157..6efec92 100644 --- a/main.go +++ b/main.go @@ -3,10 +3,12 @@ package main import ( "context" "fmt" + "log/slog" + "maps" "os" "os/signal" "path/filepath" - "sort" + "slices" "strings" "syscall" "time" @@ -29,6 +31,7 @@ func rootCmd() *cobra.Command { var cfgPath string var jobs int var grace time.Duration + var timings bool var root *cobra.Command load := func() (*deploy.Deployer, error) { cfg, err := deploy.LoadConfig(cfgPath) @@ -42,7 +45,29 @@ func rootCmd() *cobra.Command { if g < 0 { return nil, fmt.Errorf("--gc-grace must not be negative") } - return deploy.New(cfg, jobs, g), nil + d := deploy.New(cfg, jobs, g) + if timings { + d.Timings = slog.Default() + } + 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() @@ -65,15 +90,26 @@ func rootCmd() *cobra.Command { } root.PersistentFlags().StringVarP(&cfgPath, "config", "c", "/etc/puppetlabs/r10k/r10k.yaml", "r10k.yaml path") root.PersistentFlags().IntVarP(&jobs, "jobs", "j", 8, "maximum concurrent git/forge operations") + root.PersistentFlags().BoolVar(&timings, "timings", false, "log one timing line per deploy phase") root.PersistentFlags().DurationVar(&grace, "gc-grace", 10*time.Minute, "keep unreferenced worktrees and modules this long after a run marks them (overrides w10k.gc_grace)") 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") @@ -82,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 }, -- 2.47.3 From e7c72ed2d76ac1cac0b5c473d80192a9498e9d47 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:20:22 +1100 Subject: [PATCH 02/11] Test named deploys and timing phase keys --- internal/deploy/deploy_test.go | 72 ++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 248f841..820495a 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "log" + "log/slog" "net" "net/http" "net/http/httptest" @@ -770,3 +771,74 @@ func TestGCKeepsModulesOfRemovedSource(t *testing.T) { t.Fatalf("GC deleted a module still linked from a removed source's live env: %v", err) } } + +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 + commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()}) + var buf bytes.Buffer + d := f.deployer() + d.Timings = slog.New(slog.NewTextHandler(&buf, nil)) + unlock, err := d.Lock() + if err != nil { + t.Fatal(err) + } + unlock() + for range 2 { + if err := d.Deploy(context.Background(), nil, false); err != nil { + t.Fatal(err) + } + } + out := buf.String() + for _, want := range []string{ + "phase=lock ", "phase=source.fetch ", "phase=source.branches ", "phase=env.resolve ", "phase=env.puppetfile ", + "phase=module.resolve ", "phase=module.fetch ", "phase=module.worktree ", "phase=module.download ", "phase=module.extract ", + "phase=module.link ", "phase=env.worktree ", "phase=env.generate_types ", "phase=env.marker ", "phase=env.swap ", + "phase=env.total ", "phase=env.skip ", "reason=unchanged", "phase=gc.mark ", "phase=gc.delete ", "phase=run ", + " dur=", " wait=", " source=unkin", " env=main", " module=bind", " module=acme-thing", " cache=hit", " cache=miss", + " generated=", " up_to_date=", " skipped=", " marked=", " removed=", " created=1", " updated=", " unchanged=1", " failed=", + } { + if !strings.Contains(out, want) { + t.Errorf("timings lack %q", want) + } + } + if t.Failed() { + t.Log(out) + } +} -- 2.47.3 From dd1421f77ce49b2fd42ee2816e0a05e4dfc873e2 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:30:31 +1100 Subject: [PATCH 03/11] Drop named-deploy scoping and env completion --- internal/deploy/deploy.go | 53 ++++++++++++---------------------- internal/deploy/deploy_test.go | 36 ----------------------- main.go | 51 +++++++++++--------------------- 3 files changed, 35 insertions(+), 105 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index e8425b4..fb37708 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -168,29 +168,27 @@ 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, only, found, modules); err != nil { + if err := d.deploySource(ctx, s, want, modules); err != nil { errs = append(errs, fmt.Errorf("source %s: %w", s.Name, err)) } } - for _, e := range only { - if !found[e] { - errs = append(errs, fmt.Errorf("environment %s not found", e)) - } + for e := range want { + errs = append(errs, fmt.Errorf("environment %s not found", e)) } - if len(only) == 0 { - if err := d.GC(ctx); err != nil { - errs = append(errs, err) - } + if err := d.GC(ctx); err != nil { + errs = append(errs, err) } d.mu.Lock() for _, e := range slices.Sorted(maps.Keys(d.skips)) { @@ -211,17 +209,7 @@ func (d *Deployer) count(outcome string) { d.mu.Unlock() } -// 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) }) - } +func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]string, []error) { all, err := d.branches(ctx, d.srcMirror(s)) if err != nil { return nil, []error{err} @@ -238,9 +226,6 @@ func (d *Deployer) Environments(ctx context.Context, s *Source, only ...string) continue } name, corrected, err := s.EnvName(b) - if !wanted(b, name) { - continue - } if err != nil { errs = append(errs, err) continue @@ -257,7 +242,7 @@ func (d *Deployer) Environments(ctx context.Context, s *Source, only ...string) return envs, errs } -func (d *Deployer) deploySource(ctx context.Context, s *Source, only []string, found map[string]bool, modules bool) error { +func (d *Deployer) deploySource(ctx context.Context, s *Source, want 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() @@ -265,24 +250,22 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, only []string, f return err } bctx, end := d.phase(ctx, "source.branches", "source", s.Name) - envs, errs := d.Environments(bctx, s, only...) + envs, errs := d.Environments(bctx, s) end("envs", len(envs)) if envs == nil { return errors.Join(errs...) } - for name := range envs { - for _, a := range only { - if s.Matches(a, name) { - found[a] = true - } - } - } + full := len(want) == 0 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() @@ -294,7 +277,7 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, only []string, f }() } wg.Wait() - if len(only) == 0 { + if full { 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 820495a..c7e03dc 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -772,42 +772,6 @@ 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 6efec92..18f7850 100644 --- a/main.go +++ b/main.go @@ -4,11 +4,10 @@ import ( "context" "fmt" "log/slog" - "maps" "os" "os/signal" "path/filepath" - "slices" + "sort" "strings" "syscall" "time" @@ -51,24 +50,6 @@ 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 { @@ -96,20 +77,10 @@ func rootCmd() *cobra.Command { var modules bool deployCmd := &cobra.Command{ Use: "deploy [env...]", - Short: "Deploy all environments, or only the named ones (env or branch names)", + Short: "Deploy all environments, or only the named ones", 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") @@ -118,12 +89,24 @@ func rootCmd() *cobra.Command { Short: "List deployed environments", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - rows, err := live() + d, err := load() if err != nil { return err } - for _, r := range rows { - _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\n", r[0], r[1], r[2]) + 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) + } } return nil }, -- 2.47.3 From 55224fd9f79623ea837223efd5cb85c9d6a25e54 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:30:31 +1100 Subject: [PATCH 04/11] Report wait on leaf phases only and include it in module.download --- internal/deploy/deploy.go | 5 ++-- internal/deploy/deploy_test.go | 54 ++++++++++++++++++++++++++++++++++ internal/deploy/timing.go | 11 +++++-- 3 files changed, 65 insertions(+), 5 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index fb37708..6e3d49d 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -452,7 +452,7 @@ func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) { pctx, end = d.phase(ctx, "module.resolve", "module", m.Name) sha, err := d.revParse(pctx, mirror, cands...) dir := d.path("modules", key, sha) - end("cache", cache(err == nil && present(dir))) + end("cache", cache(d.Timings != nil && err == nil && present(dir))) if err != nil { return resolved{}, err } @@ -517,13 +517,14 @@ func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (reso var err error dl, err = forgeInstall(ctx, base, release, dir) ex = time.Since(t) - dl + dl += wait return err }) }) if !installed { dl = time.Since(start) } - d.emit(ctx, "module.download", dl, "module", slug, "cache", cache(!installed), "wait", wait) + d.emit(ctx, "module.download", dl, "module", slug, "cache", cache(!installed), "wait", wait.Round(time.Microsecond)) d.emit(ctx, "module.extract", ex, "module", slug, "cache", cache(!installed)) return resolved{name: slug, dir: dir, key: "forge " + base + " " + release, hit: !installed}, err } diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index c7e03dc..77d8ba7 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -806,3 +806,57 @@ func TestTimingsPhases(t *testing.T) { t.Log(out) } } + +func TestTimingsWaitWithinDur(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()}) + for _, b := range []string{"a", "b", "c", "d", "e", "f", "g", "h"} { + gitT(t, f.control, "branch", b) + } + var buf bytes.Buffer + d := New(f.cfg, 1, 10*time.Minute) + d.Timings = slog.New(slog.NewTextHandler(&buf, nil)) + if err := d.Deploy(context.Background(), nil, false); err != nil { + t.Fatal(err) + } + waits := 0 + for line := range strings.Lines(buf.String()) { + kv := map[string]string{} + for _, f := range strings.Fields(line) { + k, v, _ := strings.Cut(f, "=") + kv[k] = v + } + if kv["phase"] == "run" || kv["phase"] == "env.total" { + if _, ok := kv["wait"]; ok { + t.Errorf("aggregate phase reports wait: %s", line) + } + } + w, ok := kv["wait"] + if !ok { + continue + } + waits++ + wd, err1 := time.ParseDuration(w) + dd, err2 := time.ParseDuration(kv["dur"]) + if err1 != nil || err2 != nil || wd > dd { + t.Errorf("wait must not exceed dur: %s", line) + } + } + if waits == 0 { + t.Fatalf("no wait reported:\n%s", buf.String()) + } +} + +func TestTimingsOffEmitsNothing(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()}) + var buf bytes.Buffer + prev := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&buf, nil))) + defer slog.SetDefault(prev) + f.mustDeploy(false) + f.mustDeploy(false) + if strings.Contains(buf.String(), "phase=") { + t.Fatalf("timings off must emit nothing:\n%s", buf.String()) + } +} diff --git a/internal/deploy/timing.go b/internal/deploy/timing.go index 74cf417..dcf7868 100644 --- a/internal/deploy/timing.go +++ b/internal/deploy/timing.go @@ -14,6 +14,7 @@ type span struct { parent *span attrs []any wait atomic.Int64 + kids atomic.Bool } func spanOf(ctx context.Context) *span { @@ -22,24 +23,28 @@ func spanOf(ctx context.Context) *span { } func addWait(ctx context.Context, w time.Duration) { - for s := spanOf(ctx); s != nil; s = s.parent { + if s := spanOf(ctx); s != nil { s.wait.Add(int64(w)) } } -// phase times one unit of work; nested phases inherit attrs, and -j slot waits are reported apart as wait. +// phase times one unit of work; nested phases inherit attrs, and leaf phases report their -j slot 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) {} } s := &span{parent: spanOf(ctx), attrs: attrs} if s.parent != nil { + s.parent.kids.Store(true) s.attrs = append(slices.Clip(s.parent.attrs), attrs...) } start := time.Now() ctx = context.WithValue(ctx, spanKey{}, s) return ctx, func(more ...any) { - d.emit(ctx, name, time.Since(start), append(more, "wait", time.Duration(s.wait.Load()).Round(time.Microsecond))...) + if !s.kids.Load() { + more = append(more, "wait", time.Duration(s.wait.Load()).Round(time.Microsecond)) + } + d.emit(ctx, name, time.Since(start), more...) } } -- 2.47.3 From cee4a1fb8d5295023cb023d205969bd3a7983c1b Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:31:06 +1100 Subject: [PATCH 05/11] 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 }, -- 2.47.3 From 7d457a89cf962896464759600debfe503ead9276 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:32:25 +1100 Subject: [PATCH 06/11] 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 -- 2.47.3 From 4edc42329c817e23b9841f847589d3b912eba8fe Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 21:02:23 +1100 Subject: [PATCH 07/11] Label waiters on in-flight work cache=shared and count panics as failed - report cache=shared for callers that waited on another's once work - drop the git module.resolve cache label - recover deployEnv panics before its outcome is recorded - count source fetch and branch errors as failed --- internal/deploy/deploy.go | 111 ++++++++++++----------- internal/deploy/deploy_test.go | 160 ++++++++++++++++++++++++++++----- internal/deploy/timing.go | 7 -- 3 files changed, 197 insertions(+), 81 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index f9b94d7..a424622 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -57,9 +57,10 @@ type Deployer struct { } type flight struct { - done chan struct{} - val string - err error + done chan struct{} + val string + worked bool + err error } type deployResult struct { @@ -75,11 +76,11 @@ type deployResult struct { } type resolved struct { - name string - path string - dir string - key string - hit bool + name string + path string + dir string + key string + cache string } func New(cfg *Config, jobs int, grace time.Duration) *Deployer { @@ -93,11 +94,12 @@ func New(cfg *Config, jobs int, grace time.Duration) *Deployer { return &Deployer{runGit: runGit, cfg: cfg, grace: grace, gitTimeout: gt, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}, skips: map[string]int{}, counts: map[string]int{}} } -func (d *Deployer) once(key string, fn func() (string, error)) (string, error) { +// once runs fn once per key; cache is miss for the caller that did the work, shared for callers that waited on it, hit when fn found it already done. +func (d *Deployer) once(key string, fn func() (string, bool, error)) (string, string, error) { d.mu.Lock() f, ok := d.flights[key] if !ok { - f = &flight{done: make(chan struct{})} + f = &flight{done: make(chan struct{}), worked: true} d.flights[key] = f } d.mu.Unlock() @@ -105,11 +107,17 @@ func (d *Deployer) once(key string, fn func() (string, error)) (string, error) { func() { defer close(f.done) defer recoverErr(&f.err, key) - f.val, f.err = fn() + f.val, f.worked, f.err = fn() }() } <-f.done - return f.val, f.err + switch { + case !f.worked: + return f.val, "hit", f.err + case ok: + return f.val, "shared", f.err + } + return f.val, "miss", f.err } func (d *Deployer) limit(ctx context.Context, fn func() error) error { @@ -221,6 +229,7 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro want[e] = true } d.mu.Lock() + clear(d.flights) clear(d.skips) clear(d.counts) d.mu.Unlock() @@ -298,11 +307,15 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want, found map[ err := d.syncMirror(fctx, d.srcMirror(s), s.Remote, nil, envRefspecs) end() if err != nil { + d.count("failed") return err } bctx, end := d.phase(ctx, "source.branches", "source", s.Name) envs, errs := d.Environments(bctx, s) end("envs", len(envs)) + for range errs { + d.count("failed") + } if envs == nil { return errors.Join(errs...) } @@ -320,11 +333,7 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want, found map[ wg.Add(1) go func() { defer wg.Done() - err := func() (err error) { - defer recoverErr(&err, "environment "+name) - return d.deployEnv(ctx, s, name, ref, modules) - }() - if err != nil { + if err := d.deployEnv(ctx, s, name, ref, modules); err != nil { mu.Lock() errs = append(errs, fmt.Errorf("environment %s: %w", name, err)) mu.Unlock() @@ -376,6 +385,7 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name string, ref en d.count(outcome) total("outcome", outcome) }() + defer recoverErr(&err, "environment "+name) link := filepath.Join(s.Basedir, name) _, end := d.phase(ctx, "env.resolve", "sha", sha) cur := d.owned(s, link) @@ -406,15 +416,16 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name string, ref en d.emit(ctx, "env.skip", time.Since(start), "reason", "modules_unchanged") return nil } - skipped, err := d.once("env:"+target, func() (string, error) { + skipped, _, err := d.once("env:"+target, func() (string, bool, error) { if d.complete(target) { - return "", nil + return "", false, nil } started := d.now().UTC() if err := d.checkout(ctx, s, sha, target, mods); err != nil { - return "", err + return "", true, err } - return d.prepare(ctx, s, name, ref, checksum, target, mods, started) + v, err := d.prepare(ctx, s, name, ref, checksum, target, mods, started) + return v, true, err }) if err != nil { return err @@ -486,12 +497,10 @@ func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) { key := urlKey(m.Git) mirror := d.path("git", key+".git") pctx, end := d.phase(ctx, "module.fetch", "module", m.Name) - fetched := false - _, err := d.once("fetch:"+mirror, func() (string, error) { - fetched = true - return "", d.syncMirror(pctx, mirror, m.Git, modFetchOpts, modRefspecs) + _, c, err := d.once("fetch:"+mirror, func() (string, bool, error) { + return "", true, d.syncMirror(pctx, mirror, m.Git, modFetchOpts, modRefspecs) }) - end("cache", cache(!fetched)) + end("cache", c) if err != nil { return resolved{}, err } @@ -511,33 +520,31 @@ func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) { pctx, end = d.phase(ctx, "module.resolve", "module", m.Name) sha, err := d.revParse(pctx, mirror, cands...) dir := d.path("modules", key, sha) - end("cache", cache(d.Timings != nil && err == nil && d.complete(dir))) + end() if err != nil { return resolved{}, err } pctx, end = d.phase(ctx, "module.worktree", "module", m.Name) - added := false - _, err = d.once("mod:"+dir, func() (string, error) { + _, c, err = d.once("mod:"+dir, func() (string, bool, error) { if d.complete(dir) { - return "", nil + return "", false, nil } - added = true tmp := dir + ".tmp" for _, p := range []string{tmp, dir} { if err := d.removeWorktree(pctx, mirror, p); err != nil { - return "", err + return "", true, err } } if _, err := d.git(pctx, mirror, "worktree", "add", "--detach", "-q", "--", tmp, sha); err != nil { - return "", err + return "", true, err } if _, err := d.git(pctx, mirror, "worktree", "move", "--", tmp, dir); err != nil { - return "", err + return "", true, err } - return "", d.markDone(dir, nil) + return "", true, d.markDone(dir, nil) }) - end("cache", cache(!added)) - return resolved{name: m.Name, dir: dir, key: "git " + m.Git + " " + sha, hit: !added}, err + end("cache", c) + return resolved{name: m.Name, dir: dir, key: "git " + m.Git + " " + sha, cache: c}, err } func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (resolved, error) { @@ -545,14 +552,12 @@ func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (reso version := m.Version if version == "" { pctx, end := d.phase(ctx, "module.resolve", "module", slug) - called := false - v, err := d.once("latest:"+base+" "+slug, func() (string, error) { - called = true + v, c, err := d.once("latest:"+base+" "+slug, func() (string, bool, error) { var v string err := d.limit(pctx, func() (err error) { v, err = forgeLatest(ctx, base, slug); return err }) - return v, err + return v, true, err }) - end("cache", cache(!called)) + end("cache", c) if err != nil { return resolved{}, err } @@ -562,14 +567,12 @@ func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (reso dir := d.path("forge", release+"-"+shortHash(base)) start := time.Now() var dl, ex, wait time.Duration - installed := false - _, err := d.once("forge:"+dir, func() (string, error) { + _, c, err := d.once("forge:"+dir, func() (string, bool, error) { if d.complete(dir) { - return "", nil + return "", false, nil } - installed = true if err := os.RemoveAll(dir); err != nil { - return "", err + return "", true, err } q := time.Now() if err := d.limit(ctx, func() error { @@ -581,16 +584,16 @@ func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (reso dl += wait return err }); err != nil { - return "", err + return "", true, err } - return "", d.markDone(dir, nil) + return "", true, d.markDone(dir, nil) }) - if !installed { + if c != "miss" { dl = time.Since(start) } - d.emit(ctx, "module.download", dl, "module", slug, "cache", cache(!installed), "wait", wait.Round(time.Microsecond)) - d.emit(ctx, "module.extract", ex, "module", slug, "cache", cache(!installed)) - return resolved{name: slug, dir: dir, key: "forge " + base + " " + release, hit: !installed}, err + d.emit(ctx, "module.download", dl, "module", slug, "cache", c, "wait", wait.Round(time.Microsecond)) + d.emit(ctx, "module.extract", ex, "module", slug, "cache", c) + return resolved{name: slug, dir: dir, key: "forge " + base + " " + release, cache: c}, err } func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string, mods []resolved) error { @@ -616,7 +619,7 @@ func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string, } defer func() { _ = root.Close() }() for _, mod := range mods { - _, end := d.phase(ctx, "module.link", "module", mod.name, "cache", cache(mod.hit)) + _, end := d.phase(ctx, "module.link", "module", mod.name, "cache", mod.cache) err := linkModule(root, mod.path, mod.dir) end() if err != nil { diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 03c3dac..f9e6e09 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/cgi" @@ -14,6 +15,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "sync" "testing" @@ -793,6 +795,19 @@ func TestGCKeepsModulesOfRemovedSource(t *testing.T) { } } +func timingLines(s string) []map[string]string { + var out []map[string]string + for line := range strings.Lines(s) { + kv := map[string]string{} + for _, f := range strings.Fields(line) { + k, v, _ := strings.Cut(f, "=") + kv[k] = v + } + out = append(out, kv) + } + return out +} + func TestTimingsPhases(t *testing.T) { f := newFixture(t) f.cfg.W10k.GenerateTypes = true @@ -805,18 +820,51 @@ func TestTimingsPhases(t *testing.T) { t.Fatal(err) } unlock() - for range 2 { - if err := d.Deploy(context.Background(), nil, false); err != nil { + src := map[string]string{"source.fetch": "", "source.branches": "", "env.resolve": "", "gc.mark": "", "gc.delete": "", "run": ""} + with := func(m map[string]string) map[string]string { + for k, v := range src { + m[k] = v + } + return m + } + runs := []struct { + modules bool + want map[string]string + }{ + {false, with(map[string]string{ + "lock": "", "env.puppetfile": "", "module.resolve": ",,miss", "module.fetch": "miss,shared", "module.worktree": "miss,shared", + "module.download": "miss,miss", "module.extract": "miss,miss", "module.link": "miss,miss,miss,shared", + "env.worktree": "", "env.generate_types": "", "env.marker": "", "env.swap": "", "env.total": "created", + })}, + {false, with(map[string]string{"env.skip": "unchanged", "env.total": "unchanged"})}, + {true, with(map[string]string{ + "env.puppetfile": "", "module.resolve": ",,miss", "module.fetch": "miss,shared", "module.worktree": "hit,hit", + "module.download": "hit,hit", "module.extract": "hit,hit", "env.skip": "modules_unchanged", "env.total": "unchanged", + })}, + } + var all strings.Builder + for i, r := range runs { + if err := d.Deploy(context.Background(), nil, r.modules); err != nil { t.Fatal(err) } + labels := map[string][]string{} + for _, kv := range timingLines(buf.String()) { + labels[kv["phase"]] = append(labels[kv["phase"]], kv["cache"]+kv["outcome"]+kv["reason"]) + } + got := map[string]string{} + for k, v := range labels { + slices.Sort(v) + got[k] = strings.Join(v, ",") + } + if !maps.Equal(got, r.want) { + t.Errorf("run %d labels:\n got %v\nwant %v", i, got, r.want) + } + all.WriteString(buf.String()) + buf.Reset() } - out := buf.String() + out := all.String() for _, want := range []string{ - "phase=lock ", "phase=source.fetch ", "phase=source.branches ", "phase=env.resolve ", "phase=env.puppetfile ", - "phase=module.resolve ", "phase=module.fetch ", "phase=module.worktree ", "phase=module.download ", "phase=module.extract ", - "phase=module.link ", "phase=env.worktree ", "phase=env.generate_types ", "phase=env.marker ", "phase=env.swap ", - "phase=env.total ", "phase=env.skip ", "reason=unchanged", "phase=gc.mark ", "phase=gc.delete ", "phase=run ", - " dur=", " wait=", " source=unkin", " env=main", " module=bind", " module=acme-thing", " cache=hit", " cache=miss", + " dur=", " wait=", " source=unkin", " env=main", " module=bind", " module=acme-thing", " generated=", " up_to_date=", " skipped=", " marked=", " removed=", " created=1", " updated=", " unchanged=1", " failed=", } { if !strings.Contains(out, want) { @@ -828,6 +876,51 @@ func TestTimingsPhases(t *testing.T) { } } +func TestTimingsColdCacheHasNoHits(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()}) + 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) + } + for _, kv := range timingLines(buf.String()) { + if kv["cache"] == "hit" { + t.Errorf("cold cachedir reports %s module=%s cache=hit dur=%s", kv["phase"], kv["module"], kv["dur"]) + } + } +} + +func TestTimingsCacheLabels(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()}) + for run, want := range []string{"miss", "hit"} { + var buf bytes.Buffer + d := f.deployer() + d.Timings = slog.New(slog.NewTextHandler(&buf, nil)) + if err := d.Deploy(context.Background(), nil, true); err != nil { + t.Fatal(err) + } + misses := 0 + for _, kv := range timingLines(buf.String()) { + switch kv["phase"] { + case "module.download": + if kv["module"] == "acme-thing" && kv["cache"] != want { + t.Errorf("run %d: acme-thing download cache=%s, want %s", run, kv["cache"], want) + } + case "module.worktree": + if kv["cache"] == "miss" { + misses++ + } + } + } + if (run == 0) != (misses > 0) { + t.Errorf("run %d: module.worktree misses=%d", run, misses) + } + } +} + func TestTimingsWaitWithinDur(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()}) @@ -840,31 +933,28 @@ func TestTimingsWaitWithinDur(t *testing.T) { if err := d.Deploy(context.Background(), nil, false); err != nil { t.Fatal(err) } - waits := 0 - for line := range strings.Lines(buf.String()) { - kv := map[string]string{} - for _, f := range strings.Fields(line) { - k, v, _ := strings.Cut(f, "=") - kv[k] = v - } + contended := false + for _, kv := range timingLines(buf.String()) { if kv["phase"] == "run" || kv["phase"] == "env.total" { if _, ok := kv["wait"]; ok { - t.Errorf("aggregate phase reports wait: %s", line) + t.Errorf("aggregate phase reports wait: %v", kv) } } w, ok := kv["wait"] if !ok { continue } - waits++ wd, err1 := time.ParseDuration(w) dd, err2 := time.ParseDuration(kv["dur"]) if err1 != nil || err2 != nil || wd > dd { - t.Errorf("wait must not exceed dur: %s", line) + t.Errorf("wait must not exceed dur: %v", kv) + } + if wd > 0 && kv["phase"] != "module.download" { + contended = true } } - if waits == 0 { - t.Fatalf("no wait reported:\n%s", buf.String()) + if !contended { + t.Fatalf("-j1 with 9 envs reports no wait on any phase() leaf:\n%s", buf.String()) } } @@ -993,10 +1083,20 @@ func TestPanicFailsOnlyItsEnv(t *testing.T) { } return runGit(ctx, dir, args...) } + var buf bytes.Buffer + d.Timings = slog.New(slog.NewTextHandler(&buf, nil)) err := d.Deploy(context.Background(), nil, false) if err == nil || !strings.Contains(err.Error(), "environment bad: panic: boom") { t.Fatalf("panic not reported as env error: %v", err) } + for _, kv := range timingLines(buf.String()) { + if kv["phase"] == "env.total" && kv["env"] == "bad" && kv["outcome"] != "failed" { + t.Errorf("panicking env outcome=%s, want failed", kv["outcome"]) + } + } + if !strings.Contains(buf.String(), " created=1 updated=0 unchanged=0 failed=1 ") { + t.Errorf("summary must count the panic as failed:\n%s", buf.String()) + } if f.env("main") == "" || f.env("bad") != "" { t.Fatalf("main=%q bad=%q", f.env("main"), f.env("bad")) } @@ -1005,6 +1105,26 @@ func TestPanicFailsOnlyItsEnv(t *testing.T) { } } +func TestSourceErrorsCountFailed(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "\n"}) + gitT(t, f.control, "branch", "bad-name") + cfg, err := ParseConfig(fmt.Appendf(nil, "cachedir: %s\nsources:\n unkin:\n remote: %s\n basedir: %s\n invalid_branches: error\n gone:\n remote: %s\n basedir: %s\n", + f.cfg.Cachedir, f.control, f.basedir, filepath.Join(f.root, "missing"), filepath.Join(f.root, "gone-envs"))) + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + d := New(cfg, 4, 10*time.Minute) + d.Timings = slog.New(slog.NewTextHandler(&buf, nil)) + if err := d.Deploy(context.Background(), nil, false); err == nil { + t.Fatal("source errors not returned") + } + if !strings.Contains(buf.String(), " created=1 updated=0 unchanged=0 failed=2 ") { + t.Errorf("summary must count the fetch and branch errors as failed:\n%s", buf.String()) + } +} + func TestConcurrentWorktreeAddsOneMirror(t *testing.T) { f := newFixture(t) for i := range 40 { diff --git a/internal/deploy/timing.go b/internal/deploy/timing.go index dcf7868..7d51f5e 100644 --- a/internal/deploy/timing.go +++ b/internal/deploy/timing.go @@ -59,13 +59,6 @@ func (d *Deployer) emit(ctx context.Context, name string, dur time.Duration, arg d.Timings.Info("timing", append(line, args...)...) } -func cache(hit bool) string { - if hit { - return "hit" - } - return "miss" -} - type timedReader struct { r io.Reader d time.Duration -- 2.47.3 From 503db52306a797cf599f1d585dbea935793ed653 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 21:04:45 +1100 Subject: [PATCH 08/11] 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) { -- 2.47.3 From 260dd4fc78ad236783d05bb43bdbbc3d47edec2c Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 21:06:28 +1100 Subject: [PATCH 09/11] 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") } -- 2.47.3 From d7369850db8cb3b3627518bbf1dcb8d9b23035f2 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 21:40:33 +1100 Subject: [PATCH 10/11] Keep in-flight work across concurrent Deploys --- internal/deploy/deploy.go | 9 ++++++++- internal/deploy/deploy_test.go | 37 ++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 467ee3f..5b73773 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -229,7 +229,14 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro want[e] = true } 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 c9e8ef1..fd43dc6 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" ) @@ -1364,3 +1366,38 @@ func TestCorrectedBranchCollisionSkipsAll(t *testing.T) { t.Fatal("collision must not block other envs") } } + +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) + } +} -- 2.47.3 From 11b89d6d5d7146525b138bb2769af6124e906fac Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 21:43:22 +1100 Subject: [PATCH 11/11] Count worktree lock waits and assert timing counts, labels and --timings --- internal/deploy/deploy_test.go | 92 ++++++++++++++++++++++++++++++++++ internal/deploy/git.go | 4 +- internal/deploy/timing.go | 2 +- main_test.go | 38 ++++++++++++++ 4 files changed, 134 insertions(+), 2 deletions(-) create mode 100644 main_test.go diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index fd43dc6..e09e9c7 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -852,6 +852,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 { @@ -1401,3 +1404,92 @@ func TestConcurrentDeploySharesInFlightFetch(t *testing.T) { 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 new file mode 100644 index 0000000..a55a3b7 --- /dev/null +++ b/main_test.go @@ -0,0 +1,38 @@ +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()) + } + } +} -- 2.47.3