| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "strings" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/wire" |
| 10 | "gorm.io/gorm" |
| 11 | ) |
| 12 | |
| 13 | // Base preparation (Mac runners spec §8.4, slice F). A worker has no |
| 14 | // clone and no forge access, so the base an Engineering attempt on it |
| 15 | // starts from is resolved by the primary, in two transactions: |
| 16 | // |
| 17 | // 1. placement chose a worker and the attempt has no bound base (a first |
| 18 | // step, or a rebase round whose new tip is unknown): prepare_base goes |
| 19 | // to the primary's mailbox and the attempt waits (waiting_base), |
| 20 | // placed nowhere; |
| 21 | // 2. the primary's base report for that attempt, from the primary's own |
| 22 | // connection, binds the base to the attempt; in the same transaction |
| 23 | // the attempt is placed again and, on a worker, dispatched with its |
| 24 | // inbound Engineering transfer (dispatchStep). |
| 25 | // |
| 26 | // A fix round starts from the task branch's published tip, which is |
| 27 | // known, so it skips phase 1; so do a Retry and a republish, which run |
| 28 | // from the base the step already has. A report for anything else is |
| 29 | // refused and logged. |
| 30 | |
| 31 | // boundBase is the base an Engineering attempt starts from, "" when none |
| 32 | // is bound yet: the step's own, else (not a rebase round) the task's. |
| 33 | func boundBase(k taskRecord, s stepRecord) string { |
| 34 | if s.BaseSHA == "" && !s.Rebase { |
| 35 | return k.BaseSHA |
| 36 | } |
| 37 | return s.BaseSHA |
| 38 | } |
| 39 | |
| 40 | // prepareBase is phase 1 for the attempt placement put on worker |
| 41 | // d.runner: the attempt waits for its base (placed nowhere, the Mac it is |
| 42 | // for named), and the primary is asked once for this attempt. The caller |
| 43 | // saves s. |
| 44 | func (t *txn) prepareBase(k *taskRecord, s *stepRecord, primary string, d engineeringPlacement) error { |
| 45 | if _, err := t.waitForMac(s, d.needs, wire.PlacementBase); err != nil { |
| 46 | return err |
| 47 | } |
| 48 | s.SandboxRunner = d.runner |
| 49 | var p projectRecord |
| 50 | if err := t.db.Where("id = ?", k.ProjectID).First(&p).Error; err != nil { |
| 51 | return err |
| 52 | } |
| 53 | cmd := wire.PrepareBaseCommand{TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt, Repo: p.Repo} |
| 54 | if s.Rebase { |
| 55 | cmd.Rebase, cmd.FromBase, cmd.CandidateSHA = true, s.FromBase, s.FromCandidate |
| 56 | } |
| 57 | if !cmd.Valid() { |
| 58 | // Nothing a primary could resolve (a rebase round without its old |
| 59 | // base): the attempt ends as the primary would have ended it. |
| 60 | baseUnavailable(t, s) |
| 61 | return nil |
| 62 | } |
| 63 | var asked int64 |
| 64 | if err := t.db.Model(&commandRecord{}).Where("runner_id = ? AND kind = ? AND body LIKE ?", primary, wire.FramePrepareBase, attemptLike(s.ID, s.Attempt)).Count(&asked).Error; err != nil || asked > 0 { |
| 65 | return err |
| 66 | } |
| 67 | return t.commandTo(primary, s.Person, wire.FramePrepareBase, cmd) |
| 68 | } |
| 69 | |
| 70 | // attemptLike matches the JSON of a command naming step's attempt. |
| 71 | func attemptLike(step string, attempt int64) string { |
| 72 | return `%"step_id":"` + step + `","attempt":` + itoa64(attempt) + `,%` |
| 73 | } |
| 74 | |
| 75 | // baseUnavailable ends the attempt failed (base_unavailable): nothing |
| 76 | // ran, so its end is proven; Needs you retry. |
| 77 | func baseUnavailable(t *txn, s *stepRecord) { |
| 78 | now := t.now() |
| 79 | s.State, s.Reason, s.Terminated, s.FinishedAt = wire.StepFailed, wire.ReasonBaseUnavailable, true, &now |
| 80 | s.Placement, s.WaitingSince, s.SandboxRunner, s.RunnerID = "", nil, "", "" |
| 81 | } |
| 82 | |
| 83 | // errBaseRefused refuses a base report: logged, acked, no effect. |
| 84 | func errBaseRefused(why string) error { |
| 85 | return fmt.Errorf("%w: base_refused: %s", ErrRefused, why) |
| 86 | } |
| 87 | |
| 88 | // base is phase 2: the primary's answer to prepare_base. Only from the |
| 89 | // person's primary, for the Engineering attempt that is current, not |
| 90 | // withdrawn, of a task neither cancelled nor ended. A second report for |
| 91 | // an attempt no longer waiting for its base does nothing. |
| 92 | func (t *txn) base(l Lease, v *wire.BaseReport) error { |
| 93 | if !v.Valid() { |
| 94 | return errBaseRefused("invalid report") |
| 95 | } |
| 96 | primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person) |
| 97 | if err != nil { |
| 98 | return err |
| 99 | } |
| 100 | if primary == "" || primary != l.Runner.RunnerID { |
| 101 | return errBaseRefused("not the primary") |
| 102 | } |
| 103 | var s stepRecord |
| 104 | if err := t.db.Where("id = ? AND task_id = ? AND person = ?", v.StepID, v.TaskID, l.Runner.Person).First(&s).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 105 | return errBaseRefused("no such step") |
| 106 | } else if err != nil { |
| 107 | return err |
| 108 | } |
| 109 | k, err := t.loadTask(s.TaskID) |
| 110 | if err != nil { |
| 111 | return err |
| 112 | } |
| 113 | if k.CancelRequested || wire.FinalStage(k.Stage) || k.MoveProject != "" || s.Retired { |
| 114 | return errBaseRefused("task ended") |
| 115 | } |
| 116 | if s.Specialist != wire.SpecialistEngineering || s.Attempt != v.Attempt || s.Withdrawn { |
| 117 | return errBaseRefused("attempt not current") |
| 118 | } |
| 119 | if s.State != wire.StepQueued || s.Placement != wire.PlacementBase { |
| 120 | return nil |
| 121 | } |
| 122 | if v.Reason == wire.ReasonBaseUnavailable { |
| 123 | baseUnavailable(t, &s) |
| 124 | if err := t.saveStep(&s, &k); err != nil { |
| 125 | return err |
| 126 | } |
| 127 | return t.advance(&k) |
| 128 | } |
| 129 | s.BaseSHA = v.BaseSHA |
| 130 | if !s.Rebase && k.BaseSHA == "" { |
| 131 | k.BaseSHA = v.BaseSHA |
| 132 | } |
| 133 | if err := t.dispatchStep(&k, &s); err != nil { |
| 134 | return err |
| 135 | } |
| 136 | return t.saveStep(&s, &k) |
| 137 | } |
| 138 | |
| 139 | // macEngineeringNeeds is what Mac Engineering waiting at s needs of the |
| 140 | // person: a Mac's Claude connection, an update, or the Mac back online |
| 141 | // after OfflineLimit; "" when nothing. |
| 142 | func macEngineeringNeeds(s *stepRecord) string { |
| 143 | if s == nil || s.State != wire.StepQueued { |
| 144 | return "" |
| 145 | } |
| 146 | switch { |
| 147 | case s.Placement == wire.PlacementMacConnection: |
| 148 | return wire.NeedsMacConnection |
| 149 | case s.Placement == wire.PlacementMacUpdate: |
| 150 | return wire.NeedsMacUpdate |
| 151 | case s.Specialist == wire.SpecialistEngineering && s.Placement == wire.PlacementWaiting && s.Reason == reasonRunnerOffline: |
| 152 | return wire.NeedsRunnerOffline |
| 153 | } |
| 154 | return "" |
| 155 | } |
| 156 | |
| 157 | // helloEngineering is what a stored hello says of its runner's readiness |
| 158 | // for Mac Engineering: its tags and its Engineering status. |
| 159 | func helloEngineering(raw string) string { |
| 160 | var h wire.Hello |
| 161 | if raw == "" || json.Unmarshal([]byte(raw), &h) != nil || h.Capabilities == nil { |
| 162 | return "" |
| 163 | } |
| 164 | key := strings.Join(h.Capabilities.Tags, ",") |
| 165 | if e := h.Capabilities.Engineering; e != nil { |
| 166 | key += "|" + e.State |
| 167 | } |
| 168 | return key |
| 169 | } |
| 170 | |
| 171 | // awaitingPublication: s is a worker's Engineering round that ended |
| 172 | // (done) without its commit published yet, or whose publication failed: |
| 173 | // the round is not over, so nothing judges or follows it (the primary's |
| 174 | // published report, or the person's Retry, moves it on). |
| 175 | func awaitingPublication(s *stepRecord) bool { |
| 176 | return s.Specialist == wire.SpecialistEngineering && s.State == wire.StepDone && !s.Pushed |
| 177 | } |
| 178 | |
| 179 | // reprepareBases runs when the person's primary connects: a replacement, |
| 180 | // or the same runner at another protocol. A base preparation it cannot |
| 181 | // answer is invalidated: one asked of another runner (a primary replaced |
| 182 | // after it acked, rebind moving only unacked commands), or any while it |
| 183 | // speaks below protocol 37. The attempt is replaced, so a report for the |
| 184 | // invalidated request names an attempt that is not current and is |
| 185 | // refused; the next is placed again: a fresh prepare_base to this |
| 186 | // primary, or waiting_mac_update naming it. |
| 187 | func (t *txn) reprepareBases(person, primary string, protocol int) error { |
| 188 | if current, err := t.s.authority.PrimaryRunner(t.db, person); err != nil || current != primary { |
| 189 | return err |
| 190 | } |
| 191 | var rows []stepRecord |
| 192 | if err := t.db.Where("person = ? AND placement = ? AND state = ?", person, wire.PlacementBase, wire.StepQueued).Find(&rows).Error; err != nil { |
| 193 | return err |
| 194 | } |
| 195 | for i := range rows { |
| 196 | s := rows[i] |
| 197 | var mine int64 |
| 198 | if err := t.db.Model(&commandRecord{}).Where("runner_id = ? AND kind = ? AND body LIKE ?", primary, wire.FramePrepareBase, attemptLike(s.ID, s.Attempt)).Count(&mine).Error; err != nil { |
| 199 | return err |
| 200 | } |
| 201 | if mine > 0 && protocol >= wire.ProtocolMacEngineering { |
| 202 | continue |
| 203 | } |
| 204 | k, err := t.loadTask(s.TaskID) |
| 205 | if err != nil { |
| 206 | return err |
| 207 | } |
| 208 | if wire.FinalStage(k.Stage) || k.CancelRequested || k.MoveProject != "" || s.Retired { |
| 209 | continue |
| 210 | } |
| 211 | if err := t.replace(&k, &s); err != nil { |
| 212 | return err |
| 213 | } |
| 214 | if err := t.saveStep(&s, &k); err != nil { |
| 215 | return err |
| 216 | } |
| 217 | } |
| 218 | return nil |
| 219 | } |
| 220 | |