oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "database/sql"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "log/slog"
10 "strings"
11 "sync"
12 "time"
13
14 "amadan.net/oficina/equipo/internal/runner/containment"
15 "amadan.net/oficina/equipo/internal/runner/metered"
16 "amadan.net/oficina/equipo/internal/runner/provider"
17 "amadan.net/oficina/equipo/internal/wire"
18)
19
20// stepSchema holds the step attempts this runner was sent. At most one
21// attempt of a task runs at a time (the partial unique index).
22const stepSchema = `
23CREATE TABLE IF NOT EXISTS steps (step_id TEXT NOT NULL, attempt INTEGER NOT NULL, task_id TEXT NOT NULL, person TEXT NOT NULL, body TEXT NOT NULL, state TEXT NOT NULL, cancel INTEGER NOT NULL DEFAULT 0, phase TEXT NOT NULL DEFAULT '', base_sha TEXT NOT NULL DEFAULT '', candidate_sha TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL, PRIMARY KEY (step_id, attempt));
24CREATE UNIQUE INDEX IF NOT EXISTS steps_running ON steps(task_id) WHERE state='running';
25`
26
27// runPending is an attempt that ended without a verified exit: its final
28// report went out without termination, and a follow-up carries the proof
29// once a probe verifies the namespace's exit.
30const runPending = "pending"
31
32// Step phases while running: nothing ran yet, the specialist runs, the
33// runner committed the candidate (only publishing is left). An
34// Engineering commit can carry how its step finished, which its pushed
35// report says (committedReason): it ran out of time (the work so far),
36// or it was a fix round without a working shell. The phase stays on the
37// attempt's row, so a restart and a republish of a failed push say it
38// too.
39const (
40 phaseNone = ""
41 phaseRunning = "running"
42 phaseCommitted = "committed"
43 phaseCommittedUnfinished = "committed_unfinished"
44 phaseCommittedNoShell = "committed_no_shell"
45)
46
47// committed: only publishing is left of the attempt.
48func committed(phase string) bool {
49 return phase == phaseCommitted || committedReason(phase) != ""
50}
51
52// committedReason is the reason a pushed report of a commit in phase
53// carries ("" for none).
54func committedReason(phase string) string {
55 switch phase {
56 case phaseCommittedUnfinished:
57 return "step_timeout"
58 case phaseCommittedNoShell:
59 return wire.ReasonShellUnavailable
60 }
61 return ""
62}
63
64// stepPhase is the phase an attempt of a step was left in ("" when the
65// runner has no such attempt).
66func (s *State) stepPhase(ctx context.Context, stepID string, attempt int64) (string, error) {
67 var phase sql.NullString
68 err := s.db.QueryRowContext(ctx, "SELECT phase FROM steps WHERE step_id=? AND attempt=?", stepID, attempt).Scan(&phase)
69 if errors.Is(err, sql.ErrNoRows) {
70 return "", nil
71 }
72 return phase.String, err
73}
74
75// stepRow is one step attempt held by this runner.
76type stepRow struct {
77 wire.DispatchCommand
78 State, Phase, Base, Candidate string
79 Cancel bool
80 // Created orders steps and questions in the engine's one queue.
81 Created string
82 // Question: a question's tree (StepID is the question's id). It is
83 // not a step attempt, so it takes the plain execution lease.
84 Question bool
85}
86
87func (r stepRow) key() string { return r.StepID + "/" + itoa(r.Attempt) }
88
89// AcceptDispatch records a dispatch exactly once; the caller acks after.
90func (s *State) AcceptDispatch(ctx context.Context, frameID string, d wire.DispatchCommand) error {
91 raw, _ := json.Marshal(d)
92 return s.tx(ctx, func(t *sql.Tx) error {
93 fresh, err := seen(t, frameID)
94 if err != nil || !fresh {
95 return err
96 }
97 // A step already cancelled here (the cancel came first) keeps its
98 // row: the dispatch is never executed.
99 if _, err = t.Exec("INSERT INTO steps(step_id, attempt, task_id, person, body, state, base_sha, created_at) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", d.StepID, d.Attempt, d.TaskID, d.Person, string(raw), runRunning, d.BaseSHA, now()); err != nil {
100 return err
101 }
102 // But the cancel's own record names no specialist: it takes the
103 // dispatch's (still cancelled, in whatever state), so its report
104 // can be classified below 37 (holdBelow37).
105 if _, err = t.Exec("UPDATE steps SET body=? WHERE step_id=? AND attempt=? AND task_id=? AND cancel=1 AND coalesce(json_extract(body, '$.specialist'), '')=''", string(raw), d.StepID, d.Attempt, d.TaskID); err != nil {
106 return err
107 }
108 // Its scheduler facts: revision, priority, deadline, a release.
109 return acceptScheduled(t, d)
110 })
111}
112
113// RequestStepCancel marks an attempt cancelled exactly once, holding a
114// cancelled row for one not seen yet so a late dispatch never runs.
115func (s *State) RequestStepCancel(ctx context.Context, frameID string, c wire.CancelStepCommand) error {
116 return s.tx(ctx, func(t *sql.Tx) error {
117 fresh, err := seen(t, frameID)
118 if err != nil || !fresh {
119 return err
120 }
121 // The runner may have moved the step on to a later attempt (a
122 // refusal failed over) before the instance heard: that one stops.
123 res, err := t.Exec("UPDATE steps SET cancel=1 WHERE step_id=? AND attempt>=? AND state=?", c.StepID, c.Attempt, runRunning)
124 if err != nil {
125 return err
126 }
127 if n, _ := res.RowsAffected(); n > 0 {
128 return nil
129 }
130 body, _ := json.Marshal(wire.DispatchCommand{Person: c.Person, TaskID: c.TaskID, StepID: c.StepID, Attempt: c.Attempt, Findings: []wire.Finding{}})
131 _, err = t.Exec("INSERT INTO steps(step_id, attempt, task_id, person, body, state, cancel, created_at) VALUES(?,?,?,?,?,?,1,?) ON CONFLICT DO NOTHING", c.StepID, c.Attempt, c.TaskID, c.Person, string(body), runRunning, now())
132 return err
133 })
134}
135
136func scanStep(scan func(...any) error) (stepRow, error) {
137 var r stepRow
138 var body string
139 var cancel int
140 if err := scan(&body, &r.State, &cancel, &r.Phase, &r.Base, &r.Candidate); err != nil {
141 return r, err
142 }
143 r.Cancel = cancel == 1
144 return r, json.Unmarshal([]byte(body), &r.DispatchCommand)
145}
146
147// stepDeferred is what a StepFunc returns to run the attempt again later
148// (a merge waiting for the hub's CI): the attempt stays held, the queue
149// moves on, and the attempt is due again after deferStep's delay.
150const stepDeferred = "deferred"
151
152// stamp is a time as a fixed-width, ordered string (unix milliseconds).
153func stamp(t time.Time) string { return fmt.Sprintf("%015d", t.UnixMilli()) }
154
155// nextStep is the running step attempt that is due first in the
156// release order (connectors spec §7): urgent, then the earliest
157// deadline, then normal, then low, then the oldest, then the step id. A
158// held step is not due until its wake-up or a fact change, so it never
159// blocks one that can run.
160func (s *State) nextStep(ctx context.Context) (stepRow, bool, error) {
161 var created string
162 row := s.db.QueryRowContext(ctx, "SELECT body, state, cancel, phase, base_sha, candidate_sha, created_at FROM steps WHERE state=? AND (not_before='' OR not_before<=? OR cancel=1) ORDER BY rank, CASE WHEN by_at='' THEN 1 ELSE 0 END, by_at, created_at, step_id LIMIT 1", runRunning, stamp(time.Now()))
163 r, err := scanStep(func(dest ...any) error { return row.Scan(append(dest, &created)...) })
164 if errors.Is(err, sql.ErrNoRows) {
165 return r, false, nil
166 }
167 r.Created = created
168 return r, err == nil, err
169}
170
171// deferStep holds an attempt for after: it stays running and is due
172// again then. The first deferral's time is kept (deferredSince).
173func (s *State) deferStep(ctx context.Context, r stepRow, after time.Duration) error {
174 now := time.Now()
175 _, err := s.db.ExecContext(ctx, "UPDATE steps SET not_before=?, deferred_since=CASE WHEN deferred_since='' THEN ? ELSE deferred_since END WHERE step_id=? AND attempt>=? AND state=?", stamp(now.Add(after)), stamp(now), r.StepID, r.Attempt, runRunning)
176 return err
177}
178
179// deferredSince is when the attempt was first deferred (zero: never).
180func (s *State) deferredSince(ctx context.Context, r stepRow) time.Time {
181 var v string
182 _ = s.db.QueryRowContext(ctx, "SELECT deferred_since FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&v)
183 var ms int64
184 if _, err := fmt.Sscanf(v, "%d", &ms); err != nil || ms == 0 {
185 return time.Time{}
186 }
187 return time.UnixMilli(ms)
188}
189
190// nextDue is when the earliest deferred attempt is due again.
191func (s *State) nextDue(ctx context.Context) (time.Time, bool) {
192 var v string
193 if s.db.QueryRowContext(ctx, "SELECT MIN(v) FROM (SELECT not_before AS v FROM steps WHERE state=? AND not_before<>'' AND not_before<? UNION ALL SELECT not_before FROM asks WHERE state=? AND started=0 AND not_before<>'' AND not_before<?)", runRunning, heldUntilChange, runRunning, heldUntilChange).Scan(&v) != nil || v == "" {
194 return time.Time{}, false
195 }
196 var ms int64
197 if _, err := fmt.Sscanf(v, "%d", &ms); err != nil {
198 return time.Time{}, false
199 }
200 return time.UnixMilli(ms), true
201}
202
203// stepCancelled re-reads an attempt's cancel mark.
204func (s *State) stepCancelled(ctx context.Context, r stepRow) bool {
205 var cancel int
206 _ = s.db.QueryRowContext(ctx, "SELECT MAX(cancel) FROM steps WHERE step_id=? AND attempt>=? AND state=?", r.StepID, r.Attempt, runRunning).Scan(&cancel)
207 return cancel == 1
208}
209
210// setStepNamespace records the containment namespace an attempt runs in,
211// so its exit can be verified again later.
212func (s *State) setStepNamespace(ctx context.Context, r stepRow, id string) error {
213 _, err := s.db.ExecContext(ctx, "UPDATE steps SET ns_id=? WHERE step_id=? AND attempt=?", id, r.StepID, r.Attempt)
214 return err
215}
216
217// setStepPhase records how far an attempt got, durably.
218func (s *State) setStepPhase(ctx context.Context, r stepRow, phase, base, candidate string) error {
219 _, err := s.db.ExecContext(ctx, "UPDATE steps SET phase=?, base_sha=?, candidate_sha=? WHERE step_id=? AND attempt=? AND state=?", phase, base, candidate, r.StepID, r.Attempt, runRunning)
220 return err
221}
222
223// setWorkerCommitted records a worker's Engineering attempt committed,
224// durably and in one transaction: progress phase committed (only the
225// upload is left), its base and candidate, the commit's outcome in its
226// own field, the final report a restart sends again (redacted already),
227// and, when the attempt kept its session, that session's binding to the
228// candidate. Only a candidate whose scan passed is recorded so, and only
229// such a one is uploaded (Worker.candidatePack).
230func (s *State) setWorkerCommitted(ctx context.Context, r stepRow, base, candidate, outcome string, final wire.StepReport, kept bool) error {
231 raw, err := json.Marshal(final)
232 if err != nil {
233 return err
234 }
235 return s.tx(ctx, func(t *sql.Tx) error {
236 res, err := t.Exec("UPDATE steps SET phase=?, base_sha=?, candidate_sha=?, outcome=?, worker_report=? WHERE step_id=? AND attempt=? AND state=?", phaseCommitted, base, candidate, outcome, string(raw), r.StepID, r.Attempt, runRunning)
237 if err != nil {
238 return err
239 }
240 if n, _ := res.RowsAffected(); n != 1 {
241 return errors.New("step not held")
242 }
243 if kept {
244 _, err = t.Exec("UPDATE kept_sessions SET candidate_sha=? WHERE step_id=? AND attempt=?", candidate, r.StepID, r.Attempt)
245 }
246 return err
247 })
248}
249
250// workerCommitted is a worker attempt's recorded outcome and final
251// report ("" outcome for none).
252func (s *State) workerCommitted(ctx context.Context, stepID string, attempt int64) (string, wire.StepReport, error) {
253 var outcome, raw string
254 var rep wire.StepReport
255 err := s.db.QueryRowContext(ctx, "SELECT outcome, worker_report FROM steps WHERE step_id=? AND attempt=?", stepID, attempt).Scan(&outcome, &raw)
256 if errors.Is(err, sql.ErrNoRows) || err == nil && outcome == "" {
257 return "", rep, nil
258 }
259 if err != nil {
260 return "", rep, err
261 }
262 return outcome, rep, json.Unmarshal([]byte(raw), &rep)
263}
264
265// ReportStep queues a step report. A final one (done, failed, cancelled)
266// ends the attempt here in the same transaction.
267func (s *State) ReportStep(ctx context.Context, r stepRow, rep wire.StepReport) error {
268 return s.tx(ctx, func(t *sql.Tx) error {
269 if wire.StepTerminal(rep.State) {
270 // Without termination the attempt stays pending: probes verify
271 // its exit later and send the proof.
272 next := runReported
273 if !rep.Termination {
274 next = runPending
275 }
276 // The report's attempt: the step may have moved on from r's.
277 res, err := t.Exec("UPDATE steps SET state=?, final_state=?, final_reason=? WHERE step_id=? AND attempt=? AND state=?", next, rep.State, rep.Reason, r.StepID, max(rep.Attempt, r.Attempt), runRunning)
278 if err != nil {
279 return err
280 }
281 if n, _ := res.RowsAffected(); n != 1 {
282 return nil
283 }
284 // The attempt's render records (spec section 4, Audit), a
285 // failed attempt's included.
286 if rep.Renders == nil {
287 if rep.Renders, err = reportRenders(t, r.StepID, max(rep.Attempt, r.Attempt)); err != nil {
288 return err
289 }
290 }
291 }
292 // Unfinished work is queued as the step failing step_timeout,
293 // which any instance, and a runner rolled back to an older
294 // release replaying this outbox, reads safely; the attempt's row
295 // keeps that it was pushed, and the sender says so to an instance
296 // that knows unfinished work (unfinishedReport).
297 wire.WithoutUnfinished(&rep)
298 return s.enqueue(t, wire.FrameStep, "", rep)
299 })
300}
301
302// holdBelow37: a worker keeps f, a step report, in its outbox while the
303// instance speaks below 37. Only 37 places Engineering on a Mac, and an
304// older instance (a rollback) takes a report of a step it never
305// dispatched and drops it: the work would be lost when 37 is back (M9g).
306// So below 37 a worker sends a step report only once it is positively
307// one of a step it was dispatched that is not Engineering; anything
308// else waits, and so does one whose classification fails (err says
309// why).
310func (s *State) holdBelow37(ctx context.Context, f wire.Frame, worker bool, protocol int) (hold bool, err error) {
311 if f.Type != wire.FrameStep || !worker || protocol >= wire.ProtocolMacEngineering {
312 return false, nil
313 }
314 sendable, err := s.sendableBelow37(ctx, f)
315 return err != nil || !sendable, err
316}
317
318// errUnclassified: a queued step report that names no step dispatched
319// to this runner.
320var errUnclassified = errors.New("the report names no step dispatched here")
321
322// sendableBelow37 classifies a worker's queued step report by its own
323// task and step (any attempt: advanceStep moves the row on while earlier
324// reports wait): sendable when that step's dispatches are all of a
325// specialist other than Engineering. An error when it cannot tell.
326func (s *State) sendableBelow37(ctx context.Context, f wire.Frame) (bool, error) {
327 body, err := f.Decode()
328 if err != nil {
329 return false, err
330 }
331 rep, ok := body.(*wire.StepReport)
332 if !ok {
333 return false, errUnclassified
334 }
335 rows, err := s.db.QueryContext(ctx, "SELECT body FROM steps WHERE step_id=? AND task_id=?", rep.StepID, rep.TaskID)
336 if err != nil {
337 return false, err
338 }
339 defer rows.Close()
340 seen := 0
341 for rows.Next() {
342 var raw string
343 var d wire.DispatchCommand
344 if err := rows.Scan(&raw); err != nil {
345 return false, err
346 }
347 if err := json.Unmarshal([]byte(raw), &d); err != nil {
348 return false, err
349 }
350 if d.Specialist == wire.SpecialistEngineering || d.Specialist == "" {
351 return false, nil
352 }
353 seen++
354 }
355 if err := rows.Err(); err != nil {
356 return false, err
357 }
358 if seen == 0 {
359 return false, errUnclassified
360 }
361 return true, nil
362}
363
364// unfinishedReport is a queued step report as the sender sends it at
365// protocol: at ProtocolUnfinishedWork or later, a step that failed
366// step_timeout whose attempt pushed its unfinished work (its row: done,
367// step_timeout, phase committed_unfinished, the candidate; on a worker,
368// phase committed with outcome unfinished) is that work, done with the
369// reason step_timeout. Any other frame is unchanged.
370//
371// On a worker (Mac runners slice F) that work is never pushed here: only
372// the primary publishes a worker's commit, and only its published report
373// says pushed. From protocol 37 a worker sends it done, not pushed, with
374// its outcome (wire.OutcomeUnfinished), which the instance keeps for the
375// publication; below 37 it is sent as queued.
376func (s *State) unfinishedReport(ctx context.Context, f wire.Frame, protocol int, worker bool) (wire.Frame, error) {
377 if f.Type != wire.FrameStep || protocol < wire.ProtocolUnfinishedWork || worker && protocol < wire.ProtocolMacEngineering {
378 return f, nil
379 }
380 body, err := f.Decode()
381 if err != nil {
382 return f, err
383 }
384 rep, ok := body.(*wire.StepReport)
385 if !ok || rep.State != wire.StepFailed || rep.Reason != "step_timeout" || !rep.Termination {
386 return f, nil
387 }
388 var state, reason, phase, candidate, outcome string
389 err = s.db.QueryRowContext(ctx, "SELECT coalesce(final_state, ''), coalesce(final_reason, ''), phase, candidate_sha, outcome FROM steps WHERE step_id=? AND attempt=?", rep.StepID, rep.Attempt).Scan(&state, &reason, &phase, &candidate, &outcome)
390 kept := phase == phaseCommittedUnfinished || phase == phaseCommitted && outcome == wire.OutcomeUnfinished
391 if errors.Is(err, sql.ErrNoRows) || err == nil && (state != wire.StepDone || reason != "step_timeout" || !kept || candidate == "") {
392 return f, nil
393 }
394 if err != nil {
395 return f, err
396 }
397 rep.State, rep.Pushed, rep.CandidateSHA = wire.StepDone, true, candidate
398 if worker {
399 rep.Pushed, rep.OutcomePhase = false, wire.OutcomeUnfinished
400 }
401 return wire.NewFrame(f.ID, f.Type, rep)
402}
403
404// advanceStep moves a running step to its next attempt after the
405// provider refused this one (quota or credential) and its exit was
406// proven (spec §3, Engineering mid-step): durably, before anything runs
407// on the next connection. The refused attempt's usage and the new
408// attempt (running, with the switched line) are reported in the same
409// transaction; the instance takes the step to the new attempt.
410func (s *State) advanceStep(ctx context.Context, r *stepRow, used []wire.Usage, rep wire.StepReport) error {
411 next := r.DispatchCommand
412 next.Attempt++
413 body, err := json.Marshal(next)
414 if err != nil {
415 return err
416 }
417 err = s.tx(ctx, func(t *sql.Tx) error {
418 // The ending attempt's render records go with the advance: at the
419 // autonomy limit the instance holds the next attempt instead, and
420 // this one reports nothing more it would take.
421 if rep.Renders == nil {
422 if rep.Renders, err = reportRenders(t, r.StepID, r.Attempt); err != nil {
423 return err
424 }
425 }
426 res, err := t.Exec("UPDATE steps SET attempt=attempt+1, body=?, phase='', ns_id='' WHERE step_id=? AND attempt=? AND state=?", string(body), r.StepID, r.Attempt, runRunning)
427 if err != nil {
428 return err
429 }
430 if n, _ := res.RowsAffected(); n != 1 {
431 return errors.New("step not held")
432 }
433 if len(used) > 0 {
434 if err = s.enqueue(t, wire.FrameUsage, "", wire.UsageReport{StepID: r.StepID, Rows: used}); err != nil {
435 return err
436 }
437 }
438 rep.Attempt, rep.State, rep.Reason = next.Attempt, wire.StepRunning, ""
439 return s.enqueue(t, wire.FrameStep, "", rep)
440 })
441 if err == nil {
442 r.DispatchCommand = next
443 r.Phase = phaseNone
444 }
445 return err
446}
447
448// stepAcked finishes an attempt once the instance acked its final report.
449func stepAcked(t *sql.Tx, body string) error {
450 var r wire.StepReport
451 if err := json.Unmarshal([]byte(body), &r); err != nil {
452 return err
453 }
454 if !wire.StepTerminal(r.State) {
455 return nil
456 }
457 _, err := t.Exec("UPDATE steps SET state=? WHERE step_id=? AND attempt=? AND state IN (?,?)", runDone, r.StepID, r.Attempt, runReported, runSuperseded)
458 return err
459}
460
461// finishedSteps are the attempts whose final report the instance acked.
462func (s *State) finishedSteps(ctx context.Context) ([]stepRow, error) {
463 // A failed push keeps its private repository (and commit) for a
464 // republish, until an attempt of that step has published.
465 rows, err := s.db.QueryContext(ctx, "SELECT step_id, attempt FROM steps s WHERE state=? AND NOT (final_reason='push_failed' AND NOT EXISTS (SELECT 1 FROM steps l WHERE l.step_id=s.step_id AND l.attempt>s.attempt AND l.final_state=?))", runDone, wire.StepDone)
466 if err != nil {
467 return nil, err
468 }
469 defer rows.Close()
470 var out []stepRow
471 for rows.Next() {
472 var r stepRow
473 if err = rows.Scan(&r.StepID, &r.Attempt); err != nil {
474 return nil, err
475 }
476 out = append(out, r)
477 }
478 return out, rows.Err()
479}
480
481// syncSteps lists every attempt this runner still holds: running, its
482// final report not yet acked, or (state "pending") ended with its
483// termination unverified. An attempt is absent only once the runner has
484// no record of it left to report, so the instance may infer its end.
485func (s *State) syncSteps(ctx context.Context) ([]wire.StepRun, error) {
486 rows, err := s.db.QueryContext(ctx, "SELECT task_id, step_id, attempt, state, candidate_sha FROM steps WHERE state IN (?,?,?) ORDER BY created_at", runRunning, runReported, runPending)
487 if err != nil {
488 return nil, err
489 }
490 defer rows.Close()
491 out := []wire.StepRun{}
492 for rows.Next() {
493 var r wire.StepRun
494 if err = rows.Scan(&r.TaskID, &r.StepID, &r.Attempt, &r.State, &r.CandidateSHA); err != nil {
495 return nil, err
496 }
497 out = append(out, r)
498 }
499 return out, rows.Err()
500}
501
502// pendingStep is an attempt waiting for its termination proof.
503type pendingStep struct {
504 step, task, state, reason, ns string
505 attempt int64
506}
507
508func (s *State) pendingSteps(ctx context.Context) ([]pendingStep, error) {
509 rows, err := s.db.QueryContext(ctx, "SELECT step_id, attempt, task_id, final_state, final_reason, ns_id FROM steps WHERE state=?", runPending)
510 if err != nil {
511 return nil, err
512 }
513 defer rows.Close()
514 var out []pendingStep
515 for rows.Next() {
516 var p pendingStep
517 if err = rows.Scan(&p.step, &p.attempt, &p.task, &p.state, &p.reason, &p.ns); err != nil {
518 return nil, err
519 }
520 out = append(out, p)
521 }
522 return out, rows.Err()
523}
524
525// proveTermination sends the follow-up report for a pending attempt
526// whose exit is now verified; its ack finishes the attempt.
527func (s *State) proveTermination(ctx context.Context, p pendingStep) error {
528 return s.tx(ctx, func(t *sql.Tx) error {
529 res, err := t.Exec("UPDATE steps SET state=? WHERE step_id=? AND attempt=? AND state=?", runReported, p.step, p.attempt, runPending)
530 if err != nil {
531 return err
532 }
533 if n, _ := res.RowsAffected(); n != 1 {
534 return nil
535 }
536 renders, err := reportRenders(t, p.step, p.attempt)
537 if err != nil {
538 return err
539 }
540 return s.enqueue(t, wire.FrameStep, "", wire.StepReport{TaskID: p.task, StepID: p.step, Attempt: p.attempt, State: p.state, Reason: p.reason, Termination: true, TerminationKind: terminationKind(p.ns), Renders: renders})
541 })
542}
543
544const unrecordedPrefix = "step:"
545
546// UnrecordedStep names an attempt that recorded no namespace or process
547// group before the runner stopped. Verify must prove it ended on its own
548// terms: no namespace of this runner left (Linux), no process carrying
549// its marker (a worker).
550func UnrecordedStep(key string) string { return unrecordedPrefix + key }
551
552// unrecordedKey is the step key of an UnrecordedStep record.
553func unrecordedKey(id string) (string, bool) { return strings.CutPrefix(id, unrecordedPrefix) }
554
555// RecoverSteps settles attempts a previous process left running. Its
556// namespaces died with it and startup verified their exits, so an
557// attempt that had not committed has ended: failed (or cancelled), with
558// termination when verify confirms its namespace's exit, else pending.
559// A committed one only has its push left, which the engine reconciles;
560// a merge runs again and reconciles from its record.
561func (s *State) RecoverSteps(ctx context.Context, verify func(context.Context, string) bool) error {
562 var all []stepRow
563 ns := map[string]string{}
564 rows, err := s.db.QueryContext(ctx, "SELECT body, state, cancel, phase, base_sha, candidate_sha, ns_id, hold FROM steps WHERE state=?", runRunning)
565 if err != nil {
566 return err
567 }
568 for rows.Next() {
569 var id, hold string
570 r, err := scanStep(func(dest ...any) error { return rows.Scan(append(dest, &id, &hold)...) })
571 if err != nil {
572 rows.Close()
573 return err
574 }
575 if hold != "" && id == "" && !r.Cancel {
576 // Held by the scheduler and never launched since (an admission
577 // clears the hold; a launch records its namespace): nothing of
578 // it ran, so it keeps its hold and its wake-up.
579 continue
580 }
581 all = append(all, r)
582 ns[r.key()] = id
583 }
584 rows.Close()
585 proven := map[string]bool{}
586 for _, r := range all {
587 // An attempt that recorded nothing is never taken as ended: verify
588 // is asked about the step itself (UnrecordedStep), and says so only
589 // once nothing of it can be left.
590 if ns[r.key()] == "" {
591 ns[r.key()] = UnrecordedStep(r.key())
592 }
593 proven[r.key()] = verify == nil || verify(ctx, ns[r.key()])
594 }
595 return s.tx(ctx, func(t *sql.Tx) error {
596 for _, r := range all {
597 if _, err := t.Exec("UPDATE steps SET ns_id=? WHERE step_id=? AND attempt=? AND coalesce(ns_id, '')=''", ns[r.key()], r.StepID, r.Attempt); err != nil {
598 return err
599 }
600 rep := wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, BaseSHA: r.Base, Termination: proven[r.key()]}
601 if rep.Termination {
602 rep.TerminationKind = terminationKind(ns[r.key()])
603 }
604 switch {
605 case committed(r.Phase):
606 continue
607 case r.Specialist == wire.SpecialistMerge && !r.Cancel:
608 // A merge settles itself from its record and the default
609 // branch: it runs again and never merges twice.
610 continue
611 case r.Specialist == wire.SpecialistPreview && r.Phase == phasePreviewPublishing,
612 r.Specialist == wire.SpecialistPublish && (r.Phase == phaseSitePublishing || r.Phase == phaseSiteMinting):
613 // A preview or a site publish that may have changed Carloku
614 // reconciles from the marker, cancelled or not; it never sends
615 // again, and its outcome is never lost to a plain "cancelled".
616 continue
617 case r.Specialist == wire.SpecialistChecks && r.Phase == phaseHosted && !r.Cancel:
618 // Old hosted waits ran nothing locally. Resume them through
619 // the current base-gate executor, which never trusts hosted CI.
620 continue
621 case r.Cancel:
622 rep.State, rep.Reason = wire.StepCancelled, "cancelled"
623 default:
624 rep.State, rep.Reason = wire.StepFailed, "runner_restarted"
625 }
626 next := runReported
627 if !rep.Termination {
628 next = runPending
629 }
630 if _, err := t.Exec("UPDATE steps SET state=?, final_state=?, final_reason=? WHERE step_id=? AND attempt=?", next, rep.State, rep.Reason, r.StepID, r.Attempt); err != nil {
631 return err
632 }
633 var err error
634 if rep.Renders, err = reportRenders(t, r.StepID, r.Attempt); err != nil {
635 return err
636 }
637 if err := s.enqueue(t, wire.FrameStep, "", rep); err != nil {
638 return err
639 }
640 }
641 return nil
642 })
643}
644
645// StepFunc executes one attempt. progress sends interim reports; the
646// returned report is final, with Termination only once the attempt's
647// namespace exit was observed.
648type StepFunc func(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport
649
650// StepEngine runs step attempts one at a time from the durable table.
651type StepEngine struct {
652 State *State
653 Exec StepFunc
654 // Ask answers questions from the same queue, oldest first with the
655 // steps, so a question never runs beside a step.
656 Ask AskFunc
657 Notify func()
658 Logger *slog.Logger
659 // Sweep tidies attempts whose final report was acked; it runs at start
660 // and whenever the worker wakes.
661 Sweep func(context.Context)
662 // Verify reports whether a namespace's exit is verified now (its
663 // record released after proof, or gone).
664 Verify func(ctx context.Context, nsID string) bool
665 // Acknowledge, if set, is told of each namespace whose proven exit
666 // is committed here: only then may the proof's evidence go (a Mac's).
667 Acknowledge func(ctx context.Context, nsID string)
668 // TerminationKind is how this runner proves an attempt's end
669 // (wire.TerminationNamespace on Linux), reported with termination.
670 TerminationKind string
671 // Meter is the metered guard: a question on a metered connection
672 // passes it (askmetered.go). MeteredAsk is the harness that answers
673 // one (S2's Pi); nil, such a question cannot run here.
674 Meter *metered.Meter
675 MeteredAsk MeteredAskFunc
676
677 mu sync.Mutex
678 wake chan struct{}
679 cancel context.CancelFunc
680 // cur is the step (or "ask:" question) running now and curAttempt
681 // the attempt it was taken at; a step moves to later attempts while
682 // it runs (a refusal fails over), so a cancel for any of them stops it.
683 cur string
684 curAttempt int64
685 wg sync.WaitGroup
686}
687
688// Probe re-checks attempts whose termination is pending; a verified exit
689// sends the follow-up report with termination. It runs at start and on
690// every sync with the instance.
691func (e *StepEngine) Probe(ctx context.Context) {
692 if e.Verify == nil {
693 return
694 }
695 sent := false
696 // Questions held for their namespace's proof are released once it is
697 // verified.
698 held, err := e.State.heldAsks(ctx)
699 if err != nil {
700 e.log("ask probe", err)
701 }
702 for _, h := range held {
703 // Never released unverified: with no namespace recorded, Verify
704 // requires that no namespace of this runner remains at all.
705 if !e.Verify(ctx, h.ns) {
706 continue
707 }
708 e.log("ask probe", e.State.releaseAsk(ctx, h))
709 sent = true
710 }
711 pending, err := e.State.pendingSteps(ctx)
712 if err != nil {
713 e.log("step probe", err)
714 return
715 }
716 for _, p := range pending {
717 if !e.Verify(ctx, p.ns) {
718 continue
719 }
720 err := e.State.proveTermination(ctx, p)
721 e.log("step probe", err)
722 if err == nil && e.Acknowledge != nil {
723 e.Acknowledge(ctx, p.ns)
724 }
725 sent = true
726 }
727 if e.Meter != nil {
728 // A metered slot whose ended attempt's exit is proven now is
729 // released, with its charge or the spend unknown. One still
730 // unproven stays held, and is tried again at the next probe.
731 _ = e.Meter.Recover(ctx)
732 }
733 if sent && e.Notify != nil {
734 e.Notify()
735 }
736}
737
738// recoverSteps is State.RecoverSteps, acknowledging each proven exit
739// once the recovery has committed it.
740func (e *StepEngine) recoverSteps(ctx context.Context) error {
741 verify, proven := e.Verify, []string{}
742 if verify != nil && e.Acknowledge != nil {
743 verify = func(ctx context.Context, id string) bool {
744 ok := e.Verify(ctx, id)
745 if ok {
746 proven = append(proven, id)
747 }
748 return ok
749 }
750 }
751 if err := e.State.RecoverSteps(ctx, verify); err != nil {
752 return err
753 }
754 for _, id := range proven {
755 e.Acknowledge(ctx, id)
756 }
757 return nil
758}
759
760// Start recovers what a previous process left and starts the worker.
761func (e *StepEngine) Start(ctx context.Context) error {
762 if err := e.recoverSteps(ctx); err != nil {
763 return err
764 }
765 if err := e.State.RecoverAsks(ctx, e.Verify); err != nil {
766 return err
767 }
768 e.Probe(ctx)
769 e.mu.Lock()
770 e.wake = make(chan struct{}, 1)
771 e.mu.Unlock()
772 e.Notify()
773 e.wg.Add(1)
774 go e.loop(ctx)
775 e.Wake()
776 return nil
777}
778
779// Wait returns once the worker stopped.
780func (e *StepEngine) Wait() { e.wg.Wait() }
781
782// Wake makes the worker look for attempts.
783func (e *StepEngine) Wake() {
784 e.mu.Lock()
785 defer e.mu.Unlock()
786 if e.wake == nil {
787 return
788 }
789 select {
790 case e.wake <- struct{}{}:
791 default:
792 }
793}
794
795// CancelAsk interrupts a question's attempt if it is running now.
796func (e *StepEngine) CancelAsk(question string, attempt int64) {
797 e.Cancel("ask:"+question, attempt)
798}
799
800// Cancel interrupts the attempt if it is the one running now.
801func (e *StepEngine) Cancel(step string, attempt int64) {
802 e.mu.Lock()
803 defer e.mu.Unlock()
804 if e.cur == step && attempt >= e.curAttempt && e.cancel != nil {
805 e.cancel()
806 }
807}
808
809func (e *StepEngine) log(msg string, err error) {
810 if e.Logger != nil && err != nil {
811 e.Logger.Warn(msg, "err", sanitize(err))
812 }
813}
814
815func (e *StepEngine) loop(ctx context.Context) {
816 defer e.wg.Done()
817 // The sweep also runs hourly, so kept sessions past retention go on
818 // an idle runner too.
819 hourly := time.NewTicker(time.Hour)
820 defer hourly.Stop()
821 for {
822 select {
823 case <-ctx.Done():
824 return
825 case <-e.wake:
826 case <-hourly.C:
827 }
828 if e.Sweep != nil {
829 e.Sweep(ctx)
830 }
831 for ctx.Err() == nil {
832 // Nothing runs beside an earlier attempt whose namespace's exit
833 // is not verified yet: try again shortly.
834 if e.held(ctx) {
835 time.AfterFunc(heldRetry, e.Wake)
836 break
837 }
838 r, ok, err := e.State.nextStep(ctx)
839 if err != nil {
840 e.log("step state", err)
841 break
842 }
843 a, asked, err := e.State.nextAsk(ctx)
844 if err != nil {
845 e.log("ask state", err)
846 break
847 }
848 if !asked || e.Ask == nil {
849 if !ok {
850 break
851 }
852 e.runOne(ctx, r)
853 continue
854 }
855 // Steps and questions in arrival order, one at a time.
856 if ok && !earlier(a.Created, r.Created) {
857 e.runOne(ctx, r)
858 continue
859 }
860 e.askOne(ctx, a)
861 }
862 // A deferred attempt (a merge waiting for the hub's CI) wakes the
863 // worker when it is due, also after a restart; so does a question
864 // held for its metered connection's budget at the next day.
865 if due, ok := e.State.nextDue(ctx); ok {
866 time.AfterFunc(max(time.Until(due), 10*time.Millisecond), e.Wake)
867 }
868 }
869}
870
871// heldRetry is how soon a worker held by an unverified exit looks again.
872var heldRetry = 5 * time.Second
873
874// held probes, then reports whether a step or question attempt still
875// waits for its namespace's exit to be verified (or the state cannot
876// tell).
877func (e *StepEngine) held(ctx context.Context) bool {
878 e.Probe(ctx)
879 steps, err := e.State.pendingSteps(ctx)
880 if err != nil {
881 e.log("step state", err)
882 return true
883 }
884 asks, err := e.State.heldAsks(ctx)
885 if err != nil {
886 e.log("ask state", err)
887 return true
888 }
889 return len(steps) > 0 || len(asks) > 0
890}
891
892// earlier compares two recorded times (RFC 3339, variable precision).
893func earlier(a, b string) bool {
894 x, errA := time.Parse(time.RFC3339Nano, a)
895 y, errB := time.Parse(time.RFC3339Nano, b)
896 if errA != nil || errB != nil {
897 return a < b
898 }
899 return x.Before(y)
900}
901
902func (e *StepEngine) askOne(ctx context.Context, a askRow) {
903 report := func(rep wire.AnswerReport) {
904 e.log("answer report", e.State.ReportAnswer(context.WithoutCancel(ctx), a, rep))
905 e.Notify()
906 }
907 if a.Cancel {
908 report(wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt, State: wire.QuestionCancelled, Reason: "cancelled"})
909 return
910 }
911 actx, cancel := context.WithCancel(ctx)
912 defer cancel()
913 e.mu.Lock()
914 e.cancel, e.cur, e.curAttempt = cancel, "ask:"+a.QuestionID, a.Attempt
915 e.mu.Unlock()
916 defer func() {
917 e.mu.Lock()
918 e.cancel, e.cur = nil, ""
919 e.mu.Unlock()
920 }()
921 if e.State.askCancelled(ctx, a) {
922 cancel()
923 }
924 if local, model, ok := e.meteredAsk(ctx, a); ok {
925 // On a metered connection: the guard admits it, with the start.
926 e.askMetered(ctx, actx, a, local, model, report)
927 return
928 }
929 // Started, durably, before the provider runs: never run twice.
930 if err := e.State.startAsk(ctx, a); err != nil {
931 e.log("ask start", err)
932 return
933 }
934 res := e.Ask(actx, a, func(p wire.AnswerReport) {
935 p.State = wire.QuestionRunning
936 report(p)
937 })
938 rep := res.Report
939 if actx.Err() != nil && rep.State != wire.QuestionAnswered {
940 rep.State, rep.Reason = wire.QuestionCancelled, "cancelled"
941 }
942 if !wire.QuestionTerminal(rep.State) {
943 rep.State, rep.Reason = wire.QuestionFailed, "provider_failed"
944 }
945 // The result is kept in memory until it is saved: a failed write is
946 // tried again, never the provider. Shutting down before then, the
947 // next start ends the attempt (runner_restarted).
948 for i := 0; ; i++ {
949 err := e.State.FinishAsk(context.WithoutCancel(ctx), a, rep, res.Terminated)
950 if err == nil {
951 break
952 }
953 e.log("answer report", err)
954 select {
955 case <-ctx.Done():
956 return
957 case <-time.After(min(time.Duration(i+1)*100*time.Millisecond, 5*time.Second)):
958 }
959 }
960 e.Notify()
961}
962
963func (e *StepEngine) runOne(ctx context.Context, r stepRow) {
964 report := func(rep wire.StepReport) {
965 if rep.Termination && rep.TerminationKind == "" {
966 rep.TerminationKind = e.TerminationKind
967 }
968 e.log("step report", e.State.ReportStep(context.WithoutCancel(ctx), r, rep))
969 e.Notify()
970 }
971 // A site publish that may have changed CARLOS reconciles from its
972 // marker even when cancelled: its outcome is never lost to a plain
973 // "cancelled" (publishSite never sends again in these phases).
974 siteReconciles := r.Specialist == wire.SpecialistPublish && (r.Phase == phaseSitePublishing || r.Phase == phaseSiteMinting)
975 if r.Cancel && !siteReconciles {
976 report(wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, State: wire.StepCancelled, Reason: "cancelled", BaseSHA: r.Base, Termination: true})
977 return
978 }
979 sctx, cancel := context.WithCancel(ctx)
980 defer cancel()
981 e.mu.Lock()
982 e.cancel, e.cur, e.curAttempt = cancel, r.StepID, r.Attempt
983 e.mu.Unlock()
984 defer func() {
985 e.mu.Lock()
986 e.cancel, e.cur = nil, ""
987 e.mu.Unlock()
988 }()
989 // A cancel that arrived between nextStep and now is still honoured.
990 if e.State.stepCancelled(ctx, r) {
991 cancel()
992 }
993 rep := e.Exec(sctx, r, func(p wire.StepReport) {
994 p.State = wire.StepRunning
995 report(p)
996 })
997 if ctx.Err() != nil {
998 // Shutting down: the attempt stays held; the next start settles it.
999 return
1000 }
1001 if rep.State == stepDeferred && rep.Hold != nil {
1002 // Held by the scheduler: kept with its wake-up, said once per
1003 // hold (state running; the instance keeps it queued), and looked
1004 // at again then or when a fact changes.
1005 // The step may have moved to a later attempt (a failover) first.
1006 held := r
1007 held.Attempt = max(rep.Attempt, r.Attempt)
1008 changed, err := e.State.holdStep(context.WithoutCancel(ctx), held, rep.Hold)
1009 e.log("step hold", err)
1010 if changed {
1011 out := rep
1012 out.State = wire.StepRunning
1013 report(out)
1014 }
1015 return
1016 }
1017 if rep.State == stepDeferred {
1018 // Held for later; the queue moves on meanwhile.
1019 e.log("step defer", e.State.deferStep(context.WithoutCancel(ctx), r, mergeCIPoll))
1020 time.AfterFunc(mergeCIPoll, e.Wake)
1021 return
1022 }
1023 // A merge reports its real outcome even when asked to stop: the hub
1024 // may have merged it (the instance refuses cancels while merging).
1025 if sctx.Err() != nil && rep.State != wire.StepDone && r.Specialist != wire.SpecialistMerge {
1026 rep.State, rep.Reason = wire.StepCancelled, "cancelled"
1027 }
1028 if !wire.StepTerminal(rep.State) {
1029 rep.State, rep.Reason = wire.StepFailed, "provider_failed"
1030 }
1031 report(rep)
1032}
1033
1034// stepWait bounds one wait for the lease before an attempt starts.
1035const stepWait = time.Second
1036
1037// terminationKind is how a recorded attempt's end was proven: a process
1038// group ("pg:" records, a worker) or a namespace.
1039func terminationKind(record string) string {
1040 if strings.HasPrefix(record, "pg:") {
1041 return wire.TerminationProcessGroup
1042 }
1043 if strings.HasPrefix(record, unrecordedPrefix) {
1044 return ""
1045 }
1046 return wire.TerminationNamespace
1047}
1048
1049// starter launches a contained process, calling record with its
1050// namespace before the launch (and again once it runs); a record error
1051// launches nothing (containment.Manager.StartRecorded).
1052type starter interface {
1053 StartRecorded(context.Context, provider.Launch, []string, func(context.Context, containment.Record) error) (provider.Process, error)
1054}
1055
1056// recordedStart starts a step's or question's process with its namespace
1057// written durably before it launches.
1058func recordedStart(ctx context.Context, m starter, l provider.Launch, argv []string, record func(context.Context, string) error) (provider.Process, error) {
1059 return recordedStartKept(ctx, m, l, argv, record, nil)
1060}
1061