| 1 | // Package checksfix dispatches runs to fix the required checks the valley |
| 2 | // host's check worker failed on ready changes klaus owns, as the pipeline |
| 3 | // dispatches a fix agent for a PR's failing CI. |
| 4 | package checksfix |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "regexp" |
| 14 | "slices" |
| 15 | "sort" |
| 16 | "strings" |
| 17 | "syscall" |
| 18 | "time" |
| 19 | |
| 20 | "the-valley/flow/internal/integration" |
| 21 | "the-valley/flow/internal/restack" |
| 22 | "the-valley/flow/internal/valley" |
| 23 | ) |
| 24 | |
| 25 | // LedgerFile is the ledger's file name in a session directory. |
| 26 | const LedgerFile = "checks-dispatches.json" |
| 27 | |
| 28 | // MaxAttempts is how many fix runs klaus dispatches for a change before it |
| 29 | // stops, as the pipeline's maxFixAttempts is for a PR's CI. Checks passing |
| 30 | // start the count over. |
| 31 | const MaxAttempts = 3 |
| 32 | |
| 33 | // maxHeads is how many of a change's failed heads the ledger remembers. |
| 34 | const maxHeads = 16 |
| 35 | |
| 36 | // Entry is what klaus did about one change's failed checks. |
| 37 | type Entry struct { |
| 38 | Repo string `json:"repo"` |
| 39 | ChangeID string `json:"change_id"` |
| 40 | Handle string `json:"handle"` |
| 41 | // Heads are the failed heads klaus acted on, latest last: each is |
| 42 | // acted on once, whatever came of it. |
| 43 | Heads []string `json:"heads"` |
| 44 | // Attempts counts the fix runs that left the change's next version |
| 45 | // still failing. |
| 46 | Attempts int `json:"attempts"` |
| 47 | // RunID, Head and At are the latest dispatch's run, the head it was |
| 48 | // for, and when. RunID is cleared when checks pass. |
| 49 | RunID string `json:"run_id,omitempty"` |
| 50 | Head string `json:"head,omitempty"` |
| 51 | At string `json:"at,omitempty"` |
| 52 | // Stopped is set once the attempts are spent, until checks pass. |
| 53 | Stopped bool `json:"stopped,omitempty"` |
| 54 | // Error is why the latest launch failed, if it did. |
| 55 | Error string `json:"error,omitempty"` |
| 56 | } |
| 57 | |
| 58 | // Ledger is the session's record of fix dispatches, keyed by repo and |
| 59 | // change ID. |
| 60 | type Ledger struct { |
| 61 | path string |
| 62 | entries map[string]*Entry |
| 63 | } |
| 64 | |
| 65 | // LoadLedger reads the ledger in the session directory dir; a missing file |
| 66 | // is an empty ledger. |
| 67 | func LoadLedger(dir string) (*Ledger, error) { |
| 68 | l := &Ledger{path: filepath.Join(dir, LedgerFile), entries: make(map[string]*Entry)} |
| 69 | data, err := os.ReadFile(l.path) |
| 70 | if errors.Is(err, os.ErrNotExist) { |
| 71 | return l, nil |
| 72 | } |
| 73 | if err != nil { |
| 74 | return l, err |
| 75 | } |
| 76 | if err := json.Unmarshal(data, &l.entries); err != nil { |
| 77 | return l, fmt.Errorf("parsing %s: %w", l.path, err) |
| 78 | } |
| 79 | return l, nil |
| 80 | } |
| 81 | |
| 82 | // Entry returns the ledger's entry for change id in repo, or nil. |
| 83 | func (l *Ledger) Entry(repo, id string) *Entry { return l.entries[repo+"/"+id] } |
| 84 | |
| 85 | // Lock takes the ledger's lock in the session directory dir, which a |
| 86 | // pass that acts holds from reading the ledger to saving it. |
| 87 | func Lock(dir string) (unlock func(), err error) { |
| 88 | f, err := os.OpenFile(filepath.Join(dir, LedgerFile+".lock"), os.O_CREATE|os.O_RDWR, 0o644) |
| 89 | if err != nil { |
| 90 | return nil, err |
| 91 | } |
| 92 | if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { |
| 93 | f.Close() |
| 94 | return nil, fmt.Errorf("locking %s: %w", f.Name(), err) |
| 95 | } |
| 96 | return func() { |
| 97 | syscall.Flock(int(f.Fd()), syscall.LOCK_UN) //nolint:errcheck |
| 98 | f.Close() |
| 99 | }, nil |
| 100 | } |
| 101 | |
| 102 | // save writes the ledger through a temporary file, so a crash mid-write |
| 103 | // leaves the previous one in place. |
| 104 | func (l *Ledger) save() error { |
| 105 | data, err := json.MarshalIndent(l.entries, "", " ") |
| 106 | if err != nil { |
| 107 | return err |
| 108 | } |
| 109 | f, err := os.CreateTemp(filepath.Dir(l.path), ".checks-dispatches-*") |
| 110 | if err != nil { |
| 111 | return err |
| 112 | } |
| 113 | defer os.Remove(f.Name()) |
| 114 | if _, err := f.Write(append(data, '\n')); err != nil { |
| 115 | f.Close() |
| 116 | return err |
| 117 | } |
| 118 | if err := f.Close(); err != nil { |
| 119 | return err |
| 120 | } |
| 121 | return os.Rename(f.Name(), l.path) |
| 122 | } |
| 123 | |
| 124 | // Launch is a fix run to launch, in Dir: klaus launch [--repo Project] |
| 125 | // --change ChangeID --run-id RunID --expect-owner Owner --expect-branch |
| 126 | // Branch --expect-head Head --reason checks-failed Prompt. |
| 127 | type Launch struct { |
| 128 | Dir, Project, ChangeID, Prompt string |
| 129 | RunID string |
| 130 | Owner, Branch, Head string |
| 131 | } |
| 132 | |
| 133 | // Deps are what a pass reads and does. |
| 134 | type Deps struct { |
| 135 | List func(ctx context.Context, dir string) (*valley.Changes, error) |
| 136 | Principal func(ctx context.Context, dir string) string |
| 137 | NewRunID func() (string, error) |
| 138 | Launch func(ctx context.Context, l Launch) error |
| 139 | // Running reports whether a run, in any session, is working on the |
| 140 | // change or its branch. |
| 141 | Running func(k restack.Key, branch string) bool |
| 142 | Now func() time.Time |
| 143 | } |
| 144 | |
| 145 | // Pass reads the checks of the ready changes klaus owns in repos, on |
| 146 | // listed, or with nil, listing each repo, and with act dispatches a fix |
| 147 | // run for each failed head it hasn't acted on, saving what it did in l. |
| 148 | // It returns a line per change whose checks failed. A change is klaus's |
| 149 | // when its record's owner is the repo's principal (valley.principal). A |
| 150 | // change with no checks listed, or pending ones, is left alone. |
| 151 | func Pass(ctx context.Context, d Deps, l *Ledger, repos []restack.Repo, listed *valley.Changes, act bool) []string { |
| 152 | var out []string |
| 153 | for _, r := range repos { |
| 154 | vr, ok := repoOf(ctx, d, r, listed) |
| 155 | if !ok { |
| 156 | continue |
| 157 | } |
| 158 | principal := d.Principal(ctx, r.Dir) |
| 159 | if principal == "" { |
| 160 | continue |
| 161 | } |
| 162 | for _, ch := range vr.Changes { |
| 163 | if line := handle(ctx, d, l, r, ch, principal, act); line != "" { |
| 164 | out = append(out, line) |
| 165 | } |
| 166 | } |
| 167 | } |
| 168 | return out |
| 169 | } |
| 170 | |
| 171 | // repoOf is repo r as listed, or as the valley lists it now. |
| 172 | func repoOf(ctx context.Context, d Deps, r restack.Repo, listed *valley.Changes) (valley.Repo, bool) { |
| 173 | if listed == nil { |
| 174 | var err error |
| 175 | if listed, err = d.List(ctx, r.Dir); err != nil { |
| 176 | return valley.Repo{}, false |
| 177 | } |
| 178 | } |
| 179 | for _, vr := range listed.Repos { |
| 180 | if vr.Repo == r.Name && vr.Err() == "" { |
| 181 | return vr, true |
| 182 | } |
| 183 | } |
| 184 | return valley.Repo{}, false |
| 185 | } |
| 186 | |
| 187 | // handle acts on one change's checks and says what came of them. |
| 188 | func handle(ctx context.Context, d Deps, l *Ledger, r restack.Repo, ch valley.Change, principal string, act bool) string { |
| 189 | if ch.State != valley.StateReady || ch.Owner != principal { |
| 190 | return "" |
| 191 | } |
| 192 | v, ok := integration.ActiveVersion(ch) |
| 193 | if !ok || v.Checks == nil || v.Landing == valley.Landed || v.Landing == valley.LandedRecorded { |
| 194 | return "" |
| 195 | } |
| 196 | key := r.Name + "/" + ch.ChangeID |
| 197 | e := l.entries[key] |
| 198 | name := ch.Handle |
| 199 | if name == "" { |
| 200 | name = ch.ChangeID |
| 201 | } |
| 202 | switch v.Checks.State { |
| 203 | case valley.ChecksPassed: |
| 204 | // Checks passing start the count over, as CI passing does. |
| 205 | if act && e != nil && (e.Attempts > 0 || e.Stopped || e.RunID != "") { |
| 206 | e.Attempts, e.Stopped, e.RunID = 0, false, "" |
| 207 | l.save() //nolint:errcheck // a later pass resets it again |
| 208 | } |
| 209 | return "" |
| 210 | case valley.ChecksFailed: |
| 211 | default: |
| 212 | return "" |
| 213 | } |
| 214 | label := fmt.Sprintf("%s %s v%d checks failed (%s)", r.Name, name, v.N, strings.Join(v.Checks.FailedNames(), ", ")) |
| 215 | if e != nil && slices.Contains(e.Heads, v.Head) { |
| 216 | return label + ": " + e.said(v.Head) |
| 217 | } |
| 218 | if d.Running(restack.Key{Repo: r.Name, ChangeID: ch.ChangeID}, v.Branch) { |
| 219 | return label + ": a run is working on the change" |
| 220 | } |
| 221 | attempts := 0 |
| 222 | if e != nil { |
| 223 | attempts = e.Attempts |
| 224 | if e.RunID != "" { |
| 225 | attempts++ // the last fix run left this version failing |
| 226 | } |
| 227 | } |
| 228 | if !act { |
| 229 | if attempts >= MaxAttempts { |
| 230 | return label + fmt.Sprintf(": stopped after %d fix runs", attempts) |
| 231 | } |
| 232 | return label + ": a fix run is due" |
| 233 | } |
| 234 | if e == nil { |
| 235 | e = &Entry{Repo: r.Name, ChangeID: ch.ChangeID} |
| 236 | l.entries[key] = e |
| 237 | } |
| 238 | e.Handle = name |
| 239 | e.Attempts = attempts |
| 240 | e.Heads = append(e.Heads, v.Head) |
| 241 | if len(e.Heads) > maxHeads { |
| 242 | e.Heads = e.Heads[len(e.Heads)-maxHeads:] |
| 243 | } |
| 244 | e.Head, e.Error, e.RunID = v.Head, "", "" |
| 245 | e.At = d.Now().UTC().Format(time.RFC3339) |
| 246 | if attempts >= MaxAttempts { |
| 247 | e.Stopped = true |
| 248 | l.save() //nolint:errcheck // the head is acted on in memory either way |
| 249 | return label + ": " + e.said(v.Head) |
| 250 | } |
| 251 | runID, err := d.NewRunID() |
| 252 | if err != nil { |
| 253 | e.Error = err.Error() |
| 254 | l.save() //nolint:errcheck |
| 255 | return label + ": " + e.said(v.Head) |
| 256 | } |
| 257 | e.RunID = runID |
| 258 | // Record the dispatch before launching it: a pass that can't record |
| 259 | // what it does dispatches nothing. |
| 260 | if err := l.save(); err != nil { |
| 261 | return label + ": not dispatched: saving the ledger: " + err.Error() |
| 262 | } |
| 263 | err = d.Launch(ctx, Launch{ |
| 264 | Dir: r.Dir, Project: r.Project, ChangeID: ch.ChangeID, RunID: runID, |
| 265 | Owner: principal, Branch: v.Branch, Head: v.Head, Prompt: Prompt(r.Name, ch, v), |
| 266 | }) |
| 267 | if err != nil { |
| 268 | // A failed launch is no fix attempt. |
| 269 | e.Error, e.RunID = err.Error(), "" |
| 270 | l.save() //nolint:errcheck |
| 271 | } |
| 272 | return label + ": " + e.said(v.Head) |
| 273 | } |
| 274 | |
| 275 | // said is what the entry says klaus did about failed head. |
| 276 | func (e *Entry) said(head string) string { |
| 277 | switch { |
| 278 | case e.Head != head: |
| 279 | return "acted on before" |
| 280 | case e.Stopped: |
| 281 | return fmt.Sprintf("stopped after %d fix runs", e.Attempts) |
| 282 | case e.Error != "": |
| 283 | return "not dispatched: " + e.Error |
| 284 | } |
| 285 | return fmt.Sprintf("fix run %s dispatched (attempt %d of %d)", e.RunID, e.Attempts+1, MaxAttempts) |
| 286 | } |
| 287 | |
| 288 | // plainName is a check name klaus passes on to a run's prompt. |
| 289 | var plainName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$`) |
| 290 | |
| 291 | // maxWhy bounds the worker's reason a prompt quotes for a check. |
| 292 | const maxWhy = 300 |
| 293 | |
| 294 | // Prompt is the brief of a run that fixes the failed checks of version v of |
| 295 | // change ch in repo. |
| 296 | func Prompt(repo string, ch valley.Change, v valley.Version) string { |
| 297 | var b strings.Builder |
| 298 | fmt.Fprintf(&b, "The valley host's check worker failed required checks of change %s (%s) v%d in %s, at head %s on branch %s:\n\n", |
| 299 | ch.Handle, ch.ChangeID, v.N, repo, v.Head, v.Branch) |
| 300 | failed := v.Checks.Failed() |
| 301 | sort.SliceStable(failed, func(i, j int) bool { return failed[i].Name < failed[j].Name }) |
| 302 | for _, c := range failed { |
| 303 | name := c.Name |
| 304 | if !plainName.MatchString(name) { |
| 305 | name = "(a check with an unprintable name)" |
| 306 | } |
| 307 | why := strings.Join(strings.Fields(c.Why), " ") |
| 308 | if len(why) > maxWhy { |
| 309 | why = why[:maxWhy] + "..." |
| 310 | } |
| 311 | if why == "" { |
| 312 | why = "no reason given" |
| 313 | } |
| 314 | fmt.Fprintf(&b, " - %s: the worker says %q\n", name, why) |
| 315 | } |
| 316 | fmt.Fprintf(&b, ` |
| 317 | Read the worker's build output for each failed check with |
| 318 | 'valley telemetry --json read --source worker --logs', keeping the records |
| 319 | for change ID %s and the check's name. A read returns at most 200 records, |
| 320 | and its last line carries a cursor: pass it with --since to read the next |
| 321 | page, until you have the check's whole run. |
| 322 | |
| 323 | Fix the failures by amending the change's single commit (git commit |
| 324 | --amend); don't add commits. Before you push, build and run every check |
| 325 | 'valley checks --names origin/main HEAD' lists, and push only once each |
| 326 | passes.`, ch.ChangeID) |
| 327 | return b.String() |
| 328 | } |