gunk-dev/the-valley

restack.go

source6a7605f70901main's published tip history
12.7 KiB
1// Package restack dispatches resolution runs for the restack conflicts a
2// valley reports on changes klaus owns.
3//
4// A valley's host restacker rebases ready changes onto main after each
5// landing. When a rebase conflicts it writes a report beside the change
6// record (refs/the-valley/restack/main/<change ID>), and the valley lists
7// the latest one with the change, saying whether it is current: whether
8// every ref it observed still holds what it observed. This package reads
9// those reports and, for a current conflict on a change whose record names
10// klaus's principal as its owner, launches a run to resolve it, as the
11// pipeline dispatches conflict fixes for GitHub PRs.
12//
13// A report is an observation, not an instruction. klaus acts on one only
14// after its own reads agree with it: before dispatching it reads the change
15// and origin's refs again and skips a report whose inputs moved. It runs
16// nothing a report supplies, and builds the run's prompt from its own reads
17// alone: identities it checked, never the report's paths or text.
18package restack
19
20import (
21 "fmt"
22 "regexp"
23 "strings"
24 "time"
25
26 "the-valley/flow/internal/run"
27 "the-valley/flow/internal/valley"
28)
29
30const (
31 // MaxAttempts is how many resolution runs klaus dispatches for one
32 // change before it stops, until a restack of the change succeeds: the
33 // pipeline's budget for a PR's conflict fixes.
34 MaxAttempts = 3
35 // Cooldown is the least time between two dispatches for one change.
36 Cooldown = 60 * time.Second
37)
38
39// Key names a change: the valley's name for its repo, and its change ID.
40type Key struct{ Repo, ChangeID string }
41
42func (k Key) String() string { return k.Repo + "/" + k.ChangeID }
43
44// Conflict is a current conflict report on a change klaus owns, with the
45// change as the same listing shows it.
46type Conflict struct {
47 Key
48 Handle string
49 Target string // the branch the change lands on, main
50 Owner string // the record's owner: klaus's principal
51 Branch string // the active version's branch, as the record names it
52 Version int // the active version
53 Head string // the active version's head
54 Record string // the change's record commit
55 // Report is the report's commit, and TargetTip the target's tip the
56 // report observed.
57 Report string
58 TargetTip string
59 // Held says why klaus leaves the conflict alone, or "" when it may
60 // resolve it: the failing layer is another change, or the change sits
61 // on others.
62 Held string
63 // HeldReason is Held in a few words, as change:restack-stalled gives it.
64 HeldReason string
65
66 layers []layer
67}
68
69func (c Conflict) inputs() Inputs { return Inputs{Head: c.Head, TargetTip: c.TargetTip} }
70
71// layer is a change a report says it rebased together with the conflict's,
72// bottom first: the record and branch tip the report observed, and the
73// branch the valley's record names for it, which the report's agrees with.
74type layer struct {
75 ChangeID string
76 Record string // the record commit the report observed
77 Branch string // the active version's branch, from the change's record
78 BranchTip *string
79}
80
81// Clean is a current report saying a change klaus owns restacked cleanly.
82type Clean struct {
83 Key
84 Target string
85 Report string // the report's commit
86}
87
88// Scan reads a repo's listing for the restack reports on changes principal
89// owns: owner is the change record's, not any version's uploader, since
90// the restacker uploads the versions it rebases. It returns the current
91// conflicts on ready changes, and the changes whose current report says
92// they restacked cleanly. A report klaus's reading of the listing
93// contradicts is skipped as stale, whatever the valley says: its change's
94// layer names another record, version, head or branch, or another layer
95// names a branch its change's record doesn't, or one the listing lacks.
96// A principal of "" owns nothing.
97func Scan(repo valley.Repo, principal string) (conflicts []Conflict, clean []Clean) {
98 if principal == "" || repo.Err() != "" {
99 return nil, nil
100 }
101 byID := make(map[string]valley.Change, len(repo.Changes))
102 for _, ch := range repo.Changes {
103 byID[ch.ChangeID] = ch
104 }
105 for _, ch := range repo.Changes {
106 rs := ch.Restack
107 if ch.Owner != principal || rs == nil || !rs.Current || rs.Report == nil {
108 continue
109 }
110 rep := rs.Report
111 if rep.ChangeID != ch.ChangeID || rep.Target != ch.Target {
112 continue
113 }
114 key := Key{Repo: repo.Repo, ChangeID: ch.ChangeID}
115 if rep.Result == valley.RestackComplete {
116 clean = append(clean, Clean{Key: key, Target: ch.Target, Report: rs.Commit})
117 continue
118 }
119 if rep.Result != valley.RestackConflict || rep.Failing == nil || ch.State != valley.StateReady {
120 continue
121 }
122 active, ok := activeVersion(ch)
123 own, found := rep.Layer(ch.ChangeID)
124 tip := valley.ReportOID(rep.TargetTip)
125 if !ok || !found || tip == "" || own.Version != ch.Active ||
126 valley.ReportOID(own.Head) != active.Head || valley.ReportOID(own.Record) != ch.Record {
127 continue
128 }
129 layers, agree := checkedLayers(rep.Layers, byID)
130 if !agree {
131 continue
132 }
133 c := Conflict{
134 Key: key, Handle: ch.Handle, Target: ch.Target, Owner: ch.Owner, Branch: active.Branch,
135 Version: ch.Active, Head: active.Head, Record: ch.Record,
136 Report: rs.Commit, TargetTip: tip, layers: layers,
137 }
138 c.Held, c.HeldReason = held(c, *rep.Failing, ch, byID, principal)
139 conflicts = append(conflicts, c)
140 }
141 return conflicts, clean
142}
143
144// checkedLayers returns a report's layers with the branch each change's
145// record names, and whether every layer's agrees with it: a branch the
146// report names, or leaves out, is never the one klaus checks for movement
147// unless the record names it too. A layer whose change the listing lacks,
148// or whose record names no branch, can't be checked.
149func checkedLayers(layers []valley.RestackLayer, byID map[string]valley.Change) ([]layer, bool) {
150 out := make([]layer, 0, len(layers))
151 for _, l := range layers {
152 ch, listed := byID[l.ChangeID]
153 v, ok := activeVersion(ch)
154 if !listed || !ok || v.Branch == "" || l.Branch != v.Branch {
155 return nil, false
156 }
157 out = append(out, layer{ChangeID: l.ChangeID, Record: valley.ReportOID(l.Record), Branch: v.Branch, BranchTip: l.BranchTip})
158 }
159 return out, true
160}
161
162// held says why klaus leaves a conflict alone, or "" when it may resolve
163// it. It resolves a conflict only in the change itself, at the bottom of
164// what the restacker rebased: a conflict in a change below belongs to that
165// change, and klaus never takes over another owner's change; and a change
166// that sits on other changes can't be rebased onto main on its own.
167func held(c Conflict, failing string, ch valley.Change, byID map[string]valley.Change, principal string) (detail, reason string) {
168 if failing != c.ChangeID {
169 name := failing
170 f, listed := byID[failing]
171 if listed && f.Handle != "" {
172 name = f.Handle
173 }
174 if listed && f.Owner == principal {
175 return "the conflict is in " + name + ", a change below it, which is resolved first", "left-alone: conflict in a change below"
176 }
177 return "the conflict is in " + name + ", a change below it that flow doesn't own", "left-alone: conflict in a change below"
178 }
179 if len(c.layers) > 0 && c.layers[0].ChangeID != c.ChangeID || len(ch.Includes) > 0 {
180 return "it sits on other changes; flow resolves a conflict only in a change that sits on main", "left-alone: sits on other changes"
181 }
182 return "", ""
183}
184
185// activeVersion returns a change's active version.
186func activeVersion(ch valley.Change) (valley.Version, bool) {
187 for _, v := range ch.Versions {
188 if v.N == ch.Active {
189 return v, true
190 }
191 }
192 return valley.Version{}, false
193}
194
195// Decision is what a pass does about a conflict.
196type Decision int
197
198const (
199 // Dispatch launches a resolution run.
200 Dispatch Decision = iota
201 // Held leaves a conflict klaus doesn't resolve (Conflict.Held).
202 Held
203 // Acted leaves a conflict klaus already acted on: an earlier pass
204 // dispatched for, or refused, the same head and target tip.
205 Acted
206 // Busy leaves a change a run is working on, or one klaus is launching
207 // a run for.
208 Busy
209 // Stop leaves a change whose attempts are spent.
210 Stop
211 // Wait leaves a change dispatched for within the cooldown.
212 Wait
213)
214
215// Decide is what a pass does about conflict c at now, given the ledger's
216// entry for its change (nil for none) and whether a run is working on the
217// change. As the pipeline does for a PR's conflicts, it never starts a
218// second run on a change, nor while a launch klaus started is pending;
219// stops once MaxAttempts runs were dispatched, and waits Cooldown after
220// each launch that may have started one; and it never acts twice on one
221// set of inputs it remembers (MaxActions), the change's head and the
222// target's tip, whichever came between, so an unchanged conflict isn't
223// retried. Spent attempts come
224// before that once no run is working on the change, so a last run that
225// left the conflict as it was is seen to have stopped.
226func Decide(now time.Time, c Conflict, e *Entry, running bool) Decision {
227 spent := e != nil && e.Attempts >= MaxAttempts
228 last := e.Last()
229 switch {
230 case c.Held != "":
231 return Held
232 case e.Pending() != nil:
233 return Busy
234 case e.ActionOn(c.inputs()) != nil && (running || !spent):
235 return Acted
236 case running:
237 return Busy
238 case spent:
239 return Stop
240 case last != nil && last.RunID != "" && now.Sub(last.At) < Cooldown:
241 return Wait
242 }
243 return Dispatch
244}
245
246// Stale compares a conflict's report with origin's refs as klaus read them
247// itself (refs, by name, as OriginRefs returns them), and says which input
248// moved, or "" when every one still holds: the target's tip, the report
249// itself, and for each layer its record and the tip (or the absence) of
250// the branch its record names.
251func Stale(c Conflict, refs map[string]string) string {
252 switch {
253 case refs["refs/heads/"+c.Target] != c.TargetTip:
254 return c.Target + " moved since the report"
255 case refs[ReportRef(c.Target, c.ChangeID)] != c.Report:
256 return "a newer report replaced it"
257 }
258 for _, l := range c.layers {
259 if refs[RecordRef(c.Target, l.ChangeID)] != l.Record {
260 return "the record of " + l.ChangeID + " moved since the report"
261 }
262 tip, present := refs["refs/heads/"+l.Branch]
263 switch {
264 case l.BranchTip == nil && present:
265 return "branch " + l.Branch + " appeared since the report"
266 case l.BranchTip != nil && tip != valley.ReportOID(*l.BranchTip):
267 return "branch " + l.Branch + " moved since the report"
268 }
269 }
270 return ""
271}
272
273// Refs are the refs Stale compares.
274func Refs(c Conflict) []string {
275 refs := []string{"refs/heads/" + c.Target, ReportRef(c.Target, c.ChangeID)}
276 for _, l := range c.layers {
277 refs = append(refs, RecordRef(c.Target, l.ChangeID), "refs/heads/"+l.Branch)
278 }
279 return refs
280}
281
282// RecordRef is the ref of a change's record on origin.
283func RecordRef(target, id string) string { return "refs/the-valley/changes/" + target + "/" + id }
284
285// ReportRef is the ref of a change's restack report on origin.
286func ReportRef(target, id string) string { return "refs/the-valley/restack/" + target + "/" + id }
287
288// plainName matches a name safe to put in a prompt as it is: a repo,
289// branch or handle with no spaces, quotes or control characters.
290var plainName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$`)
291
292// Prompt is the brief of a run resolving conflict c. It holds only what
293// klaus read and checked itself: the change's ID, the version, head and
294// branch the valley's record names, and the target's tip origin holds,
295// which the report matched. None of the report's free text, such as its
296// conflict paths, goes in: the run finds the conflicts by rebasing.
297func Prompt(c Conflict) string {
298 if !run.ValidChangeID(c.ChangeID) || !valley.IsOID(c.Head) || !valley.IsOID(c.TargetTip) {
299 return ""
300 }
301 name := c.ChangeID
302 if plainName.MatchString(c.Handle) {
303 name = c.Handle + " (" + c.ChangeID + ")"
304 }
305 repo, target := "its repo", "main"
306 if plainName.MatchString(c.Repo) {
307 repo = c.Repo
308 }
309 if plainName.MatchString(c.Target) {
310 target = c.Target
311 }
312 var b strings.Builder
313 fmt.Fprintf(&b, "The valley's restacker could not rebase change %s of %s onto %s: the rebase conflicts in this change's own commits.\n\n", name, repo, target)
314 b.WriteString("flow read, before launching this run:\n")
315 fmt.Fprintf(&b, "- the change: version %d, head %s", c.Version, c.Head)
316 if plainName.MatchString(c.Branch) {
317 fmt.Fprintf(&b, ", branch %s", c.Branch)
318 }
319 fmt.Fprintf(&b, "\n- %s on origin: %s\n\n", target, c.TargetTip)
320 fmt.Fprintf(&b, "Rebase the change onto origin/%s and resolve the conflicts, keeping what both sides meant. Find the conflicting paths by running the rebase; nothing else names them for you. ", target)
321 b.WriteString("Run the tests, then push the rebased head with the leased push your instructions give. ")
322 b.WriteString("Rewrite only this change's commits: if a conflict lies in another change's commits, stop and say so. ")
323 b.WriteString("The change is a draft while you work; finalize marks the head you push ready again.\n")
324 return b.String()
325}