gunk-dev/the-valley

checksfix.go

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