| 1 | package team |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | ) |
| 8 | |
| 9 | // ResumeReport is what Resume did before (or instead of) lifting the |
| 10 | // admission pause. |
| 11 | type ResumeReport struct { |
| 12 | Jobs int // non-terminal jobs found |
| 13 | Revalidated []JobID // grants confirmed online and snapshots refreshed |
| 14 | Cancelled []JobID // grants observed revoked; cancelled through the ordinary path |
| 15 | Reconciled []ActionID // in-flight actions resolved through their adapters |
| 16 | Unresolved []ActionID // still uncertain; their jobs stay waiting |
| 17 | Expired []AttemptID |
| 18 | Quarantine bool // still quarantined after this pass |
| 19 | Why string // quarantine reason when so |
| 20 | Resumed bool // admission is open |
| 21 | } |
| 22 | |
| 23 | // Resume is the startup reconciliation. Admission stays paused until it |
| 24 | // completes. For every non-terminal job it revalidates the grant online: |
| 25 | // a revocation cancels the job, an unavailable authority aborts the pass |
| 26 | // (ErrAuthorityUnavailable) with nothing resumed. Every action left |
| 27 | // dispatching by the previous incarnation becomes uncertain and is |
| 28 | // reconciled through its adapter; what stays uncertain keeps its job |
| 29 | // waiting. After an unclean shutdown, all uncertain actions need receipts |
| 30 | // or conservative audited charges before admission reopens. Missing or |
| 31 | // mismatched external history stays quarantined until an owner releases it. |
| 32 | func (s *Store) Resume(ctx context.Context) (ResumeReport, error) { |
| 33 | s.recoveryMu.Lock() |
| 34 | defer s.recoveryMu.Unlock() |
| 35 | var rep ResumeReport |
| 36 | type jobRef struct { |
| 37 | scope Scope |
| 38 | grant GrantSnapshot |
| 39 | tgt TargetBinding |
| 40 | project ProjectID |
| 41 | } |
| 42 | var jobs []jobRef |
| 43 | err := s.tx(ctx, func(tx *sql.Tx) error { |
| 44 | var paused, restore int |
| 45 | if err := tx.QueryRowContext(ctx, `SELECT admission_paused, restore_uncertain FROM service WHERE id=1`).Scan(&paused, &restore); err != nil { |
| 46 | return err |
| 47 | } |
| 48 | |
| 49 | if paused == 0 { |
| 50 | var stale int |
| 51 | if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM jobs WHERE grant_stale=1 AND state NOT IN ('succeeded','failed','cancelled')`).Scan(&stale); err != nil { |
| 52 | return err |
| 53 | } |
| 54 | if stale == 0 { |
| 55 | return fail(CodeState, "recovery requires paused admission or stale grants") |
| 56 | } |
| 57 | } |
| 58 | // An old snapshot's intents may have executed after the backup. |
| 59 | // Classify them before revocation can otherwise release their budgets. |
| 60 | if restore != 0 { |
| 61 | if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='uncertain', last_error='restored intent may have executed after snapshot' WHERE state='intent'`); err != nil { |
| 62 | return err |
| 63 | } |
| 64 | } |
| 65 | if err := settleRecoveredUnknown(ctx, tx, s.clock.Now()); err != nil { |
| 66 | return err |
| 67 | } |
| 68 | rows, err := tx.QueryContext(ctx, `SELECT `+jobColumns+` FROM jobs WHERE state NOT IN ('succeeded','failed','cancelled') ORDER BY id`) |
| 69 | if err != nil { |
| 70 | return fail(CodeInvalid, "jobs: %v", err) |
| 71 | } |
| 72 | defer rows.Close() |
| 73 | for rows.Next() { |
| 74 | j, err := scanJob(rows) |
| 75 | if err != nil { |
| 76 | return err |
| 77 | } |
| 78 | jobs = append(jobs, jobRef{Scope{j.Account, j.ID}, j.Grant, j.Target, j.Project}) |
| 79 | } |
| 80 | return rows.Err() |
| 81 | }) |
| 82 | if err != nil { |
| 83 | return rep, err |
| 84 | } |
| 85 | rep.Jobs = len(jobs) |
| 86 | for _, jr := range jobs { |
| 87 | adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: jr.grant.Ref, Account: jr.scope.Account, Project: jr.project, Target: jr.tgt, Operation: OpJobContinue}) |
| 88 | switch { |
| 89 | case errors.Is(err, ErrGrantRevoked): |
| 90 | if err := s.tx(ctx, func(tx *sql.Tx) error { |
| 91 | j, err := loadJob(ctx, tx, jr.scope) |
| 92 | if err != nil { |
| 93 | return err |
| 94 | } |
| 95 | if j.State.Terminal() { |
| 96 | return nil |
| 97 | } |
| 98 | _, err = terminate(ctx, tx, j, JobCancelled, "authority", "grant revoked during recovery", s.clock.Now()) |
| 99 | return err |
| 100 | }); err != nil { |
| 101 | return rep, err |
| 102 | } |
| 103 | rep.Cancelled = append(rep.Cancelled, jr.scope.Job) |
| 104 | continue |
| 105 | case err != nil: |
| 106 | return rep, err |
| 107 | } |
| 108 | refreshed := false |
| 109 | err = s.tx(ctx, func(tx *sql.Tx) error { |
| 110 | j, err := loadJob(ctx, tx, jr.scope) |
| 111 | if err != nil { |
| 112 | return err |
| 113 | } |
| 114 | if j.State.Terminal() { |
| 115 | return nil |
| 116 | } |
| 117 | checked := j |
| 118 | checked.grantStale = false |
| 119 | checked.Grant.Version = adm.Version |
| 120 | checked.Grant.Epoch = adm.Epoch |
| 121 | if err := checkAdmission(checked, adm, s.clock.Now()); err != nil { |
| 122 | return err |
| 123 | } |
| 124 | if adm.Version != j.Grant.Version || adm.Epoch != j.Grant.Epoch { |
| 125 | if err := s.FenceGrantsTx(ctx, tx, []GrantChange{{Ref: adm.Grant, Version: adm.Version, Epoch: adm.Epoch}}); err != nil { |
| 126 | return err |
| 127 | } |
| 128 | j.grantStale = true |
| 129 | } |
| 130 | if err := checkGrantFence(ctx, tx, adm); err != nil { |
| 131 | return err |
| 132 | } |
| 133 | var pending int |
| 134 | if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM attempts WHERE job_id=? AND containment='pending'`, j.ID).Scan(&pending); err != nil { |
| 135 | return err |
| 136 | } |
| 137 | if j.grantStale && pending > 0 { |
| 138 | return nil |
| 139 | } |
| 140 | now := s.clock.Now() |
| 141 | if _, err := tx.ExecContext(ctx, `UPDATE jobs SET grant_stale=0, grant_version=?, grant_epoch=?, grant_observed_at=? WHERE id=?`, adm.Version, adm.Epoch, ts(now), int64(j.ID)); err != nil { |
| 142 | return fail(CodeInvalid, "snapshot: %v", err) |
| 143 | } |
| 144 | refreshed = true |
| 145 | if j.grantStale || adm.Version != j.Grant.Version || adm.Epoch != j.Grant.Epoch { |
| 146 | return appendEvent(ctx, tx, jr.scope, "grant.revalidated", "resume", map[string]any{"from": j.Grant.Version, "to": adm.Version, "epoch": adm.Epoch}, now) |
| 147 | } |
| 148 | return nil |
| 149 | }) |
| 150 | if err != nil { |
| 151 | return rep, err |
| 152 | } |
| 153 | if refreshed { |
| 154 | rep.Revalidated = append(rep.Revalidated, jr.scope.Job) |
| 155 | } |
| 156 | } |
| 157 | // Actions the dead incarnation had admitted may have run: treat them as |
| 158 | // uncertain and ask the adapters. |
| 159 | type actRef struct { |
| 160 | scope Scope |
| 161 | id ActionID |
| 162 | } |
| 163 | var acts []actRef |
| 164 | err = s.tx(ctx, func(tx *sql.Tx) error { |
| 165 | now := s.clock.Now() |
| 166 | if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='uncertain', last_error='incarnation ended while dispatching', updated_at=? WHERE state='dispatching' AND admitted_incarnation<>?`, ts(now), s.incarnation); err != nil { |
| 167 | return fail(CodeInvalid, "actions: %v", err) |
| 168 | } |
| 169 | if err := settleRecoveredUnknown(ctx, tx, now); err != nil { |
| 170 | return err |
| 171 | } |
| 172 | rows, err := tx.QueryContext(ctx, `SELECT a.id, j.id, j.account FROM actions a JOIN jobs j ON j.id=a.job_id JOIN reservations r ON r.id=a.reservation_id WHERE a.state='uncertain' AND r.state<>'settled_audited' ORDER BY a.id`) |
| 173 | if err != nil { |
| 174 | return fail(CodeInvalid, "actions: %v", err) |
| 175 | } |
| 176 | defer rows.Close() |
| 177 | for rows.Next() { |
| 178 | var a, j int64 |
| 179 | var acct string |
| 180 | if err := rows.Scan(&a, &j, &acct); err != nil { |
| 181 | return fail(CodeInvalid, "actions: %v", err) |
| 182 | } |
| 183 | acts = append(acts, actRef{Scope{AccountID(acct), JobID(j)}, ActionID(a)}) |
| 184 | } |
| 185 | return rows.Err() |
| 186 | }) |
| 187 | if err != nil { |
| 188 | return rep, err |
| 189 | } |
| 190 | for _, ar := range acts { |
| 191 | if _, err := s.Reconcile(ctx, ar.scope, ar.id); err != nil { |
| 192 | if errors.Is(err, ErrUncertain) { |
| 193 | rep.Unresolved = append(rep.Unresolved, ar.id) |
| 194 | continue |
| 195 | } |
| 196 | return rep, err |
| 197 | } |
| 198 | rep.Reconciled = append(rep.Reconciled, ar.id) |
| 199 | } |
| 200 | err = s.tx(ctx, func(tx *sql.Tx) error { |
| 201 | now := s.clock.Now() |
| 202 | // RFC3339Nano omits trailing fractional zeros; text order is not |
| 203 | // time order. Compare parsed deadlines, including old stored rows. |
| 204 | rows, err := tx.QueryContext(ctx, `SELECT id, lease_deadline FROM attempts WHERE state='active'`) |
| 205 | if err != nil { |
| 206 | return fail(CodeInvalid, "attempts: %v", err) |
| 207 | } |
| 208 | for rows.Next() { |
| 209 | var id int64 |
| 210 | var deadline string |
| 211 | if err := rows.Scan(&id, &deadline); err != nil { |
| 212 | rows.Close() |
| 213 | return fail(CodeInvalid, "attempts: %v", err) |
| 214 | } |
| 215 | if !parseTS(deadline).After(now) { |
| 216 | rep.Expired = append(rep.Expired, AttemptID(id)) |
| 217 | } |
| 218 | } |
| 219 | if err := rows.Err(); err != nil { |
| 220 | rows.Close() |
| 221 | return err |
| 222 | } |
| 223 | rows.Close() |
| 224 | for _, id := range rep.Expired { |
| 225 | if _, err := tx.ExecContext(ctx, `UPDATE attempts SET state='expired', updated_at=? WHERE id=? AND state='active'`, ts(now), int64(id)); err != nil { |
| 226 | return fail(CodeInvalid, "expire: %v", err) |
| 227 | } |
| 228 | } |
| 229 | var quarantine, restore, releaseRequired int |
| 230 | var why string |
| 231 | if err := tx.QueryRowContext(ctx, `SELECT quarantine, quarantine_why, restore_uncertain, release_required FROM service WHERE id=1`).Scan(&quarantine, &why, &restore, &releaseRequired); err != nil { |
| 232 | return fail(CodeInvalid, "service: %v", err) |
| 233 | } |
| 234 | if err := recoveryEvent(ctx, tx, "reconcile", "resume", "reconciliation completed", ""); err != nil { |
| 235 | return err |
| 236 | } |
| 237 | snap, err := recoverySnapshot(ctx, tx) |
| 238 | if err != nil { |
| 239 | return err |
| 240 | } |
| 241 | if _, err = tx.ExecContext(ctx, `UPDATE recovery_events SET snapshot_hash=? WHERE revision=?`, snap.Hash, snap.Revision); err != nil { |
| 242 | return err |
| 243 | } |
| 244 | if _, err := tx.ExecContext(ctx, `UPDATE service SET reconciled_revision=recovery_revision WHERE id=1`); err != nil { |
| 245 | return err |
| 246 | } |
| 247 | if restore != 0 || (quarantine != 0 && (releaseRequired != 0 || len(rep.Unresolved) > 0)) { |
| 248 | rep.Quarantine, rep.Why = true, why+"; "+itoa(len(rep.Unresolved))+" actions unresolved" |
| 249 | if restore != 0 { |
| 250 | rep.Why = "restored history requires operator recovery; missing post-snapshot work cannot be inferred" |
| 251 | } |
| 252 | _, err := tx.ExecContext(ctx, `UPDATE service SET quarantine_why=? WHERE id=1`, rep.Why) |
| 253 | if err != nil { |
| 254 | return fail(CodeInvalid, "service: %v", err) |
| 255 | } |
| 256 | return nil |
| 257 | } |
| 258 | if _, err := tx.ExecContext(ctx, `UPDATE service SET admission_paused=0, quarantine=0, quarantine_why='' WHERE id=1`); err != nil { |
| 259 | return fail(CodeInvalid, "service: %v", err) |
| 260 | } |
| 261 | rep.Resumed = true |
| 262 | return nil |
| 263 | }) |
| 264 | return rep, err |
| 265 | } |
| 266 | |