package thin import ( "context" "database/sql" "encoding/json" "errors" "fmt" "log/slog" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/metered" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/wire" ) // stepSchema holds the step attempts this runner was sent. At most one // attempt of a task runs at a time (the partial unique index). const stepSchema = ` CREATE 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)); CREATE UNIQUE INDEX IF NOT EXISTS steps_running ON steps(task_id) WHERE state='running'; ` // runPending is an attempt that ended without a verified exit: its final // report went out without termination, and a follow-up carries the proof // once a probe verifies the namespace's exit. const runPending = "pending" // Step phases while running: nothing ran yet, the specialist runs, the // runner committed the candidate (only publishing is left). An // Engineering commit can carry how its step finished, which its pushed // report says (committedReason): it ran out of time (the work so far), // or it was a fix round without a working shell. The phase stays on the // attempt's row, so a restart and a republish of a failed push say it // too. const ( phaseNone = "" phaseRunning = "running" phaseCommitted = "committed" phaseCommittedUnfinished = "committed_unfinished" phaseCommittedNoShell = "committed_no_shell" ) // committed: only publishing is left of the attempt. func committed(phase string) bool { return phase == phaseCommitted || committedReason(phase) != "" } // committedReason is the reason a pushed report of a commit in phase // carries ("" for none). func committedReason(phase string) string { switch phase { case phaseCommittedUnfinished: return "step_timeout" case phaseCommittedNoShell: return wire.ReasonShellUnavailable } return "" } // stepPhase is the phase an attempt of a step was left in ("" when the // runner has no such attempt). func (s *State) stepPhase(ctx context.Context, stepID string, attempt int64) (string, error) { var phase sql.NullString err := s.db.QueryRowContext(ctx, "SELECT phase FROM steps WHERE step_id=? AND attempt=?", stepID, attempt).Scan(&phase) if errors.Is(err, sql.ErrNoRows) { return "", nil } return phase.String, err } // stepRow is one step attempt held by this runner. type stepRow struct { wire.DispatchCommand State, Phase, Base, Candidate string Cancel bool // Created orders steps and questions in the engine's one queue. Created string // Question: a question's tree (StepID is the question's id). It is // not a step attempt, so it takes the plain execution lease. Question bool } func (r stepRow) key() string { return r.StepID + "/" + itoa(r.Attempt) } // AcceptDispatch records a dispatch exactly once; the caller acks after. func (s *State) AcceptDispatch(ctx context.Context, frameID string, d wire.DispatchCommand) error { raw, _ := json.Marshal(d) return s.tx(ctx, func(t *sql.Tx) error { fresh, err := seen(t, frameID) if err != nil || !fresh { return err } // A step already cancelled here (the cancel came first) keeps its // row: the dispatch is never executed. 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 { return err } // But the cancel's own record names no specialist: it takes the // dispatch's (still cancelled, in whatever state), so its report // can be classified below 37 (holdBelow37). 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 { return err } // Its scheduler facts: revision, priority, deadline, a release. return acceptScheduled(t, d) }) } // RequestStepCancel marks an attempt cancelled exactly once, holding a // cancelled row for one not seen yet so a late dispatch never runs. func (s *State) RequestStepCancel(ctx context.Context, frameID string, c wire.CancelStepCommand) error { return s.tx(ctx, func(t *sql.Tx) error { fresh, err := seen(t, frameID) if err != nil || !fresh { return err } // The runner may have moved the step on to a later attempt (a // refusal failed over) before the instance heard: that one stops. res, err := t.Exec("UPDATE steps SET cancel=1 WHERE step_id=? AND attempt>=? AND state=?", c.StepID, c.Attempt, runRunning) if err != nil { return err } if n, _ := res.RowsAffected(); n > 0 { return nil } body, _ := json.Marshal(wire.DispatchCommand{Person: c.Person, TaskID: c.TaskID, StepID: c.StepID, Attempt: c.Attempt, Findings: []wire.Finding{}}) _, 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()) return err }) } func scanStep(scan func(...any) error) (stepRow, error) { var r stepRow var body string var cancel int if err := scan(&body, &r.State, &cancel, &r.Phase, &r.Base, &r.Candidate); err != nil { return r, err } r.Cancel = cancel == 1 return r, json.Unmarshal([]byte(body), &r.DispatchCommand) } // stepDeferred is what a StepFunc returns to run the attempt again later // (a merge waiting for the hub's CI): the attempt stays held, the queue // moves on, and the attempt is due again after deferStep's delay. const stepDeferred = "deferred" // stamp is a time as a fixed-width, ordered string (unix milliseconds). func stamp(t time.Time) string { return fmt.Sprintf("%015d", t.UnixMilli()) } // nextStep is the running step attempt that is due first in the // release order (connectors spec §7): urgent, then the earliest // deadline, then normal, then low, then the oldest, then the step id. A // held step is not due until its wake-up or a fact change, so it never // blocks one that can run. func (s *State) nextStep(ctx context.Context) (stepRow, bool, error) { var created string 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())) r, err := scanStep(func(dest ...any) error { return row.Scan(append(dest, &created)...) }) if errors.Is(err, sql.ErrNoRows) { return r, false, nil } r.Created = created return r, err == nil, err } // deferStep holds an attempt for after: it stays running and is due // again then. The first deferral's time is kept (deferredSince). func (s *State) deferStep(ctx context.Context, r stepRow, after time.Duration) error { now := time.Now() _, 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) return err } // deferredSince is when the attempt was first deferred (zero: never). func (s *State) deferredSince(ctx context.Context, r stepRow) time.Time { var v string _ = s.db.QueryRowContext(ctx, "SELECT deferred_since FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&v) var ms int64 if _, err := fmt.Sscanf(v, "%d", &ms); err != nil || ms == 0 { return time.Time{} } return time.UnixMilli(ms) } // nextDue is when the earliest deferred attempt is due again. func (s *State) nextDue(ctx context.Context) (time.Time, bool) { var v string if s.db.QueryRowContext(ctx, "SELECT MIN(v) FROM (SELECT not_before AS v FROM steps WHERE state=? AND not_before<>'' AND not_before'' AND not_before=? AND state=?", r.StepID, r.Attempt, runRunning).Scan(&cancel) return cancel == 1 } // setStepNamespace records the containment namespace an attempt runs in, // so its exit can be verified again later. func (s *State) setStepNamespace(ctx context.Context, r stepRow, id string) error { _, err := s.db.ExecContext(ctx, "UPDATE steps SET ns_id=? WHERE step_id=? AND attempt=?", id, r.StepID, r.Attempt) return err } // setStepPhase records how far an attempt got, durably. func (s *State) setStepPhase(ctx context.Context, r stepRow, phase, base, candidate string) error { _, 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) return err } // setWorkerCommitted records a worker's Engineering attempt committed, // durably and in one transaction: progress phase committed (only the // upload is left), its base and candidate, the commit's outcome in its // own field, the final report a restart sends again (redacted already), // and, when the attempt kept its session, that session's binding to the // candidate. Only a candidate whose scan passed is recorded so, and only // such a one is uploaded (Worker.candidatePack). func (s *State) setWorkerCommitted(ctx context.Context, r stepRow, base, candidate, outcome string, final wire.StepReport, kept bool) error { raw, err := json.Marshal(final) if err != nil { return err } return s.tx(ctx, func(t *sql.Tx) error { 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) if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return errors.New("step not held") } if kept { _, err = t.Exec("UPDATE kept_sessions SET candidate_sha=? WHERE step_id=? AND attempt=?", candidate, r.StepID, r.Attempt) } return err }) } // workerCommitted is a worker attempt's recorded outcome and final // report ("" outcome for none). func (s *State) workerCommitted(ctx context.Context, stepID string, attempt int64) (string, wire.StepReport, error) { var outcome, raw string var rep wire.StepReport err := s.db.QueryRowContext(ctx, "SELECT outcome, worker_report FROM steps WHERE step_id=? AND attempt=?", stepID, attempt).Scan(&outcome, &raw) if errors.Is(err, sql.ErrNoRows) || err == nil && outcome == "" { return "", rep, nil } if err != nil { return "", rep, err } return outcome, rep, json.Unmarshal([]byte(raw), &rep) } // ReportStep queues a step report. A final one (done, failed, cancelled) // ends the attempt here in the same transaction. func (s *State) ReportStep(ctx context.Context, r stepRow, rep wire.StepReport) error { return s.tx(ctx, func(t *sql.Tx) error { if wire.StepTerminal(rep.State) { // Without termination the attempt stays pending: probes verify // its exit later and send the proof. next := runReported if !rep.Termination { next = runPending } // The report's attempt: the step may have moved on from r's. 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) if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return nil } // The attempt's render records (spec section 4, Audit), a // failed attempt's included. if rep.Renders == nil { if rep.Renders, err = reportRenders(t, r.StepID, max(rep.Attempt, r.Attempt)); err != nil { return err } } } // Unfinished work is queued as the step failing step_timeout, // which any instance, and a runner rolled back to an older // release replaying this outbox, reads safely; the attempt's row // keeps that it was pushed, and the sender says so to an instance // that knows unfinished work (unfinishedReport). wire.WithoutUnfinished(&rep) return s.enqueue(t, wire.FrameStep, "", rep) }) } // holdBelow37: a worker keeps f, a step report, in its outbox while the // instance speaks below 37. Only 37 places Engineering on a Mac, and an // older instance (a rollback) takes a report of a step it never // dispatched and drops it: the work would be lost when 37 is back (M9g). // So below 37 a worker sends a step report only once it is positively // one of a step it was dispatched that is not Engineering; anything // else waits, and so does one whose classification fails (err says // why). func (s *State) holdBelow37(ctx context.Context, f wire.Frame, worker bool, protocol int) (hold bool, err error) { if f.Type != wire.FrameStep || !worker || protocol >= wire.ProtocolMacEngineering { return false, nil } sendable, err := s.sendableBelow37(ctx, f) return err != nil || !sendable, err } // errUnclassified: a queued step report that names no step dispatched // to this runner. var errUnclassified = errors.New("the report names no step dispatched here") // sendableBelow37 classifies a worker's queued step report by its own // task and step (any attempt: advanceStep moves the row on while earlier // reports wait): sendable when that step's dispatches are all of a // specialist other than Engineering. An error when it cannot tell. func (s *State) sendableBelow37(ctx context.Context, f wire.Frame) (bool, error) { body, err := f.Decode() if err != nil { return false, err } rep, ok := body.(*wire.StepReport) if !ok { return false, errUnclassified } rows, err := s.db.QueryContext(ctx, "SELECT body FROM steps WHERE step_id=? AND task_id=?", rep.StepID, rep.TaskID) if err != nil { return false, err } defer rows.Close() seen := 0 for rows.Next() { var raw string var d wire.DispatchCommand if err := rows.Scan(&raw); err != nil { return false, err } if err := json.Unmarshal([]byte(raw), &d); err != nil { return false, err } if d.Specialist == wire.SpecialistEngineering || d.Specialist == "" { return false, nil } seen++ } if err := rows.Err(); err != nil { return false, err } if seen == 0 { return false, errUnclassified } return true, nil } // unfinishedReport is a queued step report as the sender sends it at // protocol: at ProtocolUnfinishedWork or later, a step that failed // step_timeout whose attempt pushed its unfinished work (its row: done, // step_timeout, phase committed_unfinished, the candidate; on a worker, // phase committed with outcome unfinished) is that work, done with the // reason step_timeout. Any other frame is unchanged. // // On a worker (Mac runners slice F) that work is never pushed here: only // the primary publishes a worker's commit, and only its published report // says pushed. From protocol 37 a worker sends it done, not pushed, with // its outcome (wire.OutcomeUnfinished), which the instance keeps for the // publication; below 37 it is sent as queued. func (s *State) unfinishedReport(ctx context.Context, f wire.Frame, protocol int, worker bool) (wire.Frame, error) { if f.Type != wire.FrameStep || protocol < wire.ProtocolUnfinishedWork || worker && protocol < wire.ProtocolMacEngineering { return f, nil } body, err := f.Decode() if err != nil { return f, err } rep, ok := body.(*wire.StepReport) if !ok || rep.State != wire.StepFailed || rep.Reason != "step_timeout" || !rep.Termination { return f, nil } var state, reason, phase, candidate, outcome string 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) kept := phase == phaseCommittedUnfinished || phase == phaseCommitted && outcome == wire.OutcomeUnfinished if errors.Is(err, sql.ErrNoRows) || err == nil && (state != wire.StepDone || reason != "step_timeout" || !kept || candidate == "") { return f, nil } if err != nil { return f, err } rep.State, rep.Pushed, rep.CandidateSHA = wire.StepDone, true, candidate if worker { rep.Pushed, rep.OutcomePhase = false, wire.OutcomeUnfinished } return wire.NewFrame(f.ID, f.Type, rep) } // advanceStep moves a running step to its next attempt after the // provider refused this one (quota or credential) and its exit was // proven (spec §3, Engineering mid-step): durably, before anything runs // on the next connection. The refused attempt's usage and the new // attempt (running, with the switched line) are reported in the same // transaction; the instance takes the step to the new attempt. func (s *State) advanceStep(ctx context.Context, r *stepRow, used []wire.Usage, rep wire.StepReport) error { next := r.DispatchCommand next.Attempt++ body, err := json.Marshal(next) if err != nil { return err } err = s.tx(ctx, func(t *sql.Tx) error { // The ending attempt's render records go with the advance: at the // autonomy limit the instance holds the next attempt instead, and // this one reports nothing more it would take. if rep.Renders == nil { if rep.Renders, err = reportRenders(t, r.StepID, r.Attempt); err != nil { return err } } 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) if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return errors.New("step not held") } if len(used) > 0 { if err = s.enqueue(t, wire.FrameUsage, "", wire.UsageReport{StepID: r.StepID, Rows: used}); err != nil { return err } } rep.Attempt, rep.State, rep.Reason = next.Attempt, wire.StepRunning, "" return s.enqueue(t, wire.FrameStep, "", rep) }) if err == nil { r.DispatchCommand = next r.Phase = phaseNone } return err } // stepAcked finishes an attempt once the instance acked its final report. func stepAcked(t *sql.Tx, body string) error { var r wire.StepReport if err := json.Unmarshal([]byte(body), &r); err != nil { return err } if !wire.StepTerminal(r.State) { return nil } _, err := t.Exec("UPDATE steps SET state=? WHERE step_id=? AND attempt=? AND state IN (?,?)", runDone, r.StepID, r.Attempt, runReported, runSuperseded) return err } // finishedSteps are the attempts whose final report the instance acked. func (s *State) finishedSteps(ctx context.Context) ([]stepRow, error) { // A failed push keeps its private repository (and commit) for a // republish, until an attempt of that step has published. 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) if err != nil { return nil, err } defer rows.Close() var out []stepRow for rows.Next() { var r stepRow if err = rows.Scan(&r.StepID, &r.Attempt); err != nil { return nil, err } out = append(out, r) } return out, rows.Err() } // syncSteps lists every attempt this runner still holds: running, its // final report not yet acked, or (state "pending") ended with its // termination unverified. An attempt is absent only once the runner has // no record of it left to report, so the instance may infer its end. func (s *State) syncSteps(ctx context.Context) ([]wire.StepRun, error) { 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) if err != nil { return nil, err } defer rows.Close() out := []wire.StepRun{} for rows.Next() { var r wire.StepRun if err = rows.Scan(&r.TaskID, &r.StepID, &r.Attempt, &r.State, &r.CandidateSHA); err != nil { return nil, err } out = append(out, r) } return out, rows.Err() } // pendingStep is an attempt waiting for its termination proof. type pendingStep struct { step, task, state, reason, ns string attempt int64 } func (s *State) pendingSteps(ctx context.Context) ([]pendingStep, error) { rows, err := s.db.QueryContext(ctx, "SELECT step_id, attempt, task_id, final_state, final_reason, ns_id FROM steps WHERE state=?", runPending) if err != nil { return nil, err } defer rows.Close() var out []pendingStep for rows.Next() { var p pendingStep if err = rows.Scan(&p.step, &p.attempt, &p.task, &p.state, &p.reason, &p.ns); err != nil { return nil, err } out = append(out, p) } return out, rows.Err() } // proveTermination sends the follow-up report for a pending attempt // whose exit is now verified; its ack finishes the attempt. func (s *State) proveTermination(ctx context.Context, p pendingStep) error { return s.tx(ctx, func(t *sql.Tx) error { res, err := t.Exec("UPDATE steps SET state=? WHERE step_id=? AND attempt=? AND state=?", runReported, p.step, p.attempt, runPending) if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return nil } renders, err := reportRenders(t, p.step, p.attempt) if err != nil { return err } 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}) }) } const unrecordedPrefix = "step:" // UnrecordedStep names an attempt that recorded no namespace or process // group before the runner stopped. Verify must prove it ended on its own // terms: no namespace of this runner left (Linux), no process carrying // its marker (a worker). func UnrecordedStep(key string) string { return unrecordedPrefix + key } // unrecordedKey is the step key of an UnrecordedStep record. func unrecordedKey(id string) (string, bool) { return strings.CutPrefix(id, unrecordedPrefix) } // RecoverSteps settles attempts a previous process left running. Its // namespaces died with it and startup verified their exits, so an // attempt that had not committed has ended: failed (or cancelled), with // termination when verify confirms its namespace's exit, else pending. // A committed one only has its push left, which the engine reconciles; // a merge runs again and reconciles from its record. func (s *State) RecoverSteps(ctx context.Context, verify func(context.Context, string) bool) error { var all []stepRow ns := map[string]string{} rows, err := s.db.QueryContext(ctx, "SELECT body, state, cancel, phase, base_sha, candidate_sha, ns_id, hold FROM steps WHERE state=?", runRunning) if err != nil { return err } for rows.Next() { var id, hold string r, err := scanStep(func(dest ...any) error { return rows.Scan(append(dest, &id, &hold)...) }) if err != nil { rows.Close() return err } if hold != "" && id == "" && !r.Cancel { // Held by the scheduler and never launched since (an admission // clears the hold; a launch records its namespace): nothing of // it ran, so it keeps its hold and its wake-up. continue } all = append(all, r) ns[r.key()] = id } rows.Close() proven := map[string]bool{} for _, r := range all { // An attempt that recorded nothing is never taken as ended: verify // is asked about the step itself (UnrecordedStep), and says so only // once nothing of it can be left. if ns[r.key()] == "" { ns[r.key()] = UnrecordedStep(r.key()) } proven[r.key()] = verify == nil || verify(ctx, ns[r.key()]) } return s.tx(ctx, func(t *sql.Tx) error { for _, r := range all { 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 { return err } rep := wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, BaseSHA: r.Base, Termination: proven[r.key()]} if rep.Termination { rep.TerminationKind = terminationKind(ns[r.key()]) } switch { case committed(r.Phase): continue case r.Specialist == wire.SpecialistMerge && !r.Cancel: // A merge settles itself from its record and the default // branch: it runs again and never merges twice. continue case r.Specialist == wire.SpecialistPreview && r.Phase == phasePreviewPublishing, r.Specialist == wire.SpecialistPublish && (r.Phase == phaseSitePublishing || r.Phase == phaseSiteMinting): // A preview or a site publish that may have changed Carloku // reconciles from the marker, cancelled or not; it never sends // again, and its outcome is never lost to a plain "cancelled". continue case r.Specialist == wire.SpecialistChecks && r.Phase == phaseHosted && !r.Cancel: // Old hosted waits ran nothing locally. Resume them through // the current base-gate executor, which never trusts hosted CI. continue case r.Cancel: rep.State, rep.Reason = wire.StepCancelled, "cancelled" default: rep.State, rep.Reason = wire.StepFailed, "runner_restarted" } next := runReported if !rep.Termination { next = runPending } 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 { return err } var err error if rep.Renders, err = reportRenders(t, r.StepID, r.Attempt); err != nil { return err } if err := s.enqueue(t, wire.FrameStep, "", rep); err != nil { return err } } return nil }) } // StepFunc executes one attempt. progress sends interim reports; the // returned report is final, with Termination only once the attempt's // namespace exit was observed. type StepFunc func(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport // StepEngine runs step attempts one at a time from the durable table. type StepEngine struct { State *State Exec StepFunc // Ask answers questions from the same queue, oldest first with the // steps, so a question never runs beside a step. Ask AskFunc Notify func() Logger *slog.Logger // Sweep tidies attempts whose final report was acked; it runs at start // and whenever the worker wakes. Sweep func(context.Context) // Verify reports whether a namespace's exit is verified now (its // record released after proof, or gone). Verify func(ctx context.Context, nsID string) bool // Acknowledge, if set, is told of each namespace whose proven exit // is committed here: only then may the proof's evidence go (a Mac's). Acknowledge func(ctx context.Context, nsID string) // TerminationKind is how this runner proves an attempt's end // (wire.TerminationNamespace on Linux), reported with termination. TerminationKind string // Meter is the metered guard: a question on a metered connection // passes it (askmetered.go). MeteredAsk is the harness that answers // one (S2's Pi); nil, such a question cannot run here. Meter *metered.Meter MeteredAsk MeteredAskFunc mu sync.Mutex wake chan struct{} cancel context.CancelFunc // cur is the step (or "ask:" question) running now and curAttempt // the attempt it was taken at; a step moves to later attempts while // it runs (a refusal fails over), so a cancel for any of them stops it. cur string curAttempt int64 wg sync.WaitGroup } // Probe re-checks attempts whose termination is pending; a verified exit // sends the follow-up report with termination. It runs at start and on // every sync with the instance. func (e *StepEngine) Probe(ctx context.Context) { if e.Verify == nil { return } sent := false // Questions held for their namespace's proof are released once it is // verified. held, err := e.State.heldAsks(ctx) if err != nil { e.log("ask probe", err) } for _, h := range held { // Never released unverified: with no namespace recorded, Verify // requires that no namespace of this runner remains at all. if !e.Verify(ctx, h.ns) { continue } e.log("ask probe", e.State.releaseAsk(ctx, h)) sent = true } pending, err := e.State.pendingSteps(ctx) if err != nil { e.log("step probe", err) return } for _, p := range pending { if !e.Verify(ctx, p.ns) { continue } err := e.State.proveTermination(ctx, p) e.log("step probe", err) if err == nil && e.Acknowledge != nil { e.Acknowledge(ctx, p.ns) } sent = true } if e.Meter != nil { // A metered slot whose ended attempt's exit is proven now is // released, with its charge or the spend unknown. One still // unproven stays held, and is tried again at the next probe. _ = e.Meter.Recover(ctx) } if sent && e.Notify != nil { e.Notify() } } // recoverSteps is State.RecoverSteps, acknowledging each proven exit // once the recovery has committed it. func (e *StepEngine) recoverSteps(ctx context.Context) error { verify, proven := e.Verify, []string{} if verify != nil && e.Acknowledge != nil { verify = func(ctx context.Context, id string) bool { ok := e.Verify(ctx, id) if ok { proven = append(proven, id) } return ok } } if err := e.State.RecoverSteps(ctx, verify); err != nil { return err } for _, id := range proven { e.Acknowledge(ctx, id) } return nil } // Start recovers what a previous process left and starts the worker. func (e *StepEngine) Start(ctx context.Context) error { if err := e.recoverSteps(ctx); err != nil { return err } if err := e.State.RecoverAsks(ctx, e.Verify); err != nil { return err } e.Probe(ctx) e.mu.Lock() e.wake = make(chan struct{}, 1) e.mu.Unlock() e.Notify() e.wg.Add(1) go e.loop(ctx) e.Wake() return nil } // Wait returns once the worker stopped. func (e *StepEngine) Wait() { e.wg.Wait() } // Wake makes the worker look for attempts. func (e *StepEngine) Wake() { e.mu.Lock() defer e.mu.Unlock() if e.wake == nil { return } select { case e.wake <- struct{}{}: default: } } // CancelAsk interrupts a question's attempt if it is running now. func (e *StepEngine) CancelAsk(question string, attempt int64) { e.Cancel("ask:"+question, attempt) } // Cancel interrupts the attempt if it is the one running now. func (e *StepEngine) Cancel(step string, attempt int64) { e.mu.Lock() defer e.mu.Unlock() if e.cur == step && attempt >= e.curAttempt && e.cancel != nil { e.cancel() } } func (e *StepEngine) log(msg string, err error) { if e.Logger != nil && err != nil { e.Logger.Warn(msg, "err", sanitize(err)) } } func (e *StepEngine) loop(ctx context.Context) { defer e.wg.Done() // The sweep also runs hourly, so kept sessions past retention go on // an idle runner too. hourly := time.NewTicker(time.Hour) defer hourly.Stop() for { select { case <-ctx.Done(): return case <-e.wake: case <-hourly.C: } if e.Sweep != nil { e.Sweep(ctx) } for ctx.Err() == nil { // Nothing runs beside an earlier attempt whose namespace's exit // is not verified yet: try again shortly. if e.held(ctx) { time.AfterFunc(heldRetry, e.Wake) break } r, ok, err := e.State.nextStep(ctx) if err != nil { e.log("step state", err) break } a, asked, err := e.State.nextAsk(ctx) if err != nil { e.log("ask state", err) break } if !asked || e.Ask == nil { if !ok { break } e.runOne(ctx, r) continue } // Steps and questions in arrival order, one at a time. if ok && !earlier(a.Created, r.Created) { e.runOne(ctx, r) continue } e.askOne(ctx, a) } // A deferred attempt (a merge waiting for the hub's CI) wakes the // worker when it is due, also after a restart; so does a question // held for its metered connection's budget at the next day. if due, ok := e.State.nextDue(ctx); ok { time.AfterFunc(max(time.Until(due), 10*time.Millisecond), e.Wake) } } } // heldRetry is how soon a worker held by an unverified exit looks again. var heldRetry = 5 * time.Second // held probes, then reports whether a step or question attempt still // waits for its namespace's exit to be verified (or the state cannot // tell). func (e *StepEngine) held(ctx context.Context) bool { e.Probe(ctx) steps, err := e.State.pendingSteps(ctx) if err != nil { e.log("step state", err) return true } asks, err := e.State.heldAsks(ctx) if err != nil { e.log("ask state", err) return true } return len(steps) > 0 || len(asks) > 0 } // earlier compares two recorded times (RFC 3339, variable precision). func earlier(a, b string) bool { x, errA := time.Parse(time.RFC3339Nano, a) y, errB := time.Parse(time.RFC3339Nano, b) if errA != nil || errB != nil { return a < b } return x.Before(y) } func (e *StepEngine) askOne(ctx context.Context, a askRow) { report := func(rep wire.AnswerReport) { e.log("answer report", e.State.ReportAnswer(context.WithoutCancel(ctx), a, rep)) e.Notify() } if a.Cancel { report(wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt, State: wire.QuestionCancelled, Reason: "cancelled"}) return } actx, cancel := context.WithCancel(ctx) defer cancel() e.mu.Lock() e.cancel, e.cur, e.curAttempt = cancel, "ask:"+a.QuestionID, a.Attempt e.mu.Unlock() defer func() { e.mu.Lock() e.cancel, e.cur = nil, "" e.mu.Unlock() }() if e.State.askCancelled(ctx, a) { cancel() } if local, model, ok := e.meteredAsk(ctx, a); ok { // On a metered connection: the guard admits it, with the start. e.askMetered(ctx, actx, a, local, model, report) return } // Started, durably, before the provider runs: never run twice. if err := e.State.startAsk(ctx, a); err != nil { e.log("ask start", err) return } res := e.Ask(actx, a, func(p wire.AnswerReport) { p.State = wire.QuestionRunning report(p) }) rep := res.Report if actx.Err() != nil && rep.State != wire.QuestionAnswered { rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" } if !wire.QuestionTerminal(rep.State) { rep.State, rep.Reason = wire.QuestionFailed, "provider_failed" } // The result is kept in memory until it is saved: a failed write is // tried again, never the provider. Shutting down before then, the // next start ends the attempt (runner_restarted). for i := 0; ; i++ { err := e.State.FinishAsk(context.WithoutCancel(ctx), a, rep, res.Terminated) if err == nil { break } e.log("answer report", err) select { case <-ctx.Done(): return case <-time.After(min(time.Duration(i+1)*100*time.Millisecond, 5*time.Second)): } } e.Notify() } func (e *StepEngine) runOne(ctx context.Context, r stepRow) { report := func(rep wire.StepReport) { if rep.Termination && rep.TerminationKind == "" { rep.TerminationKind = e.TerminationKind } e.log("step report", e.State.ReportStep(context.WithoutCancel(ctx), r, rep)) e.Notify() } // A site publish that may have changed CARLOS reconciles from its // marker even when cancelled: its outcome is never lost to a plain // "cancelled" (publishSite never sends again in these phases). siteReconciles := r.Specialist == wire.SpecialistPublish && (r.Phase == phaseSitePublishing || r.Phase == phaseSiteMinting) if r.Cancel && !siteReconciles { report(wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, State: wire.StepCancelled, Reason: "cancelled", BaseSHA: r.Base, Termination: true}) return } sctx, cancel := context.WithCancel(ctx) defer cancel() e.mu.Lock() e.cancel, e.cur, e.curAttempt = cancel, r.StepID, r.Attempt e.mu.Unlock() defer func() { e.mu.Lock() e.cancel, e.cur = nil, "" e.mu.Unlock() }() // A cancel that arrived between nextStep and now is still honoured. if e.State.stepCancelled(ctx, r) { cancel() } rep := e.Exec(sctx, r, func(p wire.StepReport) { p.State = wire.StepRunning report(p) }) if ctx.Err() != nil { // Shutting down: the attempt stays held; the next start settles it. return } if rep.State == stepDeferred && rep.Hold != nil { // Held by the scheduler: kept with its wake-up, said once per // hold (state running; the instance keeps it queued), and looked // at again then or when a fact changes. // The step may have moved to a later attempt (a failover) first. held := r held.Attempt = max(rep.Attempt, r.Attempt) changed, err := e.State.holdStep(context.WithoutCancel(ctx), held, rep.Hold) e.log("step hold", err) if changed { out := rep out.State = wire.StepRunning report(out) } return } if rep.State == stepDeferred { // Held for later; the queue moves on meanwhile. e.log("step defer", e.State.deferStep(context.WithoutCancel(ctx), r, mergeCIPoll)) time.AfterFunc(mergeCIPoll, e.Wake) return } // A merge reports its real outcome even when asked to stop: the hub // may have merged it (the instance refuses cancels while merging). if sctx.Err() != nil && rep.State != wire.StepDone && r.Specialist != wire.SpecialistMerge { rep.State, rep.Reason = wire.StepCancelled, "cancelled" } if !wire.StepTerminal(rep.State) { rep.State, rep.Reason = wire.StepFailed, "provider_failed" } report(rep) } // stepWait bounds one wait for the lease before an attempt starts. const stepWait = time.Second // terminationKind is how a recorded attempt's end was proven: a process // group ("pg:" records, a worker) or a namespace. func terminationKind(record string) string { if strings.HasPrefix(record, "pg:") { return wire.TerminationProcessGroup } if strings.HasPrefix(record, unrecordedPrefix) { return "" } return wire.TerminationNamespace } // starter launches a contained process, calling record with its // namespace before the launch (and again once it runs); a record error // launches nothing (containment.Manager.StartRecorded). type starter interface { StartRecorded(context.Context, provider.Launch, []string, func(context.Context, containment.Record) error) (provider.Process, error) } // recordedStart starts a step's or question's process with its namespace // written durably before it launches. func recordedStart(ctx context.Context, m starter, l provider.Launch, argv []string, record func(context.Context, string) error) (provider.Process, error) { return recordedStartKept(ctx, m, l, argv, record, nil) }