oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "context"
5 "encoding/base64"
6 "encoding/json"
7 "errors"
8 "slices"
9 "strings"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/wire"
13 "gorm.io/gorm"
14)
15
16// Several runners per person (Mac runners spec §1). Every mailbox command
17// and every step attempt names the runner it belongs to: Pending serves a
18// connection only its own commands, an ack counts only from that runner,
19// a step report only from the step's runner, and a sync settles only the
20// syncing runner's steps.
21
22// UnboundSteps counts steps the runner binding missed: no runner, not
23// waiting for one, while the person has a runner. It is the schema check
24// after migration 0054; anything but zero is a bug.
25func UnboundSteps(tx *gorm.DB) (int64, error) {
26 var n int64
27 err := tx.Raw(`SELECT count(*) FROM chat_steps s WHERE coalesce(s.runner_id, '') = ''
28 AND coalesce(s.placement, '') <> 'waiting_runner'
29 AND EXISTS (SELECT 1 FROM runners r WHERE r.person = s.person)`).Scan(&n).Error
30 return n, err
31}
32
33// orphanedBy selects a person's revoked primaries: what was theirs is the
34// current primary's.
35const orphanedBy = `SELECT id FROM runners WHERE person = ? AND revoked_at IS NOT NULL AND coalesce(role, '') IN ('primary', '')`
36
37// attemptKinds are commands that belong to one attempt on one runner: a
38// dispatch whose ack was lost may already run there, so they never move.
39// A sealed secret opens only with its own runner's key.
40var attemptKinds = []string{wire.FrameDispatch, wire.FrameCancelStep, wire.FrameAsk, wire.FrameCancelAsk, wire.FrameBlob, wire.FrameSendPack, wire.FramePublish, wire.FrameSecret}
41
42// rebind gives the person's primary the conversation's commands no runner
43// holds: those written while the person had no primary, and a revoked
44// primary's unacked ones. A revoked runner's attempts stay its own (steps,
45// dispatches, questions, transfers, publications) until their termination
46// is proven; the replacement's sync never settles them.
47func (t *txn) rebind(p RunnerPrincipal) error {
48 if primary, err := t.s.authority.PrimaryRunner(t.db, p.Person); err != nil || primary != p.RunnerID {
49 return err
50 }
51 return t.db.Exec(`UPDATE runner_commands SET runner_id = ? WHERE person = ? AND acked_at IS NULL AND kind NOT IN ?
52 AND (coalesce(runner_id, '') = '' OR runner_id IN (`+orphanedBy+`))`, p.RunnerID, p.Person, attemptKinds, p.Person).Error
53}
54
55// withdrawnEnded applies the termination proof of a withdrawn attempt:
56// it ends as not run when it was withdrawn for that (a pack too large to
57// relay), else the next attempt is placed.
58func (t *txn) withdrawnEnded(k *taskRecord, s *stepRecord) error {
59 runner := s.RunnerID
60 if err := t.withdrawnSettle(k, s); err != nil {
61 return err
62 }
63 return t.removalProgress(runner)
64}
65
66func (t *txn) withdrawnSettle(k *taskRecord, s *stepRecord) error {
67 if s.Specialist == wire.SpecialistCopy {
68 s.Terminated = true
69 return t.withdrawCopy(k, s)
70 }
71 if s.Specialist == wire.SpecialistPreview {
72 // Its proof arrived without an outcome: never replaced.
73 if err := t.settlePreview(k, s); err != nil {
74 return err
75 }
76 return t.saveStep(s, k)
77 }
78 if s.Specialist == wire.SpecialistPublish {
79 // Likewise a publish: it may have deployed.
80 return t.settlePublish(k, s)
81 }
82 if k.CancelRequested || wire.FinalStage(k.Stage) {
83 // Cancelled meanwhile: the proof finishes the cancellation and
84 // nothing is placed.
85 now := t.now()
86 s.State, s.Reason, s.Terminated, s.FinishedAt, s.Withdrawn = wire.StepCancelled, "cancelled", true, &now, false
87 if !wire.FinalStage(k.Stage) {
88 k.Stage = wire.StageCancelled
89 }
90 return t.saveStep(s, k)
91 }
92 if s.Specialist == wire.SpecialistEngineering && s.Reason == wire.ReasonWorkspaceTooLarge {
93 // Its pack could not be relayed: it ends with Needs you, never on
94 // another runner.
95 endFailed(t, s, s.Reason)
96 if err := t.saveStep(s, k); err != nil {
97 return err
98 }
99 return t.advance(k)
100 }
101 if s.Reason != "" {
102 s.Terminated = true
103 return t.resolveNotRun(k, s, s.Reason)
104 }
105 if err := t.replace(k, s); err != nil {
106 return err
107 }
108 return t.saveStep(s, k)
109}
110
111// removalProgress revokes a runner being removed once nothing it may
112// have started is left unproven.
113func (t *txn) removalProgress(runner string) error {
114 if runner == "" || t.s.authority.FinishRemoval == nil {
115 return nil
116 }
117 var removing int64
118 if err := t.db.Raw(`SELECT count(*) FROM runners WHERE id = ? AND removing_at IS NOT NULL AND revoked_at IS NULL`, runner).Scan(&removing).Error; err != nil || removing == 0 {
119 return err
120 }
121 var open int64
122 if err := t.db.Model(&stepRecord{}).Where("runner_id = ? AND state IN ?", runner, []string{wire.StepQueued, wire.StepRunning}).Count(&open).Error; err != nil || open != 0 {
123 return err
124 }
125 return t.s.authority.FinishRemoval(t.db, runner)
126}
127
128// RemoveRunner takes a runner's work back for its removal, in the
129// caller's transaction. An attempt that never started (protocol 2: no
130// start authorization granted) is withdrawn and placed elsewhere at once.
131// One that may have started (authorized, or on a protocol 1 runner whose
132// start is not known) is cancelled and counted uncertain: the caller
133// keeps the runner removing until its proof arrives. With now, the
134// runner is revoked at once instead, so those attempts are quarantined:
135// stopped (machine_removed) with no proof until the creator recovers them.
136func (s *Store) RemoveRunner(tx *gorm.DB, person, runner string, now bool) (uncertain int, err error) {
137 t := &txn{s: s, ctx: context.Background(), db: tx, touched: map[string]bool{}}
138 defer func() {
139 for p := range t.touched {
140 s.hub.Wake(p)
141 }
142 }()
143 var proto int
144 _ = tx.Raw(`SELECT coalesce(protocol, 1) FROM runner_sessions WHERE runner_id = ?`, runner).Scan(&proto).Error
145 var rows []stepRecord
146 if err := tx.Where("runner_id = ? AND state IN ?", runner, []string{wire.StepQueued, wire.StepRunning}).Find(&rows).Error; err != nil {
147 return 0, err
148 }
149 // Engineering waiting for the base of an attempt on it never started
150 // either: withdrawn (its base report is refused from now on) and
151 // placed again without it.
152 var basing []stepRecord
153 if err := tx.Where("sandbox_runner = ? AND placement = ? AND state = ?", runner, wire.PlacementBase, wire.StepQueued).Find(&basing).Error; err != nil {
154 return 0, err
155 }
156 rows = append(rows, basing...)
157 for i := range rows {
158 st := rows[i]
159 k, err := t.loadTask(st.TaskID)
160 if err != nil {
161 return 0, err
162 }
163 started := st.Withdrawn || st.StartedAt != nil || proto < wire.Protocol2
164 switch {
165 case !started:
166 if err := t.replace(&k, &st); err != nil {
167 return 0, err
168 }
169 if err := t.saveStep(&st, &k); err != nil {
170 return 0, err
171 }
172 case now:
173 if err := t.voidAttempt(st); err != nil {
174 return 0, err
175 }
176 at := t.now()
177 st.State, st.Reason, st.Terminated, st.Withdrawn, st.FinishedAt = wire.StepFailed, "machine_removed", false, false, &at
178 if err := t.saveStep(&st, &k); err != nil {
179 return 0, err
180 }
181 default:
182 uncertain++
183 if st.Withdrawn {
184 continue
185 }
186 st.Withdrawn = true
187 if err := t.saveStep(&st, &k); err != nil {
188 return 0, err
189 }
190 if err := t.commandTo(runner, st.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: st.Person, TaskID: k.ID, StepID: st.ID, Attempt: st.Attempt}); err != nil {
191 return 0, err
192 }
193 }
194 }
195 return uncertain, nil
196}
197
198// RecoverTask settles a step stopped when its machine was removed: the
199// task's creator says the machine is off. Its end is recorded unverified
200// (audited), and Retry is possible.
201func (s *Store) RecoverTask(ctx context.Context, person, id string) (attempt int64, err error) {
202 err = s.tx(ctx, func(t *txn) error {
203 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
204 return err
205 }
206 if err := t.isOwner(person); err != nil {
207 return err
208 }
209 k, err := t.loadTask(id)
210 if err != nil {
211 return err
212 }
213 if k.Creator != person {
214 return ErrForbidden
215 }
216 st, found, err := t.latestStep(k.ID)
217 if err != nil {
218 return err
219 }
220 if !found || st.State != wire.StepFailed || st.Reason != "machine_removed" || st.Terminated {
221 return ErrNotRetryable
222 }
223 st.Terminated, st.TerminationKind = true, wire.TerminationUnverified
224 if s.authority.Audit != nil {
225 if err := s.authority.Audit(t.db, person, "task.recover", st.ID); err != nil {
226 return err
227 }
228 }
229 attempt = st.Attempt
230 return t.saveStep(&st, &k)
231 })
232 return attempt, err
233}
234
235// MaxRunnerLabel bounds the machine label a runner reports.
236const MaxRunnerLabel = 80
237
238// cleanHello keeps what the instance stores of a hello within bounds: a
239// capability report out of bounds is dropped (the runner is treated as
240// able to do nothing special), the label is one short line.
241func cleanHello(h wire.Hello) wire.Hello {
242 if h.Capabilities != nil && wire.ValidCapabilities(*h.Capabilities) != nil {
243 h.Capabilities = nil
244 }
245 label, _ := cleanText(strings.ReplaceAll(h.Label, "\n", " "), MaxRunnerLabel)
246 h.Label = label
247 switch h.Sandbox {
248 case "", wire.SandboxBubblewrap, wire.SandboxSeatbelt, wire.SandboxNone:
249 default:
250 h.Sandbox = ""
251 }
252 // The seal key is published for the apps to seal to: only an X25519
253 // public key (32 bytes, standard base64) is kept.
254 if raw, err := base64.StdEncoding.DecodeString(h.SealKey); err != nil || len(raw) != 32 {
255 h.SealKey = ""
256 }
257 return h
258}
259
260// runnerInfo is one of a person's runners as placement and the runners
261// view see it.
262type runnerInfo struct {
263 ID, Role, Label string
264 Seq int64
265 Online bool
266 // Removing: being removed; it gets no new work. Tainted: the instance
267 // holds that a check ran outside the sandbox on it.
268 Removing bool
269 Tainted bool
270 Protocol int
271 Revision int64
272 SeenAt time.Time
273 Hello wire.Hello
274 Running int64
275}
276
277func (r runnerInfo) tags() []string {
278 if r.Hello.Capabilities == nil || r.Protocol < wire.Protocol2 {
279 // A protocol 1 runner is the Linux default.
280 return []string{wire.TagLinux}
281 }
282 return r.Hello.Capabilities.Tags
283}
284
285// fits reports whether checks with needs, refused by those runners, may
286// be placed on r.
287func (r runnerInfo) fits(needs, refused []string) bool {
288 return wire.Covers(r.tags(), needs) && !slices.Contains(refused, r.ID) && r.Protocol >= wire.Protocol2 && !r.Removing
289}
290
291// runners are the person's unrevoked runners in enrolment order, with
292// what each last said and how many steps it runs.
293func (t *txn) runners(person string) ([]runnerInfo, error) {
294 var rows []struct {
295 ID, Role, Label string
296 Seq int64
297 Removing bool
298 Tainted bool
299 }
300 if err := t.db.Raw(`SELECT id, coalesce(role, '') AS role, coalesce(label, '') AS label, rowid AS seq, removing_at IS NOT NULL AS removing, tainted_at IS NOT NULL AS tainted FROM runners
301 WHERE person = ? AND revoked_at IS NULL ORDER BY rowid`, person).Scan(&rows).Error; err != nil {
302 return nil, err
303 }
304 out := make([]runnerInfo, 0, len(rows))
305 for _, r := range rows {
306 info := runnerInfo{ID: r.ID, Role: wire.RolePrimary, Label: r.Label, Seq: r.Seq, Removing: r.Removing, Tainted: r.Tainted}
307 if r.Role == wire.RoleWorker {
308 info.Role = wire.RoleWorker
309 }
310 var sess runnerSessionRecord
311 err := t.db.Where("runner_id = ?", r.ID).First(&sess).Error
312 if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
313 return nil, err
314 }
315 if err == nil {
316 info.Online = sess.Connected && t.now().Sub(sess.SeenAt) < runnerOnline
317 info.Protocol, info.Revision, info.SeenAt = max(sess.Protocol, wire.Protocol1), sess.Revision, sess.SeenAt
318 if sess.Hello != "" {
319 if err := json.Unmarshal([]byte(sess.Hello), &info.Hello); err != nil {
320 return nil, err
321 }
322 if info.Hello.Label != "" {
323 info.Label = info.Hello.Label
324 }
325 }
326 }
327 if err := t.db.Model(&stepRecord{}).Where("runner_id = ? AND state IN ?", r.ID, []string{wire.StepQueued, wire.StepRunning}).Count(&info.Running).Error; err != nil {
328 return nil, err
329 }
330 out = append(out, info)
331 }
332 return out, nil
333}
334
335// runnerOnline reports whether one of the person's runners is online now.
336func (t *txn) runnerOnline(person, id string) (bool, error) {
337 rs, err := t.runners(person)
338 if err != nil {
339 return false, err
340 }
341 for _, r := range rs {
342 if r.ID == id {
343 return r.Online, nil
344 }
345 }
346 return false, nil
347}
348
349// runnerView is the Runner resource.
350func runnerView(r runnerInfo) wire.Runner {
351 v := wire.Runner{ID: r.ID, Revision: r.Revision, Online: r.Online, Label: r.Label, Role: r.Role, Platform: r.Hello.Platform, Capabilities: r.Hello.Capabilities, Removing: r.Removing, SealKey: r.Hello.SealKey}
352 if !r.SeenAt.IsZero() {
353 at := r.SeenAt
354 v.Since = &at
355 }
356 return v
357}
358
359// runnerLabel names a runner for people ("" when unknown).
360func (t *txn) runnerLabel(id string) string {
361 if id == "" {
362 return ""
363 }
364 var labels []string
365 _ = t.db.Raw(`SELECT coalesce(label, '') FROM runners WHERE id = ?`, id).Scan(&labels).Error
366 var sess runnerSessionRecord
367 if t.db.Where("runner_id = ?", id).First(&sess).Error == nil && sess.Hello != "" {
368 var h wire.Hello
369 if json.Unmarshal([]byte(sess.Hello), &h) == nil && h.Label != "" {
370 return h.Label
371 }
372 }
373 if len(labels) == 1 {
374 return labels[0]
375 }
376 return ""
377}
378
379// phaseCommitted is a worker's Engineering report that its candidate is
380// committed (not pushed): the outbound transfer opens for it.
381const phaseCommitted = "committed"
382
383// WithdrawAfter is how long a worker holding a step must be offline
384// before the step is withdrawn for another runner that fits: a brief
385// disconnect cancels nothing.
386const WithdrawAfter = 2 * time.Minute
387
388// OfflineLimit is how long a step waits for the only runner that fits
389// before checks resolve as not run (runner_offline), and Mac Engineering
390// waiting for its Mac needs the person (still waiting).
391const OfflineLimit = 30 * time.Minute
392
393// reasonRunnerOffline: the runner a step needs was offline too long.
394const reasonRunnerOffline = "runner_offline"
395
396// checksNeeds are the tags checks of the task's newest candidate need:
397// macOS and Xcode when the change touched Apple files or the
398// repository's gate needs Xcode (the primary's index says so), and the
399// iOS simulator when the repository has a shared scheme. The change is
400// every Engineering round of the task, not only the one whose commit is
401// the candidate: a later round, or a delegated Copy commit, makes a new
402// candidate that still holds an earlier round's Apple files. Retired
403// rounds (a task moved to another project) are not the candidate's.
404func (t *txn) checksNeeds(k taskRecord, s stepRecord) ([]string, error) {
405 var apple int64
406 if err := t.db.Model(&stepRecord{}).Where("task_id = ? AND specialist = ? AND apple = ? AND coalesce(retired, 0) = 0", k.ID, wire.SpecialistEngineering, true).Count(&apple).Error; err != nil {
407 return nil, err
408 }
409 info, err := t.repoInfo(k, s.Person)
410 if err != nil {
411 return nil, err
412 }
413 return macNeeds(apple > 0 || info.NeedsMacOS, info), nil
414}
415
416// engineeringNeeds are the tags Engineering of the task needs: macOS and
417// Xcode (and the simulator) when the repository's gate needs Xcode, as
418// the primary's index of its default branch says (the base, not anything
419// the change wrote), and claude to make the change there (slice F). The
420// task's recorded Mac need (MacNeeds) comes first: the catalog can add
421// to it, never take it away. Anything else needs nothing.
422func (t *txn) engineeringNeeds(k taskRecord, person string) ([]string, error) {
423 info, err := t.repoInfo(k, person)
424 if err != nil {
425 return nil, err
426 }
427 needs := decodeList(k.MacNeeds)
428 for _, tag := range macNeeds(info.NeedsMacOS, info) {
429 if !slices.Contains(needs, tag) {
430 needs = append(needs, tag)
431 }
432 }
433 if len(needs) > 0 {
434 needs = append(needs, wire.TagClaude)
435 }
436 return needs, nil
437}
438
439// recordMacNeeds records, the first time placement finds the task's
440// Engineering needs a Mac, which Mac tags it needs, in the placement's
441// transaction. Never cleared or changed after.
442func (t *txn) recordMacNeeds(k *taskRecord, needs []string) error {
443 mac := macTags(needs)
444 if k.MacNeeds != "" || len(mac) == 0 {
445 return nil
446 }
447 k.MacNeeds = encodeList(mac)
448 return t.db.Model(&taskRecord{}).Where("id = ? AND coalesce(mac_needs, '') = ''", k.ID).Update("mac_needs", k.MacNeeds).Error
449}
450
451// macTags are needs without claude: what makes a runner a Mac for them.
452func macTags(needs []string) []string {
453 return slices.DeleteFunc(slices.Clone(needs), func(t string) bool { return t == wire.TagClaude })
454}
455
456// repoInfo is the primary's catalog entry for the task's repository
457// (zero when it has none).
458func (t *txn) repoInfo(k taskRecord, person string) (wire.RepoInfo, error) {
459 var p projectRecord
460 if err := t.db.Where("id = ?", k.ProjectID).First(&p).Error; err != nil {
461 return wire.RepoInfo{}, err
462 }
463 h, err := t.hello(person)
464 if err != nil {
465 return wire.RepoInfo{}, err
466 }
467 var info wire.RepoInfo
468 for _, r := range h.Catalog {
469 if r.Repo == p.Repo {
470 info = r
471 }
472 }
473 return info, nil
474}
475
476func macNeeds(mac bool, info wire.RepoInfo) []string {
477 if !mac {
478 return []string{}
479 }
480 needs := []string{wire.TagMacOS, wire.TagXcode}
481 if info.Simulator {
482 needs = append(needs, wire.TagIOSSimulator)
483 }
484 return needs
485}
486
487// waitForMac leaves Mac work waiting (placed false): for a Mac runner to
488// be added (waiting_mac), or, placement, for the reason it names.
489func (t *txn) waitForMac(s *stepRecord, needs []string, placement string) (bool, error) {
490 now := t.now()
491 s.Needs, s.RunnerID, s.Placement, s.WaitingSince = encodeList(needs), "", placement, &now
492 return false, nil
493}
494
495func decodeList(raw string) []string {
496 out := []string{}
497 if raw != "" {
498 _ = json.Unmarshal([]byte(raw), &out)
499 }
500 return out
501}
502
503func encodeList(v []string) string {
504 if len(v) == 0 {
505 return ""
506 }
507 raw, _ := json.Marshal(v)
508 return string(raw)
509}
510
511// place chooses the runner for a step's current attempt (Mac runners spec
512// §1.4). Checks are placed by their needs; Review and merges run on the
513// primary; Engineering runs on the primary (pinned there for the task)
514// unless it is Mac work, which engineeringPlace places (on a Mac worker
515// with EQUIPO_MAC_ENGINEERING, slice F). Mac work never runs on a Linux
516// primary (2026-11-28): checks that need macOS with no enrolled runner
517// that fits wait for a Mac runner (waiting_mac, the person's to add), and
518// so does Engineering for a repository whose gate needs Xcode. Among the person's
519// runners whose tags cover the needs: the primary if it does, else the
520// online worker running fewest steps, ties by enrolment order. A fitting
521// runner that is offline leaves the step waiting (placed false). When the
522// primary cannot relay a pack (protocol 1), the step goes to the primary
523// without needs and ends honestly there (needs_macos), as before. A Mac
524// whose sandbox is not proven gets checks only with the person's choice
525// for this attempt on it (macsandbox.go); when it is the only one online
526// that fits, the step waits for its sandbox (placed false).
527func (t *txn) place(k *taskRecord, s *stepRecord) (placed bool, err error) {
528 primary, err := t.s.authority.PrimaryRunner(t.db, s.Person)
529 if err != nil {
530 return false, err
531 }
532 s.Placement, s.WaitingSince, s.SandboxRunner = "", nil, ""
533 switch s.Specialist {
534 case wire.SpecialistEngineering:
535 return t.placeEngineering(k, s, primary)
536 case wire.SpecialistChecks:
537 default:
538 s.Needs, s.RunnerID = "", primary
539 return true, nil
540 }
541 needs, err := t.checksNeeds(*k, *s)
542 if err != nil {
543 return false, err
544 }
545 s.Needs = encodeList(needs)
546 s.RunnerID = primary
547 if len(needs) == 0 {
548 return true, nil
549 }
550 rs, err := t.runners(s.Person)
551 if err != nil {
552 return false, err
553 }
554 refused := decodeList(s.RefusedBy)
555 var fit []runnerInfo
556 relay := false
557 for _, r := range rs {
558 if r.ID == primary && r.Protocol >= wire.Protocol2 {
559 relay = true
560 }
561 if r.fits(needs, refused) {
562 fit = append(fit, r)
563 }
564 }
565 if len(fit) == 0 {
566 // No runner can, and none is enrolled that could: the checks wait
567 // for a Mac runner instead of the Linux primary judging them
568 // needs_macos, whatever its protocol.
569 return t.waitForMac(s, needs, wire.PlacementMac)
570 }
571 if !relay {
572 // A Mac is enrolled but an older primary cannot relay a pack to
573 // it: the checks wait for a runner (the primary's update), and
574 // resolve as not run after the offline limit, as for an offline
575 // Mac. Never judged on the Linux primary.
576 now := t.now()
577 s.RunnerID, s.Placement, s.WaitingSince = "", wire.PlacementWaiting, &now
578 return false, nil
579 }
580 var chosen, unproven *runnerInfo
581 for i := range fit {
582 r := &fit[i]
583 ok := r.sandboxProven()
584 if !ok {
585 // Outside the sandbox only by the creator's choice, and never on
586 // a Mac holding a model credential (D1).
587 if ok, err = t.unsandboxedOK(*s, r.ID); err != nil {
588 return false, err
589 }
590 }
591 if !ok {
592 if r.Online && unproven == nil {
593 unproven = r
594 }
595 continue
596 }
597 switch {
598 case r.ID == primary:
599 chosen = r
600 case !r.Online:
601 case chosen == nil || chosen.ID != primary && r.Running < chosen.Running:
602 chosen = r
603 }
604 if chosen != nil && chosen.ID == primary {
605 break
606 }
607 }
608 if chosen == nil {
609 now := t.now()
610 s.RunnerID, s.Placement, s.WaitingSince = "", wire.PlacementWaiting, &now
611 if unproven != nil {
612 s.Placement, s.SandboxRunner = wire.PlacementSandbox, unproven.ID
613 }
614 return false, nil
615 }
616 s.RunnerID = chosen.ID
617 return true, nil
618}
619
620// engineeringPlacement is where Engineering's current attempt goes, as
621// decided without writing anything: on runner, or waiting (placement)
622// for waitFor, with needs.
623type engineeringPlacement struct {
624 runner, placement, waitFor string
625 needs []string
626 // want: everything the task's Engineering needs (whoever takes it).
627 want []string
628}
629
630// placeEngineering places Engineering's attempt (placeEngineering's
631// decision, engineeringPlace). On a worker, the attempt's base must be
632// bound first: with none (a first step, or a rebase round whose new tip
633// is unknown) the primary is asked for it and the attempt waits
634// (waiting_base, base_prepare.go). Placed, the task is pinned to the
635// runner, on the task value the transaction carries so its next save
636// keeps the pin.
637func (t *txn) placeEngineering(k *taskRecord, s *stepRecord, primary string) (bool, error) {
638 d, err := t.engineeringPlace(*k, *s, primary)
639 if err != nil {
640 return false, err
641 }
642 // Mac work from now on, whatever the catalog, a pin or a removal
643 // later says.
644 if err := t.recordMacNeeds(k, d.want); err != nil {
645 return false, err
646 }
647 if s.State == wire.StepQueued && s.Reason == reasonRunnerOffline {
648 // The wait for an offline Mac is over or starts again.
649 s.Reason = ""
650 }
651 if d.placement != "" {
652 _, err := t.waitForMac(s, d.needs, d.placement)
653 s.SandboxRunner = d.waitFor
654 return false, err
655 }
656 s.Needs, s.RunnerID = "", d.runner
657 if d.runner == "" {
658 // No runner at all (no primary): dispatchStep has it wait.
659 return true, nil
660 }
661 if d.runner != primary {
662 if boundBase(*k, *s) == "" {
663 return false, t.prepareBase(k, s, primary, d)
664 }
665 s.Needs = encodeList(d.needs)
666 }
667 if k.EngineeringRunner != d.runner {
668 k.EngineeringRunner = d.runner
669 if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Update("engineering_runner", d.runner).Error; err != nil {
670 return false, err
671 }
672 }
673 return true, nil
674}
675
676// engineeringPlace decides where Engineering of the task runs (Mac
677// runners spec §1.4, §8.5). Work that is not Mac work, and not pinned to
678// a worker, runs on the primary. Mac work never runs on a Linux primary:
679// a primary that is a Mac takes it; otherwise, with EQUIPO_MAC_ENGINEERING
680// unset, it waits as mac-placement-wait left it (waiting_mac with no Mac
681// that fits, waiting_mac_engineering with one). Set, the candidates are
682// the pinned worker (enrolled, not removing) alone, else the workers that
683// are Macs for the needs, in §1.4's order. Each must speak protocol 37,
684// and so must the primary (waiting_mac_update, naming the one that does
685// not); a Mac without claude waits for it (waiting_mac_connection, whose
686// status says why); an offline one is waited for (waiting_runner). A
687// pinned worker that lost a tag is waited for, never replaced. An older
688// primary (protocol 1) is no exception.
689func (t *txn) engineeringPlace(k taskRecord, s stepRecord, primary string) (engineeringPlacement, error) {
690 needs, err := t.engineeringNeeds(k, s.Person)
691 if err != nil {
692 return engineeringPlacement{}, err
693 }
694 d, err := t.engineeringDecide(k, s, primary, needs)
695 d.want = needs
696 return d, err
697}
698
699func (t *txn) engineeringDecide(k taskRecord, s stepRecord, primary string, needs []string) (engineeringPlacement, error) {
700 if len(needs) == 0 && (k.EngineeringRunner == "" || k.EngineeringRunner == primary) {
701 return engineeringPlacement{runner: primary}, nil
702 }
703 rs, err := t.runners(s.Person)
704 if err != nil {
705 return engineeringPlacement{}, err
706 }
707 var pin, prim *runnerInfo
708 for i := range rs {
709 switch r := &rs[i]; {
710 case r.ID == primary:
711 prim = r
712 case r.ID == k.EngineeringRunner && r.Role == wire.RoleWorker && !r.Removing:
713 pin = r
714 }
715 }
716 if len(needs) == 0 && pin == nil {
717 return engineeringPlacement{runner: primary}, nil
718 }
719 if !t.s.macEngineering.Load() {
720 // As mac-placement-wait left it: a Mac's tags, without claude.
721 mac := macTags(needs)
722 fit := false
723 for _, r := range rs {
724 if r.fits(mac, nil) {
725 if r.ID == primary {
726 return engineeringPlacement{runner: primary}, nil
727 }
728 fit = true
729 }
730 }
731 if !fit {
732 return engineeringPlacement{placement: wire.PlacementMac, needs: mac}, nil
733 }
734 return engineeringPlacement{placement: wire.PlacementMacEngineering, needs: mac}, nil
735 }
736 mac := macTags(needs)
737 if prim == nil {
738 return engineeringPlacement{placement: wire.PlacementWaiting, needs: needs}, nil
739 }
740 if pin == nil && len(mac) > 0 && prim.fits(needs, nil) {
741 // A primary that is a Mac takes it.
742 return engineeringPlacement{runner: primary}, nil
743 }
744 // readiness is what keeps worker r from taking it now ("" when
745 // nothing does) and the runner it waits for.
746 readiness := func(r runnerInfo) (string, string) {
747 switch {
748 case r.Protocol < wire.ProtocolMacEngineering:
749 return wire.PlacementMacUpdate, r.ID
750 case prim.Protocol < wire.ProtocolMacEngineering:
751 return wire.PlacementMacUpdate, prim.ID
752 case !wire.Covers(r.tags(), needs):
753 return wire.PlacementMacConnection, r.ID
754 case !r.Online:
755 return wire.PlacementWaiting, r.ID
756 }
757 return "", r.ID
758 }
759 if pin != nil {
760 if !macFor(*pin, mac) {
761 // It lost what makes it a Mac for this: wait for it.
762 return engineeringPlacement{placement: wire.PlacementWaiting, waitFor: pin.ID, needs: needs}, nil
763 }
764 if why, who := readiness(*pin); why != "" {
765 return engineeringPlacement{placement: why, waitFor: who, needs: needs}, nil
766 }
767 return engineeringPlacement{runner: pin.ID, needs: needs}, nil
768 }
769 var chosen *runnerInfo
770 first := map[string]string{}
771 for i := range rs {
772 r := &rs[i]
773 if r.Role != wire.RoleWorker || r.Removing || !macFor(*r, mac) {
774 continue
775 }
776 why, who := readiness(*r)
777 switch {
778 case why == "" && (chosen == nil || r.Running < chosen.Running):
779 chosen = r
780 case why != "" && first[why] == "":
781 first[why] = who
782 }
783 }
784 if chosen != nil {
785 return engineeringPlacement{runner: chosen.ID, needs: needs}, nil
786 }
787 for _, why := range []string{wire.PlacementWaiting, wire.PlacementMacConnection, wire.PlacementMacUpdate} {
788 if who := first[why]; who != "" {
789 return engineeringPlacement{placement: why, waitFor: who, needs: needs}, nil
790 }
791 }
792 return engineeringPlacement{placement: wire.PlacementMac, needs: needs}, nil
793}
794
795// macFor reports whether r is a runner for work with tags at all
796// (protocol 2, tags covered).
797func macFor(r runnerInfo, tags []string) bool {
798 return r.Protocol >= wire.Protocol2 && wire.Covers(r.tags(), tags)
799}
800
801// restartMacEngineering: whether the unstarted Engineering attempt s is
802// not where placement would put it now (Mac work its runner cannot take,
803// or a worker that can no longer take it); if so the attempt is ended and
804// the next one placed (it waits, or goes where it now fits). A finished
805// or cancelled task's attempt is not replaced (its cancellation is on
806// the way), but it does not start either.
807func (t *txn) restartMacEngineering(s *stepRecord) (bool, error) {
808 k, err := t.loadTask(s.TaskID)
809 if err != nil {
810 return false, err
811 }
812 primary, err := t.s.authority.PrimaryRunner(t.db, s.Person)
813 if err != nil {
814 return false, err
815 }
816 d, err := t.engineeringPlace(k, *s, primary)
817 if err != nil || d.runner == s.RunnerID {
818 return false, err
819 }
820 if wire.FinalStage(k.Stage) || k.CancelRequested {
821 return true, nil
822 }
823 if err := t.replace(&k, s); err != nil {
824 return false, err
825 }
826 return true, t.saveStep(s, &k)
827}
828
829// recheckMacEngineering places again the runner's queued Engineering
830// attempts that are Mac work it cannot take and that it has not been
831// given yet (the dispatch not acknowledged): one queued before Mac work
832// waited for a Mac, or before the catalog said the gate needs Xcode. A
833// protocol 2 runner's start authorization checks the ones it was given;
834// an older runner asks for none, and one it holds is left with it, as
835// before, rather than lose track of an attempt it may run.
836func (t *txn) recheckMacEngineering(runner string) error {
837 var rows []stepRecord
838 if err := t.db.Where("runner_id = ? AND specialist = ? AND state = ? AND started_at IS NULL AND coalesce(withdrawn, 0) = 0", runner, wire.SpecialistEngineering, wire.StepQueued).Find(&rows).Error; err != nil {
839 return err
840 }
841 for i := range rows {
842 s := rows[i]
843 var undelivered int64
844 if err := t.db.Model(&commandRecord{}).Where("runner_id = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", s.RunnerID, wire.FrameDispatch, `%"step_id":"`+s.ID+`","attempt":`+itoa64(s.Attempt)+`,%`).Count(&undelivered).Error; err != nil {
845 return err
846 }
847 if undelivered == 0 {
848 continue
849 }
850 if _, err := t.restartMacEngineering(&s); err != nil {
851 return err
852 }
853 }
854 return nil
855}
856
857// replace ends the current attempt's placement and places the next one:
858// after a refusal, a withdrawal before it started, or a withdrawn
859// attempt's termination. The caller saves s.
860func (t *txn) replace(k *taskRecord, s *stepRecord) error {
861 if err := t.voidAttempt(*s); err != nil {
862 return err
863 }
864 if s.Specialist == wire.SpecialistPreview && s.StartedAt != nil {
865 // A preview attempt that started may have published: no
866 // replacement ever runs after it (settlePreview).
867 return t.settlePreview(k, s)
868 }
869 if s.Specialist == wire.SpecialistPublish && s.StartedAt != nil {
870 // Nor a publish attempt that started (settlePublish).
871 return t.settlePublish(k, s)
872 }
873 s.Attempt++
874 s.State, s.Reason, s.Terminated, s.StartedAt, s.FinishedAt, s.Withdrawn, s.TerminationKind = wire.StepQueued, "", false, nil, nil, false, ""
875 s.Summary, s.LogTail, s.Checks, s.Gate, s.ExitCode, s.Output = "", "", "", "", nil, ""
876 return t.dispatchStep(k, s)
877}
878
879// voidAttempt makes sure nothing of an attempt is served again: its
880// unacked dispatch and the chunks of its transfers.
881func (t *txn) voidAttempt(s stepRecord) error {
882 if err := t.db.Model(&commandRecord{}).Where("runner_id = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", s.RunnerID, wire.FrameDispatch, attemptLike(s.ID, s.Attempt)).Update("acked_at", t.now()).Error; err != nil {
883 return err
884 }
885 // Its unanswered prepare_base too: the primary need not resolve it.
886 if err := t.db.Model(&commandRecord{}).Where("kind = ? AND acked_at IS NULL AND body LIKE ?", wire.FramePrepareBase, attemptLike(s.ID, s.Attempt)).Update("acked_at", t.now()).Error; err != nil {
887 return err
888 }
889 return t.closeTransfers(s.ID, s.Attempt)
890}
891
892// withdraw takes an attempt back from its runner, serialised with its
893// start authorization by the write transaction: not started, it can never
894// start (the attempt moves on) and the next one is placed at once;
895// started, the runner is asked to cancel it and the next attempt is placed
896// only once its termination is reported, as Retry requires.
897func (t *txn) withdraw(k *taskRecord, s *stepRecord) error {
898 if s.Withdrawn || wire.StepTerminal(s.State) {
899 return nil
900 }
901 if s.StartedAt == nil {
902 if err := t.replace(k, s); err != nil {
903 return err
904 }
905 return t.saveStep(s, k)
906 }
907 s.Withdrawn = true
908 if err := t.saveStep(s, k); err != nil {
909 return err
910 }
911 return t.commandTo(s.RunnerID, s.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt})
912}
913
914// Authorize is the start authorization of one step attempt (a protocol 2
915// lease naming it): granted only to the runner the attempt is placed on,
916// while it is current and not withdrawn, and the first grant records that
917// it started. Refused is the reason a lease is refused, "" when granted.
918//
919// A Research step's lease rechecks the grant it was dispatched under
920// (authorizeResearch), on every call. Any other step bound to a data
921// specialist, and every maker step of a task with one, is granted only
922// while its binding equals grantFor for its task's project, its start
923// and each page_render check alike (authorizeSpecialist); page_render
924// needs page.render in that binding. A purpose unknown for the step is
925// refused.
926//
927// A merge step's lease is also merge authority's (authorizeMergeLease):
928// an automatic merge on a connection below wire.ProtocolMergeFacts is
929// refused, and purpose merge_request decides the merge again, right before
930// the hub request, on every call.
931func (s *Store) Authorize(ctx context.Context, l Lease, stepID string, attempt int64, purpose, digest, destination string) (refused string, err error) {
932 err = s.tx(ctx, func(t *txn) error {
933 if _, err := t.current(l); err != nil {
934 return err
935 }
936 var st stepRecord
937 if err := t.db.Where("id = ? AND person = ?", stepID, l.Runner.Person).First(&st).Error; errors.Is(err, gorm.ErrRecordNotFound) {
938 refused = "withdrawn"
939 return nil
940 } else if err != nil {
941 return err
942 }
943 if st.Attempt != attempt || st.RunnerID != l.Runner.RunnerID || st.Withdrawn || wire.StepTerminal(st.State) {
944 refused = "withdrawn"
945 return nil
946 }
947 // A purpose this instance does not check for this step is refused,
948 // never taken for a start check.
949 if !leasePurposeKnown(st.Specialist, purpose) {
950 refused = "withdrawn"
951 return nil
952 }
953 if st.Specialist != wire.SpecialistResearch {
954 r, err := t.authorizeSpecialist(l, st, purpose)
955 if err != nil || r != "" {
956 refused = r
957 return err
958 }
959 }
960 if st.Specialist == wire.SpecialistMerge {
961 r, err := t.authorizeMergeLease(l, &st, purpose)
962 if err != nil || r != "" {
963 refused = r
964 return err
965 }
966 }
967 if st.Specialist == wire.SpecialistCopy {
968 if err := t.authorizeCopy(st); err != nil {
969 refused = "withdrawn"
970 return nil
971 }
972 }
973 if st.Specialist == wire.SpecialistResearch {
974 r, err := t.authorizeResearch(&st)
975 if err != nil || r != "" {
976 refused = r
977 return err
978 }
979 }
980 if st.Specialist == wire.SpecialistPreview {
981 r, err := t.authorizePreview(l, &st, purpose, digest)
982 if err != nil || r != "" {
983 refused = r
984 return err
985 }
986 } else if purpose == wire.LeasePurposePreview {
987 refused = "withdrawn"
988 return nil
989 }
990 if st.Specialist == wire.SpecialistPublish {
991 r, err := t.authorizePublish(l, &st, purpose, digest, destination)
992 if err != nil || r != "" {
993 refused = r
994 return err
995 }
996 } else if purpose == wire.LeasePurposePublish || purpose == wire.LeasePurposeMint {
997 refused = "withdrawn"
998 return nil
999 }
1000 if st.StartedAt != nil {
1001 return nil
1002 }
1003 // The start of a step of a held job, or one whose person can't
1004 // have building done: refused here, where the start would be
1005 // recorded, so it never starts; a step already started keeps its
1006 // grant and finishes (abilities §6.3).
1007 if held, err := t.stepHeld(st); err != nil || held {
1008 if err != nil {
1009 return err
1010 }
1011 // Settled now, as not started: a Carry on that comes before
1012 // the runner reports it gives it a fresh attempt all the same.
1013 k, err := t.loadTask(st.TaskID)
1014 if err != nil {
1015 return err
1016 }
1017 now := t.now()
1018 st.State, st.Reason, st.Terminated, st.FinishedAt, st.AbilityHeld = wire.StepCancelled, "cancelled", true, &now, true
1019 if err := t.saveStep(&st, &k); err != nil {
1020 return err
1021 }
1022 refused = wire.CodeAbilityOff
1023 return nil
1024 }
1025 if st.Specialist == wire.SpecialistEngineering {
1026 // Placement is decided again before Engineering starts: one
1027 // dispatched to the Linux primary before Mac work waited for a
1028 // Mac (an instance upgraded with it queued), or before the
1029 // catalog said the gate needs Xcode, does not start there.
1030 mac, err := t.restartMacEngineering(&st)
1031 if err != nil || mac {
1032 refused = "withdrawn"
1033 return err
1034 }
1035 }
1036 now := t.now()
1037 return t.db.Model(&stepRecord{}).Where("id = ? AND attempt = ?", st.ID, st.Attempt).Update("started_at", now).Error
1038 })
1039 return refused, err
1040}
1041
1042// waitingPlacements are the placements of a step waiting to be placed,
1043// a runner that can run Design's among them. A Design step the autonomy
1044// limit held goes only once its person acts (releaseDesignHeld).
1045// waiting_base is not one: the attempt waits for the primary's base
1046// report, never placed again meanwhile (base_prepare.go).
1047var waitingPlacements = []string{wire.PlacementWaiting, wire.PlacementSandbox, wire.PlacementMac, wire.PlacementMacEngineering, wire.PlacementMacConnection, wire.PlacementMacUpdate, wire.PlacementDesign}
1048
1049// placeWaiting places the person's steps waiting for a runner, when one
1050// that fits may have come online or been added, or for a Mac's sandbox,
1051// when it may be proven now, or for a runner that can run Design.
1052func (t *txn) placeWaiting(person string) error {
1053 var rows []stepRecord
1054 if err := t.db.Where("person = ? AND placement IN ? AND state = ?", person, waitingPlacements, wire.StepQueued).Order("created_at").Find(&rows).Error; err != nil {
1055 return err
1056 }
1057 for i := range rows {
1058 s := rows[i]
1059 k, err := t.loadTask(s.TaskID)
1060 if err != nil {
1061 return err
1062 }
1063 if wire.FinalStage(k.Stage) || k.CancelRequested {
1064 continue
1065 }
1066 since, was, mac, why := s.WaitingSince, s.Placement, s.SandboxRunner, s.Reason
1067 if err := t.dispatchStep(&k, &s); err != nil {
1068 return err
1069 }
1070 if s.Placement == was && s.SandboxRunner == mac && s.Reason == why {
1071 // Still waiting: the clock does not restart.
1072 s.WaitingSince = since
1073 if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Update("waiting_since", since).Error; err != nil {
1074 return err
1075 }
1076 continue
1077 }
1078 if err := t.saveStep(&s, &k); err != nil {
1079 return err
1080 }
1081 }
1082 return nil
1083}
1084
1085// Place runs placement for every person: steps waiting for a runner are
1086// placed when one that fits is online; checks that waited OfflineLimit
1087// resolve as not run (runner_offline, never a pass) and review goes on;
1088// a step placed on a worker that went offline is withdrawn when another
1089// runner that fits is online. The instance runs it every minute.
1090func (s *Store) Place(ctx context.Context) error {
1091 return s.tx(ctx, func(t *txn) error {
1092 var persons []string
1093 if err := t.db.Model(&stepRecord{}).Where("state IN ? AND (placement IN ? OR runner_id IN (SELECT id FROM runners WHERE role = ?))", []string{wire.StepQueued, wire.StepRunning}, waitingPlacements, wire.RoleWorker).Distinct().Pluck("person", &persons).Error; err != nil {
1094 return err
1095 }
1096 for _, p := range persons {
1097 if err := t.placeWaiting(p); err != nil {
1098 return err
1099 }
1100 if err := t.offline(p); err != nil {
1101 return err
1102 }
1103 }
1104 // A task whose maker no longer acts for its project is asked
1105 // about once its Design attempts have ended (design_routing.go).
1106 return t.offerRecoveriesAll()
1107 })
1108}
1109
1110// offline applies the offline rule to the person's checks, and to Mac
1111// Engineering waiting for its Mac (offlineEngineering).
1112func (t *txn) offline(person string) error {
1113 if err := t.offlineEngineering(person); err != nil {
1114 return err
1115 }
1116 rs, err := t.runners(person)
1117 if err != nil {
1118 return err
1119 }
1120 byID := map[string]runnerInfo{}
1121 for _, r := range rs {
1122 byID[r.ID] = r
1123 }
1124 var rows []stepRecord
1125 if err := t.db.Where("person = ? AND specialist = ? AND state IN ?", person, wire.SpecialistChecks, []string{wire.StepQueued, wire.StepRunning}).Find(&rows).Error; err != nil {
1126 return err
1127 }
1128 for i := range rows {
1129 s := rows[i]
1130 k, err := t.loadTask(s.TaskID)
1131 if err != nil {
1132 return err
1133 }
1134 if wire.FinalStage(k.Stage) || k.CancelRequested || s.Withdrawn || s.Placement == wire.PlacementSandbox {
1135 // Waiting for a Mac's sandbox is not a runner offline: it waits
1136 // until the sandbox is proven or the person chooses.
1137 continue
1138 }
1139 if s.Placement == wire.PlacementWaiting {
1140 if s.WaitingSince != nil && t.now().Sub(*s.WaitingSince) >= OfflineLimit {
1141 if err := t.resolveOffline(&k, &s); err != nil {
1142 return err
1143 }
1144 }
1145 continue
1146 }
1147 r, ok := byID[s.RunnerID]
1148 if !ok || r.Role != wire.RoleWorker || r.Online {
1149 continue
1150 }
1151 // Placed on a worker that is offline: withdraw it if another
1152 // runner that fits is online now, or once it has been offline for
1153 // the limit (the next attempt then waits, or resolves).
1154 alt := false
1155 for _, o := range rs {
1156 if o.ID != r.ID && o.Online && !o.Removing && o.Protocol >= wire.Protocol2 && wire.Covers(o.tags(), decodeList(s.Needs)) && !slices.Contains(decodeList(s.RefusedBy), o.ID) {
1157 alt = true
1158 }
1159 }
1160 away := t.now().Sub(r.SeenAt)
1161 if alt && away >= WithdrawAfter || away >= OfflineLimit {
1162 if err := t.withdraw(&k, &s); err != nil {
1163 return err
1164 }
1165 if s.Placement == wire.PlacementWaiting && !alt {
1166 // It waited for that runner already.
1167 seen := r.SeenAt
1168 if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Update("waiting_since", seen).Error; err != nil {
1169 return err
1170 }
1171 }
1172 }
1173 }
1174 return nil
1175}
1176
1177// offlineEngineering: Mac Engineering that has waited OfflineLimit for
1178// the only Mac that can take it keeps waiting and needs the person
1179// (runner_offline). It is never resolved and never moves to Linux;
1180// Cancel stays available.
1181func (t *txn) offlineEngineering(person string) error {
1182 var rows []stepRecord
1183 if err := t.db.Where("person = ? AND specialist = ? AND state = ? AND placement = ? AND coalesce(sandbox_runner, '') <> '' AND coalesce(reason, '') = ''", person, wire.SpecialistEngineering, wire.StepQueued, wire.PlacementWaiting).Find(&rows).Error; err != nil {
1184 return err
1185 }
1186 for i := range rows {
1187 s := rows[i]
1188 if s.WaitingSince == nil || t.now().Sub(*s.WaitingSince) < OfflineLimit {
1189 continue
1190 }
1191 k, err := t.loadTask(s.TaskID)
1192 if err != nil {
1193 return err
1194 }
1195 if wire.FinalStage(k.Stage) || k.CancelRequested {
1196 continue
1197 }
1198 s.Reason = reasonRunnerOffline
1199 if err := t.saveStep(&s, &k); err != nil {
1200 return err
1201 }
1202 }
1203 return nil
1204}
1205
1206// resolveOffline ends waiting checks honestly: not run, the runner was
1207// offline. Review proceeds on the candidate.
1208func (t *txn) resolveOffline(k *taskRecord, s *stepRecord) error {
1209 now := t.now()
1210 s.State, s.Checks, s.Reason, s.Gate, s.ExitCode, s.Terminated, s.FinishedAt, s.Placement = wire.StepDone, wire.ChecksCannotRun, "runner_offline", "", nil, true, &now, ""
1211 s.LogTail = "Not run: the runner that can check this change was offline."
1212 if err := t.saveStep(s, k); err != nil {
1213 return err
1214 }
1215 return t.advance(k)
1216}
1217
1218// RunnerList is GET /api/v1/runners: the person's runners.
1219func (s *Store) RunnerList(ctx context.Context, person string) (out wire.RunnerList, err error) {
1220 err = s.read(ctx, func(tx *gorm.DB) error {
1221 if err := s.authority.CurrentPerson(ctx, tx); err != nil {
1222 return err
1223 }
1224 out.Items, err = (&txn{s: s, db: tx}).runnerViews(person)
1225 return err
1226 })
1227 return out, err
1228}
1229
1230func (t *txn) runnerViews(person string) ([]wire.Runner, error) {
1231 rs, err := t.runners(person)
1232 if err != nil {
1233 return nil, err
1234 }
1235 out := make([]wire.Runner, 0, len(rs))
1236 for _, r := range rs {
1237 out = append(out, runnerView(r))
1238 }
1239 slices.SortStableFunc(out, func(a, b wire.Runner) int {
1240 if a.Role == b.Role {
1241 return 0
1242 }
1243 if a.Role == wire.RolePrimary {
1244 return -1
1245 }
1246 return 1
1247 })
1248 return out, nil
1249}
1250