//go:build integration package integration_test import ( "context" "encoding/json" "fmt" "log/slog" "net/http" "net/http/httptest" "sync" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgxpool" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/practice" "lincodex/backend/internal/worker/practicequeue" "lincodex/backend/internal/worker/retry" ) const ( practiceQueueTimeout = 8 * time.Minute // practiceQueueLease is the lease of the queue tests, on their clock. practiceQueueLease = 5 * time.Second // practiceRunsPerMinute is the debug run limit of the tests. practiceRunsPerMinute = 2 // fakeRunnerBusyWait is the Retry-After of the fake runner when busy. fakeRunnerBusyWait = 30 * time.Second ) func TestAssessmentPracticeQueue(t *testing.T) { env := bootstrap(t, postgresService, redisService) ctx, cancel := context.WithTimeout(t.Context(), practiceQueueTimeout) defer cancel() harness := newPracticeHarness(ctx, t, env, func(parts assessmentHarnessParts) (*practice.Service, error) { service, err := practice.NewService(parts.transactor, parts.keyring, parts.clock.Now, true) if err != nil { return nil, err } return service.WithRunRateLimit(env.Redis, outbound.RateLimitRule{Window: time.Minute, Limit: practiceRunsPerMinute}), nil }) clock := &practiceQueueClock{} runner := newFakePracticeRunner() queue := newPracticeQueueRig(t, harness.pool, runner, clock) candidates := make([]practiceCandidate, practice.MaxRunningJobs+practice.MaxQueuedJobs+1) for index := range candidates { candidates[index] = newPracticeCandidate(ctx, t, harness, fmt.Sprintf("practice-queue-%02d", index), 30+index) } t.Run("twelve runs at once fill one running and ten queued slots and the last is busy", func(t *testing.T) { responses := make([]*httptest.ResponseRecorder, len(candidates)) start := make(chan struct{}) var wait sync.WaitGroup for index, candidate := range candidates { wait.Add(1) go func() { defer wait.Done() <-start body := practiceRunBody(t, candidate.practiceID, "python", practiceSource, nil) responses[index] = practiceRunRequest(t, harness, candidate, body, "queue-run") }() } close(start) wait.Wait() busy := -1 for index, response := range responses { switch response.Code { case http.StatusAccepted: case http.StatusServiceUnavailable: if busy >= 0 { t.Fatalf("a second run was refused as busy: %s", response.Body.String()) } busy = index requireSessionProblem(t, response, http.StatusServiceUnavailable, "service_unavailable") if response.Header().Get("Retry-After") != "10" { t.Fatalf("busy Retry-After = %q, want 10", response.Header().Get("Retry-After")) } default: t.Fatalf("run %d = %d %s", index, response.Code, response.Body.String()) } } if busy < 0 { t.Fatal("no run was refused as busy") } assertPracticeRows(t, ctx, harness.pool, candidates[busy].practiceID, "public", 0) assertPracticeJobStates(t, ctx, harness.pool, map[string]int{"queued": 11}) // One worker holds the only running slot while the runner works; a // second worker finds nothing it may run. runner.hold(true) workerCtx, stopWorker := context.WithCancel(ctx) workerDone := make(chan struct{}) go func() { defer close(workerDone) queue.worker.Run(workerCtx) }() waitForPracticeJobStates(t, ctx, harness.pool, map[string]int{"running": 1, "queued": 10}) other := queue.newWorker(t) if _, claimed, err := other.RunOnce(ctx); err != nil || claimed { t.Fatalf("second worker claimed = %v, error %v; want nothing while one job runs", claimed, err) } runner.hold(false) waitForPracticeJobStates(t, ctx, harness.pool, map[string]int{"finished": 11}) stopWorker() <-workerDone runner.requireOneRunPerSubmission(t, 11) assertPracticeResultsStored(t, ctx, harness.pool, 11) }) t.Run("a full queue answers a final solution busy and consumes nothing", func(t *testing.T) { latecomer := candidates[len(candidates)-1] for _, candidate := range candidates[:len(candidates)-1] { body := practiceRunBody(t, candidate.practiceID, "python", practiceSource+"# second run\n", nil) if response := practiceRunRequest(t, harness, candidate, body, "queue-refill"); response.Code != http.StatusAccepted { t.Fatalf("refill run = %d %s", response.Code, response.Body.String()) } } versionBefore := practiceAttemptVersion(t, ctx, harness.pool, latecomer.attemptID) command := practice.FinalCommand{ ActorID: latecomer.userID, AttemptID: domain.AssessmentAttemptID(latecomer.attemptID), PracticeID: latecomer.practiceID, IdempotencyKey: "final-while-full", Language: languagePointer(domain.TaskLanguagePython), Source: practiceSource, } busy, err := harness.service.SubmitFinal(ctx, command) if err != nil || busy.RetryAfter <= 0 || busy.Practice.Status != domain.AssessmentPracticeFailed || busy.Practice.FailureReason != domain.AssessmentPracticeSandboxBusy { t.Fatalf("final solution with a full queue = %+v, error %v; want failed with sandbox_busy", busy, err) } assertPracticeRows(t, ctx, harness.pool, latecomer.practiceID, "final", 0) if version := practiceAttemptVersion(t, ctx, harness.pool, latecomer.attemptID); version != versionBefore { t.Fatalf("attempt version = %d after a busy refusal, want %d", version, versionBefore) } queue.drain(t, ctx) command.IdempotencyKey = "final-after-full" accepted, err := harness.service.SubmitFinal(ctx, command) if err != nil || accepted.Practice.Status != domain.AssessmentPracticePending { t.Fatalf("final solution after the queue drained = %+v, error %v", accepted, err) } queue.drain(t, ctx) assertPracticeStatus(t, ctx, harness.pool, latecomer.practiceID, "finished", "") }) t.Run("a busy runner and an infrastructure failure never grade or consume", func(t *testing.T) { candidate := candidates[0] submitPracticeFinal(t, ctx, harness, candidate, "final-runner-busy") runner.answerBusy(1) if outcome, claimed, err := queue.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeBusy { t.Fatalf("try on a busy runner = %q claimed %v, error %v; want busy", outcome, claimed, err) } job := readPracticeJob(t, ctx, harness.pool, candidate.practiceID) if job.state != "queued" || job.attempts != 0 || job.generation != 0 { t.Fatalf("job after a busy runner = %+v, want queued without a counted attempt", job) } assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "pending", "") // The job waits for the time the runner asked for. if _, claimed, err := queue.worker.RunOnce(ctx); err != nil || claimed { t.Fatalf("claim before the runner's wait = %v, error %v", claimed, err) } clock.advance(fakeRunnerBusyWait + time.Second) runner.failInfrastructure(1) if outcome, _, err := queue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeRetry { t.Fatalf("try after an infrastructure failure = %q, error %v; want retry", outcome, err) } job = readPracticeJob(t, ctx, harness.pool, candidate.practiceID) if job.state != "queued" || job.attempts != 1 || job.generation != 1 || job.errorClass != "runner_infrastructure_failure" { t.Fatalf("job after an infrastructure failure = %+v, want queued with a new generation", job) } assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "pending", "") assertNoPracticeResult(t, ctx, harness.pool, candidate.practiceID) clock.advance(time.Minute) if outcome, _, err := queue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeFinished { t.Fatalf("try after the backoff = %q, error %v; want finished", outcome, err) } assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "finished", "") }) t.Run("a worker restarted mid-job recovers it with a single run and result", func(t *testing.T) { candidate := candidates[1] submitPracticeFinal(t, ctx, harness, candidate, "final-restart") runner.hold(true) defer runner.hold(false) crashedPool := newPoolFor(ctx, t, harness.databaseURL) crashed := queue.workerOn(t, crashedPool) crashCtx, crash := context.WithCancel(ctx) crashedDone := make(chan struct{}) go func() { defer close(crashedDone) _, _, _ = crashed.worker.RunOnce(crashCtx) }() waitForPracticeJobStates(t, ctx, harness.pool, map[string]int{"running": 1}) submissionID := latestPracticeSubmission(t, ctx, harness.pool, candidate.practiceID, "final") runner.waitForRuns(t, ctx, submissionID, 1) // The process dies: its connections are gone, so it cannot give the // job back, and the lease keeps the job running. crashedPool.Close() crash() <-crashedDone stale := crashed.lastClaim() job := readPracticeJob(t, ctx, harness.pool, candidate.practiceID) if job.state != "running" || job.leaseOwner != stale.LeaseOwner { t.Fatalf("job after the crash = %+v, want running under the crashed lease", job) } restarted := queue.newWorker(t) if _, claimed, err := restarted.RunOnce(ctx); err != nil || claimed { t.Fatalf("claim during the crashed lease = %v, error %v; want none", claimed, err) } clock.advance(practiceQueueLease + time.Second) runner.hold(false) if outcome, claimed, err := restarted.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeFinished { t.Fatalf("restarted worker = %q claimed %v, error %v; want the job finished", outcome, claimed, err) } job = readPracticeJob(t, ctx, harness.pool, candidate.practiceID) if job.state != "finished" || job.attempts != 1 || job.generation != 0 { t.Fatalf("recovered job = %+v, want finished on the same run key with one counted takeover", job) } if runs := runner.runsOf(submissionID); runs != 1 { t.Fatalf("runner started %d runs for the recovered job, want 1", runs) } result := readPracticeResult(t, ctx, harness.pool, candidate.practiceID, "final") // The crashed worker coming back late cannot add a second result. lateStore := postgresadapter.NewPracticeJobStore(newPoolFor(ctx, t, harness.databaseURL)) held, err := lateStore.Complete(ctx, stale, domain.PracticeRunResult{Outcome: domain.PracticeOutcomeWrongAnswer, Groups: []domain.PracticeGroupOutcome{}}) if err != nil || held { t.Fatalf("late completion held = %v, error %v; want refused", held, err) } if again := readPracticeResult(t, ctx, harness.pool, candidate.practiceID, "final"); again != result { t.Fatalf("result changed after a late completion: %s, was %s", again, result) } assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "finished", "") }) t.Run("debug runs have a technical rate limit and consume nothing when refused", func(t *testing.T) { candidate := newPracticeCandidate(ctx, t, harness, "practice-limits", 60) run := func(key string) *httptest.ResponseRecorder { body := practiceRunBody(t, candidate.practiceID, "go", "package main\nfunc main() {}\n// "+key+"\n", nil) return practiceRunRequest(t, harness, candidate, body, key) } if response := run("limit-first"); response.Code != http.StatusAccepted { t.Fatalf("first run = %d %s", response.Code, response.Body.String()) } unfinished := run("limit-while-unfinished") requireSessionProblem(t, unfinished, http.StatusTooManyRequests, "rate_limited") if unfinished.Header().Get("Retry-After") == "" { t.Fatal("refused run has no Retry-After") } queue.drain(t, ctx) if response := run("limit-second"); response.Code != http.StatusAccepted { t.Fatalf("second run = %d %s", response.Code, response.Body.String()) } queue.drain(t, ctx) limited := run("limit-third") requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited") if limited.Header().Get("Retry-After") == "" { t.Fatal("rate-limited run has no Retry-After") } assertPracticeRows(t, ctx, harness.pool, candidate.practiceID, "public", 2) assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "not_started", "") }) assertEverySubmissionHasOneJob(t, ctx, harness.pool) } // practiceQueueRig builds workers on the test clock and the fake runner. type practiceQueueRig struct { pool *pgxpool.Pool runner *fakePracticeRunner clock *practiceQueueClock logger *slog.Logger worker *practicequeue.Worker } func newPracticeQueueRig(t *testing.T, pool *pgxpool.Pool, runner *fakePracticeRunner, clock *practiceQueueClock) *practiceQueueRig { t.Helper() rig := &practiceQueueRig{pool: pool, runner: runner, clock: clock, logger: slog.New(slog.DiscardHandler)} rig.worker = rig.newWorker(t) return rig } func (rig *practiceQueueRig) newWorker(t *testing.T) *practicequeue.Worker { t.Helper() return rig.workerOn(t, rig.pool).worker } // recordedWorker is a worker whose store remembers its last claim, so a test // can act as that worker after it stopped. type recordedWorker struct { worker *practicequeue.Worker store *recordingPracticeStore } func (worker recordedWorker) lastClaim() outbound.ClaimedPracticeJob { worker.store.mu.Lock() defer worker.store.mu.Unlock() return worker.store.claimed } func (rig *practiceQueueRig) workerOn(t *testing.T, pool *pgxpool.Pool) recordedWorker { t.Helper() store := &recordingPracticeStore{PracticeJobStore: postgresadapter.NewPracticeJobStore(pool)} executor, err := practice.NewExecutor(rig.runner, store, rig.clock.now, practice.ExecutionSettings{ PollInterval: 20 * time.Millisecond, Lease: practiceQueueLease, RunTimeout: time.Hour, MaxAttempts: 3, BackoffInitial: 10 * time.Second, BackoffMax: 40 * time.Second, StoreTimeout: 5 * time.Second, }, rig.logger) if err != nil { t.Fatalf("NewExecutor() error = %v", err) } worker, err := practicequeue.New(store, executor, rig.logger, practicequeue.Settings{ PollInterval: 20 * time.Millisecond, Lease: practiceQueueLease, StoreTimeout: 5 * time.Second, Backoff: retry.Backoff{Initial: 20 * time.Millisecond, Max: 100 * time.Millisecond}, }, rig.clock.now) if err != nil { t.Fatalf("practicequeue.New() error = %v", err) } return recordedWorker{worker: worker, store: store} } // drain runs jobs until none is left unfinished, moving the clock past any // wait. func (rig *practiceQueueRig) drain(t *testing.T, ctx context.Context) { t.Helper() for range 100 { if _, claimed, err := rig.worker.RunOnce(ctx); err != nil { t.Fatalf("drain the practice queue: %v", err) } else if claimed { continue } var active int if err := rig.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_jobs WHERE state IN ('queued', 'running')`).Scan(&active); err != nil { t.Fatalf("count unfinished practice jobs: %v", err) } if active == 0 { return } rig.clock.advance(time.Minute) } t.Fatal("the practice queue did not drain") } type recordingPracticeStore struct { outbound.PracticeJobStore mu sync.Mutex claimed outbound.ClaimedPracticeJob } func (store *recordingPracticeStore) Claim(ctx context.Context, claim outbound.PracticeJobClaim) (outbound.ClaimedPracticeJob, bool, error) { job, claimed, err := store.PracticeJobStore.Claim(ctx, claim) if claimed { store.mu.Lock() store.claimed = job store.mu.Unlock() } return job, claimed, err } // practiceQueueClock is the application clock of the queue tests: the real // time moved forward by the test, so jobs stored with the database time are // due at once. type practiceQueueClock struct { mu sync.Mutex offset time.Duration } func (clock *practiceQueueClock) now() time.Time { clock.mu.Lock() defer clock.mu.Unlock() return time.Now().UTC().Add(clock.offset) } func (clock *practiceQueueClock) advance(by time.Duration) { clock.mu.Lock() defer clock.mu.Unlock() clock.offset += by } // fakePracticeRunner stands in for the code runner. It is idempotent by run // key like the real one, so a second submit of a key returns the stored run, // and it counts the runs it started per practice item. type fakePracticeRunner struct { mu sync.Mutex runs map[outbound.CodeRunKey]*fakePracticeRun // started counts the runs started per submission. started map[uuid.UUID]int holding bool busy int failures int } type fakePracticeRun struct { request outbound.CodeRunRequest finished bool } func newFakePracticeRunner() *fakePracticeRunner { return &fakePracticeRunner{runs: map[outbound.CodeRunKey]*fakePracticeRun{}, started: map[uuid.UUID]int{}} } func (runner *fakePracticeRunner) Submit(_ context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) { runner.mu.Lock() defer runner.mu.Unlock() if runner.busy > 0 { runner.busy-- return outbound.CodeRunStatus{State: outbound.CodeRunBusy, RetryAfter: fakeRunnerBusyWait}, nil } if runner.failures > 0 { runner.failures-- return outbound.CodeRunStatus{}, fmt.Errorf("fake runner: %w", outbound.ErrCodeRunnerInfrastructureFailure) } run, exists := runner.runs[request.Key] if !exists { run = &fakePracticeRun{request: request} runner.runs[request.Key] = run runner.started[request.Key.SubmissionID]++ } return runner.statusLocked(run), nil } func (runner *fakePracticeRunner) Poll(_ context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) { runner.mu.Lock() defer runner.mu.Unlock() run, exists := runner.runs[request.Key] if !exists { return outbound.CodeRunStatus{}, outbound.ErrCodeRunNotFound } return runner.statusLocked(run), nil } func (runner *fakePracticeRunner) statusLocked(run *fakePracticeRun) outbound.CodeRunStatus { if runner.holding && !run.finished { return outbound.CodeRunStatus{State: outbound.CodeRunRunning, RunID: "fake"} } run.finished = true result := outbound.CodeRunResult{Outcome: outbound.CodeOutcomeAccepted, Duration: 10 * time.Millisecond} for _, group := range run.request.Groups { groupResult := outbound.CodeGroupResult{ ID: group.ID, Visibility: group.Visibility, Outcome: outbound.CodeOutcomeAccepted, PassedTests: len(group.Tests), TotalTests: len(group.Tests), } for _, test := range group.Tests { groupResult.Tests = append(groupResult.Tests, outbound.CodeTestResult{ID: test.ID, Outcome: outbound.CodeOutcomeAccepted, TimeMs: 1, MemoryKB: 512}) } result.Groups = append(result.Groups, groupResult) } return outbound.CodeRunStatus{State: outbound.CodeRunFinished, RunID: "fake", Result: &result} } // hold keeps new and unfinished runs running until it is turned off. func (runner *fakePracticeRunner) hold(holding bool) { runner.mu.Lock() defer runner.mu.Unlock() runner.holding = holding } func (runner *fakePracticeRunner) answerBusy(times int) { runner.mu.Lock() defer runner.mu.Unlock() runner.busy = times } func (runner *fakePracticeRunner) failInfrastructure(times int) { runner.mu.Lock() defer runner.mu.Unlock() runner.failures = times } func (runner *fakePracticeRunner) runsOf(submissionID uuid.UUID) int { runner.mu.Lock() defer runner.mu.Unlock() return runner.started[submissionID] } func (runner *fakePracticeRunner) waitForRuns(t *testing.T, ctx context.Context, submissionID uuid.UUID, want int) { t.Helper() for ctx.Err() == nil { if runner.runsOf(submissionID) >= want { return } time.Sleep(10 * time.Millisecond) } t.Fatalf("runner did not start %d runs", want) } // requireOneRunPerSubmission checks that every submission ran exactly once. func (runner *fakePracticeRunner) requireOneRunPerSubmission(t *testing.T, want int) { t.Helper() runner.mu.Lock() defer runner.mu.Unlock() submissions := map[uuid.UUID]int{} for key := range runner.runs { submissions[key.SubmissionID]++ } if len(submissions) != want { t.Fatalf("runner ran %d submissions, want %d", len(submissions), want) } for submission, runs := range submissions { if runs != 1 { t.Fatalf("submission %s ran %d times", submission, runs) } } } func submitPracticeFinal(t *testing.T, ctx context.Context, harness *practiceHarness, candidate practiceCandidate, key string) { t.Helper() result, err := harness.service.SubmitFinal(ctx, practice.FinalCommand{ ActorID: candidate.userID, AttemptID: domain.AssessmentAttemptID(candidate.attemptID), PracticeID: candidate.practiceID, IdempotencyKey: key, Language: languagePointer(domain.TaskLanguagePython), Source: practiceSource, }) if err != nil || result.Practice.Status != domain.AssessmentPracticePending { t.Fatalf("final submission = %+v, error %v", result, err) } } func latestPracticeSubmission(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, mode string) uuid.UUID { t.Helper() var id uuid.UUID if err := pool.QueryRow(ctx, `SELECT id FROM assessment_practice_submissions WHERE practice_id = $1 AND mode = $2 ORDER BY created_at DESC LIMIT 1`, practiceID, mode).Scan(&id); err != nil { t.Fatalf("read latest practice submission: %v", err) } return id } type practiceJobRow struct { state string attempts int generation int errorClass string leaseOwner uuid.UUID } // readPracticeJob reads the job of the latest final submission of a practice. func readPracticeJob(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID) practiceJobRow { t.Helper() var job practiceJobRow var owner *uuid.UUID var class *string if err := pool.QueryRow(ctx, `SELECT job.state, job.attempts, job.generation, job.last_error_class, job.lease_owner FROM assessment_practice_jobs AS job JOIN assessment_practice_submissions AS submission ON submission.id = job.submission_id WHERE submission.practice_id = $1 AND submission.mode = 'final' ORDER BY submission.created_at DESC LIMIT 1`, practiceID).Scan(&job.state, &job.attempts, &job.generation, &class, &owner); err != nil { t.Fatalf("read practice job: %v", err) } if owner != nil { job.leaseOwner = *owner } if class != nil { job.errorClass = *class } return job } func readPracticeResult(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, mode string) string { t.Helper() var result []byte if err := pool.QueryRow(ctx, `SELECT result FROM assessment_practice_submissions WHERE practice_id = $1 AND mode = $2 ORDER BY created_at DESC LIMIT 1`, practiceID, mode).Scan(&result); err != nil || len(result) == 0 { t.Fatalf("read practice result: %v (%d bytes)", err, len(result)) } var decoded domain.PracticeRunResult if err := json.Unmarshal(result, &decoded); err != nil || decoded.Outcome != domain.PracticeOutcomeAccepted { t.Fatalf("stored result %s, decode error %v", result, err) } return string(result) } // assertNoPracticeResult checks that no final submission of the practice has // a result. func assertNoPracticeResult(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID) { t.Helper() var stored int if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_submissions WHERE practice_id = $1 AND mode = 'final' AND result IS NOT NULL`, practiceID).Scan(&stored); err != nil { t.Fatalf("count practice results: %v", err) } if stored != 0 { t.Fatalf("%d practice results stored, want none", stored) } } func assertPracticeResultsStored(t *testing.T, ctx context.Context, pool *pgxpool.Pool, want int) { t.Helper() var stored int if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_submissions WHERE result IS NOT NULL`).Scan(&stored); err != nil { t.Fatalf("count practice results: %v", err) } if stored != want { t.Fatalf("%d practice results stored, want %d", stored, want) } } func assertPracticeStatus(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, status, reason string) { t.Helper() var gotStatus string var gotReason *string if err := pool.QueryRow(ctx, `SELECT status, failure_reason FROM assessment_practices WHERE id = $1`, practiceID).Scan(&gotStatus, &gotReason); err != nil { t.Fatalf("read practice status: %v", err) } if gotStatus != status || (gotReason != nil) != (reason != "") || (gotReason != nil && *gotReason != reason) { t.Fatalf("practice status = %s %v, want %s %q", gotStatus, gotReason, status, reason) } } func practiceAttemptVersion(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) int64 { t.Helper() var version int64 if err := pool.QueryRow(ctx, `SELECT version FROM assessment_attempts WHERE id = $1`, attemptID).Scan(&version); err != nil { t.Fatalf("read attempt version: %v", err) } return version } func practiceJobStates(t *testing.T, ctx context.Context, pool *pgxpool.Pool) map[string]int { t.Helper() rows, err := pool.Query(ctx, `SELECT state, count(*) FROM assessment_practice_jobs GROUP BY state`) if err != nil { t.Fatalf("count practice jobs: %v", err) } defer rows.Close() states := map[string]int{} for rows.Next() { var state string var count int if err := rows.Scan(&state, &count); err != nil { t.Fatalf("scan practice job count: %v", err) } states[state] = count } if err := rows.Err(); err != nil { t.Fatalf("read practice job counts: %v", err) } return states } func assertPracticeJobStates(t *testing.T, ctx context.Context, pool *pgxpool.Pool, want map[string]int) { t.Helper() if got := practiceJobStates(t, ctx, pool); !sameJobStates(got, want) { t.Fatalf("practice jobs = %v, want %v", got, want) } } func waitForPracticeJobStates(t *testing.T, ctx context.Context, pool *pgxpool.Pool, want map[string]int) { t.Helper() deadline := time.Now().Add(30 * time.Second) for { got := practiceJobStates(t, ctx, pool) if sameJobStates(got, want) { return } if time.Now().After(deadline) || ctx.Err() != nil { t.Fatalf("practice jobs = %v, want %v", got, want) } time.Sleep(20 * time.Millisecond) } } // sameJobStates compares the counts of the states in want; finished jobs of // earlier cases are ignored unless want names them. func sameJobStates(got, want map[string]int) bool { for _, state := range []string{"queued", "running", "failed"} { if got[state] != want[state] { return false } } if finished, named := want["finished"]; named && got["finished"] != finished { return false } return true }