gunk-dev/the-valley

restack_conflicts.go

source30e24c82839bmain's published tip history
10.5 KiB
1package cmd
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "log/slog"
8 "os"
9 "os/exec"
10 "strings"
11 "time"
12
13 "the-valley/flow/internal/event"
14 "the-valley/flow/internal/git"
15 "the-valley/flow/internal/integration"
16 "the-valley/flow/internal/restack"
17 "the-valley/flow/internal/run"
18 "the-valley/flow/internal/tmux"
19 "the-valley/flow/internal/valley"
20 "github.com/spf13/cobra"
21)
22
23var restackConflictsCmd = &cobra.Command{
24 Use: "restack-conflicts",
25 Short: "Dispatch runs to resolve the restack conflicts a valley reports on changes flow owns",
26 Long: `Reads the restack reports of the valley repos the session's runs deliver
27to, and launches a run to resolve each current conflict on a change flow
28owns. The dashboard does this after each integration check, about once a
29minute; run it by hand where no dashboard runs.
30
31A valley's restacker rebases ready changes onto main after each landing, and
32when a rebase conflicts it reports the conflict beside the change. A change
33is flow's when its record's owner is flow's principal, the repo's git
34config valley.principal; who uploaded its latest version doesn't count,
35since the restacker uploads the versions it rebases. A report counts only
36while the valley says it is current, and while what the listing shows of
37the change (its record, active version, head and branch) matches the
38report, and each other change the report rebased is listed on the branch
39the report names for it.
40
41For each such conflict, unless flow leaves it alone (below), flow:
42
43 1. reads the change and origin's refs again: main, the report, and each
44 rebased change's record and the branch its record names, and skips
45 the report if any moved;
46 2. records the attempt, and the ID of the run it is about to launch, in
47 its ledger, and does nothing if it can't;
48 3. returns the change to draft ('valley unready'), and launches nothing
49 unless the valley then lists it as flow's draft at the same head and
50 branch;
51 4. launches 'valley flow launch [--repo <project>] --change <change-id>
52 --run-id <id> --expect-owner <principal> --expect-branch <branch>
53 --expect-head <head> --expect-draft --reason restack-conflict <brief>'
54 from a clone of the repo. Launch checks all of it again, fetching the
55 branch and asking the valley under its continuation lock, before it
56 creates the worktree and again as the worker starts, and fails rather
57 than start a worker on a change that was readied or moved meanwhile,
58 or that it couldn't check. It keeps its own refusals too: a run
59 already working on the change or its branch, or a branch with work
60 origin lacks.
61
62The brief names the change, its version, head and branch, and main's tip:
63what flow read itself. Nothing a report says is run, and none of its text
64is passed on; the run finds the conflicts by rebasing, and pushes the
65rebased head with the leased push its instructions give.
66
67As the pipeline does for a PR's conflicts, flow never starts a second run
68on a change, waits 60 seconds after each dispatch, and stops after 3 runs,
69until a report says the change restacked cleanly: one reset per clean
70report, and only while origin still holds that report. It acts once on
71each set of inputs, the change's head and main's tip, whatever came
72between: an unchanged conflict is not retried, nor one that comes back to
73inputs flow acted on before, nor one whose unready or launch failed; it
74shows what came of those inputs then. Once
75no run is working on a change whose attempts are spent, flow says it
76stopped, even if the last run left the conflict as it was.
77
78An attempt is given back only when flow knows no worker started: it
79stopped before launching, or launch exited with status 3. Any other launch
80failure keeps the attempt and the cooldown, and so does a pass that ends
81mid-launch: either leaves the launch pending in the ledger, and the change
82busy, until a run by its ID is recorded (a dispatch) or flow proves no
83worker of it runs: no launch holds the clone's continuation lock, no run
84by the ID is recorded, and no live tmux pane's command names it. Time alone
85settles nothing.
86
87flow leaves a conflict alone when it is in another change below this one
88(a change whose owner isn't flow is never taken over), or when the change
89sits on other changes.
90
91Each dispatch emits change:restack-dispatched under the new run's ID. A
92conflict flow stops short of resolving, or leaves alone (above), emits
93change:restack-stalled once for each set of inputs: the change needs the
94coordinator, as flow will not resolve it. Its reason says why: attempts
95spent, unready or launch failed, or "left-alone: sits on other changes" or
96"left-alone: conflict in a change below". What flow did is kept in the
97session's restack-dispatches.json; valley flow status and the dashboard show it, a conflict left
98alone as needing help.
99The ledger drops a change's entry once the change lands or is withdrawn,
100unless a launch for it is pending, and keeps what came of a change's latest
10116 sets of inputs; older ones may be acted on again.
102
103Prints one line per conflict on a change flow owns.`,
104 Args: cobra.NoArgs,
105 RunE: func(cmd *cobra.Command, args []string) error {
106 store, err := sessionStore()
107 if err != nil {
108 return err
109 }
110 hds, ok := store.(*run.HomeDirStore)
111 if !ok {
112 return fmt.Errorf("restack-conflicts needs a session directory")
113 }
114 views, err := restackPass(cmd.Context(), hds, nil, true)
115 if err != nil {
116 return err
117 }
118 if len(views) == 0 {
119 fmt.Println("No restack conflicts on changes flow owns.")
120 }
121 for _, v := range views {
122 fmt.Println(v)
123 }
124 return nil
125 },
126}
127
128func init() {
129 rootCmd.AddCommand(restackConflictsCmd)
130}
131
132// restackLaunchTimeout bounds one resolution run's launch.
133const restackLaunchTimeout = 5 * time.Minute
134
135// restackPass runs a restack pass over the valley repos of the session's
136// runs, reading their reports in listed, or with nil, listing each repo.
137// With act it holds the ledger's lock, dispatches and records what it did;
138// without, it only reports.
139func restackPass(ctx context.Context, store *run.HomeDirStore, listed *valley.Changes, act bool) ([]restack.View, error) {
140 states, err := store.List()
141 if err != nil {
142 return nil, err
143 }
144 root, _ := git.RepoRoot()
145 repos := restack.Repos(states, root)
146 if len(repos) == 0 {
147 return nil, nil
148 }
149 if act {
150 unlock, err := restack.Lock(store.BaseDir())
151 if err != nil {
152 return nil, err
153 }
154 defer unlock()
155 }
156 // The ledger holds the attempts and cooldowns: a pass that can't read
157 // it dispatches nothing, rather than start them over.
158 ledger, err := restack.LoadLedger(store.BaseDir())
159 if err != nil && act {
160 return nil, fmt.Errorf("reading the restack ledger: %w", err)
161 }
162 if err != nil {
163 slog.Warn("reading the restack ledger", "err", err)
164 }
165 all, err := run.ListAllSessions()
166 if err != nil {
167 all = states
168 }
169 events := event.NewLog(store.BaseDir())
170 emit := func(runID, typ string, data map[string]interface{}) {
171 if err := events.Emit(event.New(runID, typ, data)); err != nil {
172 slog.Warn("emitting a restack event", "type", typ, "err", err)
173 }
174 }
175 d := restack.Default(launchResolution, runRecorded, restack.RunningOn(all, run.DefaultTmuxDeps()), workerGone, emit)
176 return restack.Pass(ctx, d, ledger, repos, listed, act), nil
177}
178
179// launchResolution launches a resolution run with this klaus binary,
180// under the run ID klaus recorded, in launch's strict mode: launch checks
181// the change is still the owner's draft at the branch and head klaus
182// checked before it starts the worker. Launch's exit status 3 says it
183// failed before starting one (restack.ErrNotStarted).
184func launchResolution(ctx context.Context, l restack.Launch) error {
185 self, err := os.Executable()
186 if err != nil {
187 self = "klaus"
188 }
189 args := []string{"launch"}
190 if l.Project != "" {
191 args = append(args, "--repo", l.Project)
192 }
193 args = append(args, "--change", l.ChangeID, "--run-id", l.RunID,
194 "--expect-owner", l.Owner, "--expect-branch", l.Branch, "--expect-head", l.Head, "--expect-draft",
195 "--reason", event.DispatchRestackConflict, "--", l.Prompt)
196 return runLaunch(ctx, self, l.Dir, args)
197}
198
199// runLaunch runs launch with this klaus binary, self, in dir, and says why
200// it failed. An error wrapping restack.ErrNotStarted says launch exited
201// with status 3, before it started a worker.
202func runLaunch(ctx context.Context, self, dir string, args []string) error {
203 ctx, cancel := context.WithTimeout(ctx, restackLaunchTimeout)
204 defer cancel()
205 cmd := exec.CommandContext(ctx, self, args...)
206 cmd.Dir = dir
207 out, err := cmd.CombinedOutput()
208 if err == nil {
209 return nil
210 }
211 why := launchError(out)
212 var exit *exec.ExitError
213 if errors.As(err, &exit) && exit.ExitCode() == exitNoWorker {
214 return fmt.Errorf("klaus launch: %w: %s", restack.ErrNotStarted, why)
215 }
216 return fmt.Errorf("klaus launch: %w: %s", err, why)
217}
218
219// launchError is what a failed launch's output says went wrong: its
220// "Error: " line, else all of it.
221func launchError(out []byte) string {
222 lines := strings.Split(string(out), "\n")
223 for i := len(lines) - 1; i >= 0; i-- {
224 if msg, ok := strings.CutPrefix(lines[i], "Error: "); ok {
225 return msg
226 }
227 }
228 return strings.TrimSpace(string(out))
229}
230
231// runRecorded reports whether a run by runID is recorded in any session.
232func runRecorded(runID string) bool {
233 states, err := run.ListAllSessions()
234 return err == nil && findRun(states, runID) != nil
235}
236
237// workerGone reports whether klaus can prove that no worker of run runID
238// runs, nor is about to start, from the clone at dir: no launch holds the
239// clone's continuation lock, under which launch checks for live holders,
240// starts its worker and records its run (and stops a worker whose run it
241// couldn't record); no run by the ID is recorded, in any session; and no
242// live tmux pane runs a command that names the run, as every worker's
243// does. A launch still on its way to the lock is no worker yet: under the
244// lock it finds any run recorded meanwhile, and starts none beside it. Any
245// read that fails is doubt: false.
246func workerGone(ctx context.Context, dir, runID string) bool {
247 release, ok := tryLockContinuation(ctx, dir)
248 if !ok {
249 return false
250 }
251 defer release()
252 states, err := run.ListAllSessions()
253 if err != nil || findRun(states, runID) != nil {
254 return false
255 }
256 live, err := tmux.PaneStartedWith(ctx, runID)
257 return err == nil && !live
258}
259
260// restackViews indexes views by change, as the dashboard and status look
261// them up.
262func restackViews(views []restack.View) map[integration.ChangeKey]restack.View {
263 out := make(map[integration.ChangeKey]restack.View, len(views))
264 for _, v := range views {
265 out[integration.ChangeKey{Repo: v.Repo, ChangeID: v.ChangeID}] = v
266 }
267 return out
268}