oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package team
2
3import (
4 "context"
5 "database/sql"
6 "errors"
7 "strings"
8 "time"
9)
10
11const attemptColumns = `id, job_id, step_id, number, runner, workspace, fence, lease_deadline, state, containment, stop_requested, stop_acked, provider, model, effort, outcome, created_at, updated_at`
12
13func scanAttempt(r rowScanner) (Attempt, error) {
14 var a Attempt
15 var lease, state, cont, stopReq, stopAck, created, updated string
16 if err := r.Scan(&a.ID, &a.Job, &a.Step, &a.Number, &a.Runner, &a.Workspace, &a.Fence, &lease, &state, &cont, &stopReq, &stopAck,
17 &a.Provider, &a.Model, &a.Effort, &a.Outcome, &created, &updated); err != nil {
18 return a, err
19 }
20 a.State, a.Containment = AttemptState(state), Containment(cont)
21 if !a.State.Valid() || (a.Containment != ContainmentPending && a.Containment != ContainmentContained) {
22 return a, fail(CodeUnknownKind, "attempt %d stored %q/%q", a.ID, state, cont)
23 }
24 a.LeaseDeadline, a.StopRequested, a.StopAcked = parseTS(lease), parseTS(stopReq), parseTS(stopAck)
25 a.CreatedAt, a.UpdatedAt = parseTS(created), parseTS(updated)
26 return a, nil
27}
28
29func loadAttempt(ctx context.Context, tx *sql.Tx, job JobID, id AttemptID) (Attempt, error) {
30 a, err := scanAttempt(tx.QueryRowContext(ctx, `SELECT `+attemptColumns+` FROM attempts WHERE job_id=? AND id=?`, int64(job), int64(id)))
31 if errors.Is(err, sql.ErrNoRows) {
32 return a, fail(CodeScope, "attempt %d", id)
33 }
34 return a, err
35}
36
37// holder is what a checked Handle resolves to inside a transaction.
38type holder struct {
39 job jobRow
40 step Step
41 attempt Attempt
42}
43
44// current resolves h against stored rows and fails closed on any
45// difference: unknown attempt, other runner, fence behind the step's,
46// attempt not active, lease expired. Nothing in h is trusted.
47func current(ctx context.Context, tx *sql.Tx, scope Scope, h Handle, now time.Time) (holder, error) {
48 j, err := loadJob(ctx, tx, scope)
49 if err != nil {
50 return holder{}, err
51 }
52 a, err := loadAttempt(ctx, tx, j.ID, h.Attempt)
53 if err != nil {
54 return holder{}, err
55 }
56 if j.grantStale {
57 return holder{}, fail(CodeGrantStale, "job grant needs reconciliation")
58 }
59 if a.Runner != h.Runner || a.Fence != h.Fence {
60 return holder{}, fail(CodeFence, "handle does not match attempt %d", a.ID)
61 }
62 st, err := loadStep(ctx, tx, j.ID, a.Step)
63 if err != nil {
64 return holder{}, err
65 }
66 if st.Fence != a.Fence || st.Holder != a.ID {
67 return holder{}, fail(CodeFence, "attempt %d fence %d, step at %d", a.ID, a.Fence, st.Fence)
68 }
69 if a.State != AttemptActive {
70 return holder{}, fail(CodeFence, "attempt %d is %s", a.ID, a.State)
71 }
72 if !now.Before(a.LeaseDeadline) {
73 return holder{}, fail(CodeLeaseExpired, "attempt %d lease ended %s", a.ID, a.LeaseDeadline.Format(time.RFC3339))
74 }
75 if j.State.Terminal() {
76 return holder{}, fail(CodeState, "job %d is %s", j.ID, j.State)
77 }
78 return holder{job: j, step: st, attempt: a}, nil
79}
80
81// Claim takes the step for runner under a fresh attempt and fence. In one
82// transaction it checks admission, job state and deadline, step state,
83// containment of any prior attempt, dependencies, the per-step attempt
84// cap, the job and account concurrency caps and the workspace identity,
85// then writes the attempt with a lease and the step's next fence.
86func (s *Store) Claim(ctx context.Context, scope Scope, stepKey, runner, workspace string) (Handle, error) {
87 return s.ClaimRevision(ctx, scope, 0, stepKey, runner, workspace)
88}
89
90func (s *Store) ClaimRevision(ctx context.Context, scope Scope, expectedRevision int64, stepKey, runner, workspace string) (Handle, error) {
91 if runner == "" || workspace == "" {
92 return Handle{}, fail(CodeInvalid, "claim needs runner and workspace identities")
93 }
94 var h Handle
95 err := s.tx(ctx, func(tx *sql.Tx) error {
96 if err := admissionOpen(ctx, tx); err != nil {
97 return err
98 }
99 now := s.clock.Now()
100 j, err := loadJob(ctx, tx, scope)
101 if err != nil {
102 return err
103 }
104 if expectedRevision != 0 && j.Revision != expectedRevision {
105 return ErrRevision
106 }
107 if j.grantStale {
108 return fail(CodeGrantStale, "job grant needs reconciliation")
109 }
110 switch {
111 case j.State.Terminal():
112 return fail(CodeState, "job %d is %s", j.ID, j.State)
113 case j.State == JobWaiting && !j.Wait.claimable():
114 return fail(CodeState, "job %d waiting for %s", j.ID, j.Wait)
115 case j.State == JobVerifying:
116 return fail(CodeState, "job %d is verifying", j.ID)
117 }
118 if now.Sub(j.CreatedAt) > time.Duration(j.Policy.JobSeconds)*time.Second {
119 return fail(CodeQuota, "job %d past its %ds budget", j.ID, j.Policy.JobSeconds)
120 }
121 st, err := loadStepByKey(ctx, tx, j.ID, stepKey)
122 if err != nil {
123 return err
124 }
125 if j.Evidence.Predicate == PredicateSoftwareFeature && st.Capability == CapImplement {
126 if err := featureBuildReady(ctx, tx, j); err != nil {
127 return err
128 }
129 }
130 if (j.Target.Kind == TargetConversation) != (st.Capability == CapCoordinate) {
131 return ErrScope
132 }
133 if j.Target.Kind == TargetProjectRead && st.Capability != CapResearch {
134 return ErrScope
135 }
136 if st.State != StepPending && st.State != StepRunning {
137 return fail(CodeState, "step %q is %s", st.Key, st.State)
138 }
139 // A prior attempt still pending containment blocks a reclaim, whatever
140 // its lease says: expiry is not proof the worker stopped.
141 var prior int64
142 var priorState string
143 err = tx.QueryRowContext(ctx, `SELECT id, state FROM attempts WHERE step_id=? AND containment='pending'`, int64(st.ID)).Scan(&prior, &priorState)
144 switch {
145 case err == nil:
146 if AttemptState(priorState) == AttemptActive {
147 a, err := loadAttempt(ctx, tx, j.ID, AttemptID(prior))
148 if err != nil {
149 return err
150 }
151 if now.Before(a.LeaseDeadline) {
152 return fail(CodeState, "step %q held by attempt %d", st.Key, prior)
153 }
154 }
155 // Expired, released or stopping: the supervisor's Contain comes first.
156 return fail(CodeContainment, "attempt %d of step %q not yet contained", prior, st.Key)
157 case !errors.Is(err, sql.ErrNoRows):
158 return fail(CodeInvalid, "prior attempt: %v", err)
159 }
160 if st.State == StepRunning {
161 // Running with no attempt pending containment cannot happen; refuse
162 // rather than guess.
163 return fail(CodeState, "step %q running without a live attempt", st.Key)
164 }
165 for _, dep := range st.DependsOn {
166 d, err := loadStepByKey(ctx, tx, j.ID, dep)
167 if err != nil {
168 return err
169 }
170 if d.State != StepSucceeded {
171 return fail(CodeDependency, "step %q waits for %q (%s)", st.Key, dep, d.State)
172 }
173 var uncontained int
174 if err := tx.QueryRowContext(ctx, "SELECT count(*) FROM attempts WHERE step_id=? AND containment='pending'", d.ID).Scan(&uncontained); err != nil {
175 return err
176 }
177 if uncontained > 0 {
178 return ErrContainment
179 }
180
181 }
182 if st.Attempts >= j.Policy.MaxAttemptsPerStep {
183 return fail(CodeQuota, "step %q used its %d attempts", st.Key, j.Policy.MaxAttemptsPerStep)
184 }
185 var jobLive, accountLive int
186 if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM attempts WHERE job_id=? AND containment='pending'`, int64(j.ID)).Scan(&jobLive); err != nil {
187 return fail(CodeInvalid, "concurrency: %v", err)
188 }
189 if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM attempts a JOIN jobs j ON j.id=a.job_id WHERE j.account=? AND a.containment='pending'`, string(j.Account)).Scan(&accountLive); err != nil {
190 return fail(CodeInvalid, "concurrency: %v", err)
191 }
192 account, err := accountPolicy(ctx, tx, j.Account)
193 if err != nil {
194 return err
195 }
196 if jobLive >= j.Policy.MaxConcurrentAttempts || accountLive >= account.MaxConcurrentAttempts {
197 return fail(CodeQuota, "concurrent attempts: job %d, account %d, cap %d", jobLive, accountLive, j.Policy.MaxConcurrentAttempts)
198 }
199 fence := st.Fence + 1
200 deadline := now.Add(j.Policy.lease())
201 res, err := tx.ExecContext(ctx, `INSERT INTO attempts(job_id, step_id, number, runner, workspace, fence, lease_deadline, state, containment,
202 stop_requested, stop_acked, provider, model, effort, outcome, created_at, updated_at)
203 VALUES (?,?,?,?,?,?,?,'active','pending','','','','','','',?,?)`,
204 int64(j.ID), int64(st.ID), st.Attempts+1, runner, workspace, fence, ts(deadline), ts(now), ts(now))
205 if err != nil {
206 if strings.Contains(err.Error(), "UNIQUE") {
207 if strings.Contains(err.Error(), "workspace") {
208 return fail(CodeWorkspace, "workspace %q already used in job %d", workspace, j.ID)
209 }
210 return fail(CodeContainment, "step %q already has a live attempt", st.Key)
211 }
212 return fail(CodeInvalid, "insert attempt: %v", err)
213 }
214 id, _ := res.LastInsertId()
215 if err := reserveTime(ctx, tx, j, AttemptID(id), now); err != nil {
216 return err
217 }
218 if _, err := tx.ExecContext(ctx, `UPDATE steps SET state='running', fence=?, holder=?, attempts=attempts+1 WHERE id=? AND fence=?`, fence, id, int64(st.ID), st.Fence); err != nil {
219 return fail(CodeInvalid, "update step: %v", err)
220 }
221 {
222 var err error
223 j, err = bumpJob(ctx, tx, j, JobRunning, WaitNone, j.Outcome, now)
224 if err != nil {
225 return err
226 }
227 }
228 h = Handle{Revision: j.Revision, Attempt: AttemptID(id), Fence: fence, Runner: runner}
229 return appendEvent(ctx, tx, scope, "attempt.claimed", runner, map[string]any{"step": st.Key, "attempt": id, "fence": fence, "workspace": workspace}, now)
230 })
231 return h, err
232}
233
234// Renew extends the lease. The grant is introspected online first; an
235// observed revocation cancels the job through the ordinary cancel path and
236// an unavailable authority extends nothing. The transaction then requires
237// the handle to be current, the lease unexpired (the previous holder gets
238// no grace), the attempt within its time cap and the stored grant snapshot
239// to match the admission.
240func (s *Store) Renew(ctx context.Context, scope Scope, h Handle) (time.Time, error) {
241 job, err := s.GetJob(ctx, scope)
242 if err != nil {
243 return time.Time{}, err
244 }
245 adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: job.Grant.Ref, Account: job.Account, Project: job.Project, Target: job.Target, Operation: OpAttemptContinue})
246 if err != nil {
247 if errors.Is(err, ErrGrantRevoked) {
248 return time.Time{}, s.observedRevocation(ctx, scope, err)
249 }
250 return time.Time{}, err
251 }
252 if err := s.fenceObserved(ctx, job.Grant, adm); err != nil {
253 return time.Time{}, err
254 }
255 var deadline time.Time
256 err = s.tx(ctx, func(tx *sql.Tx) error {
257 if err := admissionOpen(ctx, tx); err != nil {
258 return err
259 }
260 now := s.clock.Now()
261 hd, err := current(ctx, tx, scope, h, now)
262 if err != nil {
263 return err
264 }
265 if err := checkAdmission(hd.job, adm, now); err != nil {
266 return err
267 }
268 if now.Sub(hd.attempt.CreatedAt) > time.Duration(hd.job.Policy.AttemptSeconds)*time.Second {
269 return fail(CodeQuota, "attempt %d past its %ds budget", hd.attempt.ID, hd.job.Policy.AttemptSeconds)
270 }
271 deadline = now.Add(hd.job.Policy.lease())
272 _, err = tx.ExecContext(ctx, `UPDATE attempts SET lease_deadline=?, updated_at=? WHERE id=? AND fence=?`, ts(deadline), ts(now), int64(hd.attempt.ID), h.Fence)
273 if err != nil {
274 return fail(CodeInvalid, "renew: %v", err)
275 }
276 return nil
277 })
278 return deadline, err
279}
280
281// checkAdmission compares a fresh admission with the job's stored grant
282// snapshot and the admission window. Version or epoch drift is ErrGrantStale:
283// only Resume moves the snapshot, after its own online check.
284func checkAdmission(j jobRow, adm Admission, now time.Time) error {
285 if j.grantStale {
286 return fail(CodeGrantStale, "job grant needs reconciliation")
287 }
288 if adm.Grant != j.Grant.Ref {
289 return fail(CodeGrantStale, "admission for grant %q, job holds %q", adm.Grant, j.Grant.Ref)
290 }
291 if adm.Version != j.Grant.Version || adm.Epoch != j.Grant.Epoch {
292 return fail(CodeGrantStale, "grant %q version %d/%d, stored %d/%d", adm.Grant, adm.Version, adm.Epoch, j.Grant.Version, j.Grant.Epoch)
293 }
294 if adm.ExpiresAt.Sub(adm.IssuedAt) > j.Policy.admission() || !now.Before(adm.ExpiresAt) || now.Before(adm.IssuedAt) {
295 return fail(CodeAdmissionExpired, "admission issued %s expires %s, now %s", adm.IssuedAt.Format(time.RFC3339Nano), adm.ExpiresAt.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano))
296 }
297 return nil
298}
299
300// Complete is the runner's terminal report. Success marks the step
301// succeeded; failure returns the step to pending while attempts remain and
302// otherwise fails the job. The attempt stays containment-pending until the
303// supervisor confirms, so a replacement cannot run beside a worker whose
304// resources are not yet contained.
305func (s *Store) Complete(ctx context.Context, scope Scope, h Handle, r AttemptResult) error {
306 if !r.Outcome.Valid() {
307 return fail(CodeUnknownKind, "outcome %q", r.Outcome)
308 }
309 return s.tx(ctx, func(tx *sql.Tx) error {
310 now := s.clock.Now()
311 hd, err := current(ctx, tx, scope, h, now)
312 if err != nil {
313 return err
314 }
315 if r.Outcome == OutcomeSuccess && hd.job.Target.Kind == TargetConversation {
316 var n int
317 if err := tx.QueryRowContext(ctx, "SELECT count(*) FROM events WHERE job_id=? AND type='coordinator.delivered'", scope.Job).Scan(&n); err != nil {
318 return err
319 }
320 if n != 1 {
321 return ErrEvidence
322 }
323 }
324 if r.Outcome == OutcomeSuccess && hd.step.Capability == CapScope && hd.job.Evidence.Predicate == PredicateSoftwareFeature {
325 if err := completedFeatureScope(ctx, tx, hd); err != nil {
326 return err
327 }
328 }
329 if r.Outcome == OutcomeSuccess && hd.step.Capability == CapReproduce && hd.job.Evidence.RequireBugFreeze {
330 if err := completedBugReproduction(ctx, tx, hd); err != nil {
331 return err
332 }
333 }
334 var open int
335 if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM actions WHERE attempt_id=? AND state IN ('intent','dispatching','uncertain')`, int64(hd.attempt.ID)).Scan(&open); err != nil {
336 return fail(CodeInvalid, "open actions: %v", err)
337 }
338 if open > 0 && r.Outcome == OutcomeSuccess {
339 return fail(CodeState, "attempt %d has %d unresolved actions", hd.attempt.ID, open)
340 }
341 aState, sState := AttemptSucceeded, StepSucceeded
342 if r.Outcome == OutcomeFailure {
343 aState, sState = AttemptFailed, StepPending
344 if r.Detail == "account_mismatch" || hd.job.Evidence.RequireBugFreeze || hd.step.Attempts >= hd.job.Policy.MaxAttemptsPerStep {
345 sState = StepFailed
346 }
347 // Intents never dispatched hold budget for nothing; in-flight
348 // actions keep theirs until a receipt or reconciliation.
349 if err := revokeIntents(ctx, tx, hd.attempt.ID, now); err != nil {
350 return err
351 }
352 }
353 if _, err := tx.ExecContext(ctx, `UPDATE attempts SET state=?, outcome=?, updated_at=? WHERE id=?`, string(aState), r.Detail, ts(now), int64(hd.attempt.ID)); err != nil {
354 return fail(CodeInvalid, "complete attempt: %v", err)
355 }
356 if _, err := tx.ExecContext(ctx, `UPDATE steps SET state=?, holder=0 WHERE id=? AND fence=?`, string(sState), int64(hd.step.ID), h.Fence); err != nil {
357 return fail(CodeInvalid, "complete step: %v", err)
358 }
359 if err := appendEvent(ctx, tx, scope, "attempt."+string(aState), h.Runner, map[string]any{"step": hd.step.Key, "attempt": hd.attempt.ID, "detail": r.Detail}, now); err != nil {
360 return err
361 }
362 if sState == StepFailed {
363 _, err := terminate(ctx, tx, hd.job, JobFailed, h.Runner, "step "+hd.step.Key+" exhausted its attempts", now)
364 return err
365 }
366 return nil
367 })
368}
369
370// Release gives the step back without a result: the provider refused,
371// the runner cannot continue. The attempt ends released (containment
372// still pending), the step returns to pending once contained, and the
373// job waits with the typed reason. The attempt number is consumed.
374func (s *Store) Release(ctx context.Context, scope Scope, h Handle, reason WaitReason, detail string) error {
375 if !reason.Valid() || reason == WaitNone {
376 return fail(CodeUnknownKind, "wait reason %q", reason)
377 }
378 return s.tx(ctx, func(tx *sql.Tx) error {
379 now := s.clock.Now()
380 hd, err := current(ctx, tx, scope, h, now)
381 if err != nil {
382 return err
383 }
384 var open int
385 if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM actions WHERE attempt_id=? AND state IN ('dispatching','uncertain')`, int64(hd.attempt.ID)).Scan(&open); err != nil {
386 return fail(CodeInvalid, "open actions: %v", err)
387 }
388 if open > 0 {
389 return fail(CodeState, "attempt %d has %d actions in flight", hd.attempt.ID, open)
390 }
391 var outcomes int
392 if hd.job.Evidence.RequireBugFreeze {
393 if err := tx.QueryRowContext(ctx, `SELECT (SELECT COUNT(*) FROM actions WHERE attempt_id=? AND state IN ('succeeded','failed')) + (SELECT COUNT(*) FROM artifacts WHERE attempt_id=?)`, int64(hd.attempt.ID), int64(hd.attempt.ID)).Scan(&outcomes); err != nil {
394 return fail(CodeInvalid, "attempt outcomes: %v", err)
395 }
396 }
397 if hd.step.Attempts >= hd.job.Policy.MaxAttemptsPerStep || hd.job.Evidence.RequireBugFreeze && (reason != WaitRunnerUnavailable || outcomes > 0) {
398 if err := revokeIntents(ctx, tx, hd.attempt.ID, now); err != nil {
399 return err
400 }
401 if _, err := tx.ExecContext(ctx, `UPDATE attempts SET state='failed',outcome=?,updated_at=? WHERE id=?`, detail, ts(now), int64(hd.attempt.ID)); err != nil {
402 return err
403 }
404 if _, err := tx.ExecContext(ctx, `UPDATE steps SET state='failed',holder=0 WHERE id=? AND fence=?`, int64(hd.step.ID), h.Fence); err != nil {
405 return err
406 }
407 if err := appendEvent(ctx, tx, scope, "attempt.failed", h.Runner, map[string]any{"step": hd.step.Key, "attempt": hd.attempt.ID, "detail": detail}, now); err != nil {
408 return err
409 }
410 _, err := terminate(ctx, tx, hd.job, JobFailed, h.Runner, detail, now)
411 return err
412 }
413 if err := revokeIntents(ctx, tx, hd.attempt.ID, now); err != nil {
414 return err
415 }
416 if _, err := tx.ExecContext(ctx, `UPDATE attempts SET state='released', outcome=?, updated_at=? WHERE id=?`, detail, ts(now), int64(hd.attempt.ID)); err != nil {
417 return fail(CodeInvalid, "release attempt: %v", err)
418 }
419 if _, err := bumpJob(ctx, tx, hd.job, JobWaiting, reason, hd.job.Outcome, now); err != nil {
420 return err
421 }
422 return appendEvent(ctx, tx, scope, "attempt.released", h.Runner, map[string]any{"step": hd.step.Key, "attempt": hd.attempt.ID, "wait": reason, "detail": detail}, now)
423 })
424}
425
426// revokeIntents revokes the attempt's actions still at intent and
427// releases their reservations: nothing was dispatched under them.
428func revokeIntents(ctx context.Context, tx *sql.Tx, attempt AttemptID, now time.Time) error {
429 if _, err := tx.ExecContext(ctx, `UPDATE reservations SET state='released', settled_at=? WHERE state='open' AND id IN (SELECT reservation_id FROM actions WHERE attempt_id=? AND state='intent')`, ts(now), int64(attempt)); err != nil {
430 return fail(CodeInvalid, "release reservations: %v", err)
431 }
432 if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='revoked', updated_at=? WHERE attempt_id=? AND state='intent'`, ts(now), int64(attempt)); err != nil {
433 return fail(CodeInvalid, "revoke intents: %v", err)
434 }
435 return nil
436}
437
438// Contain is the supervisor's confirmation that the attempt's whole
439// containment unit is gone. It acknowledges a pending stop, closes an
440// expired or finished attempt and, for an expired or stopped attempt on a
441// still-pending step, clears the holder so a fresh claim may follow.
442func (s *Store) Contain(ctx context.Context, scope Scope, id AttemptID, supervisor string) error {
443 if s.bound(ctx) == nil {
444 s.recoveryMu.Lock()
445 defer s.recoveryMu.Unlock()
446 }
447 return s.tx(ctx, func(tx *sql.Tx) error {
448 now := s.clock.Now()
449 j, err := loadJob(ctx, tx, scope)
450 if err != nil {
451 return err
452 }
453 a, err := loadAttempt(ctx, tx, j.ID, id)
454 if err != nil {
455 return err
456 }
457 if a.Containment == ContainmentContained {
458 return nil
459 }
460 state := a.State
461 switch a.State {
462 case AttemptActive:
463 if now.Before(a.LeaseDeadline) {
464 return fail(CodeState, "attempt %d still active under its lease", a.ID)
465 }
466 state = AttemptExpired
467 case AttemptStopping:
468 state = AttemptStopped
469 }
470 if _, err := tx.ExecContext(ctx, `UPDATE attempts SET state=?, containment='contained', stop_acked=?, updated_at=? WHERE id=?`, string(state), ts(now), ts(now), int64(a.ID)); err != nil {
471 return fail(CodeInvalid, "contain: %v", err)
472 }
473 st, err := loadStep(ctx, tx, j.ID, a.Step)
474 if err != nil {
475 return err
476 }
477 if st.Holder == a.ID && st.State == StepRunning {
478 if _, err := tx.ExecContext(ctx, `UPDATE steps SET holder=0, state='pending' WHERE id=?`, int64(st.ID)); err != nil {
479 return fail(CodeInvalid, "release step: %v", err)
480 }
481 }
482 if err := settleTime(ctx, tx, a, now); err != nil {
483 return err
484 }
485 return appendEvent(ctx, tx, scope, "attempt.contained", supervisor, map[string]any{"attempt": a.ID, "state": state}, now)
486 })
487}
488
489// Attempts lists the job's attempts.
490func (s *Store) Attempts(ctx context.Context, scope Scope) ([]Attempt, error) {
491 var out []Attempt
492 err := s.read(ctx, func(tx *sql.Tx) error {
493 if _, err := loadJob(ctx, tx, scope); err != nil {
494 return err
495 }
496 rows, err := tx.QueryContext(ctx, `SELECT `+attemptColumns+` FROM attempts WHERE job_id=? ORDER BY id`, int64(scope.Job))
497 if err != nil {
498 return fail(CodeInvalid, "attempts: %v", err)
499 }
500 defer rows.Close()
501 for rows.Next() {
502 a, err := scanAttempt(rows)
503 if err != nil {
504 return err
505 }
506 out = append(out, a)
507 }
508 return rows.Err()
509 })
510 return out, err
511}
512