feat(practice): queue practice runs with one running and ten waiting
This commit is contained in:
1 parent
51770eea6c
commit
754c745fba
40 files changed
+3040
-70
No files matched your search
@@ -162,6 +162,8 @@ type Config struct {
|
||||
// CodeRunner configures the client of the own code runner. It is disabled
|
||||
// unless CODE_RUNNER_URL is set.
|
||||
CodeRunner CodeRunnerSettings
|
||||
// Practice configures the debug run limits and the practice queue worker.
|
||||
Practice PracticeSettings
|
||||
|
||||
// TrustedProxyCIDRs are the reverse proxies in front of the API. The
|
||||
// client address is taken from X-Forwarded-For only through them (see
|
||||
@@ -267,6 +269,11 @@ func (config *Config) loadIdentityAndProxySettings(lookup LookupEnv) error {
|
||||
return err
|
||||
}
|
||||
config.CodeRunner = codeRunner
|
||||
practice, err := LoadPracticeSettings(lookup, codeRunner.RequestTimeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
config.Practice = practice
|
||||
return config.loadTrustedProxies(lookup)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// Debug runs of one candidate are a technical abuse brake on the shared
|
||||
// sandbox, not a product quota: a few runs a minute and a working
|
||||
// session's worth an hour.
|
||||
defaultPracticeRunsPerMinute = 6
|
||||
defaultPracticeRunsPerHour = 60
|
||||
maxPracticeRunsPerMinute = 600
|
||||
maxPracticeRunsPerHour = 36000
|
||||
// defaultPracticePollInterval is the wait between two reads of a running
|
||||
// run and after a pass that found nothing to run. It is also the usual
|
||||
// delay before a queued run starts.
|
||||
defaultPracticePollInterval = time.Second
|
||||
minPracticePollInterval = 10 * time.Millisecond
|
||||
maxPracticePollInterval = 30 * time.Second
|
||||
// defaultPracticeJobLease is how long a claimed practice job belongs to
|
||||
// one worker without a renewal; every poll renews it. A worker that
|
||||
// crashed delays its job by at most this long.
|
||||
defaultPracticeJobLease = 30 * time.Second
|
||||
maxPracticeJobLease = 10 * time.Minute
|
||||
// defaultPracticeJobMaxAttempts bounds the failed tries and expired
|
||||
// leases of a job before it fails without a verdict.
|
||||
defaultPracticeJobMaxAttempts = 5
|
||||
maxPracticeJobMaxAttempts = 100
|
||||
)
|
||||
|
||||
// PracticeSettings configure code practice: the rate limit of debug runs and
|
||||
// the practice queue worker. The queue limits (one running, ten queued) are
|
||||
// product rules in the practice usecase, not settings.
|
||||
type PracticeSettings struct {
|
||||
// RunsPerMinute and RunsPerHour bound the debug runs of one candidate.
|
||||
RunsPerMinute int64
|
||||
RunsPerHour int64
|
||||
// PollInterval is the wait between two reads of a running run and after
|
||||
// an empty pass of the queue worker.
|
||||
PollInterval time.Duration
|
||||
// JobLease is how long a claimed job belongs to one worker without a
|
||||
// renewal.
|
||||
JobLease time.Duration
|
||||
// JobMaxAttempts bounds the failed tries of a job.
|
||||
JobMaxAttempts int
|
||||
}
|
||||
|
||||
// LoadPracticeSettings reads the practice settings. requestTimeout is the
|
||||
// code runner request timeout: a lease must outlast one runner call and one
|
||||
// poll, or another worker could take a job over while its call is still
|
||||
// running.
|
||||
func LoadPracticeSettings(lookup LookupEnv, requestTimeout time.Duration) (PracticeSettings, error) {
|
||||
settings := PracticeSettings{}
|
||||
perMinute, err := intOrDefault(lookup, "PRACTICE_RUNS_PER_MINUTE", defaultPracticeRunsPerMinute)
|
||||
if err != nil {
|
||||
return PracticeSettings{}, err
|
||||
}
|
||||
perHour, err := intOrDefault(lookup, "PRACTICE_RUNS_PER_HOUR", defaultPracticeRunsPerHour)
|
||||
if err != nil {
|
||||
return PracticeSettings{}, err
|
||||
}
|
||||
settings.RunsPerMinute, settings.RunsPerHour = int64(perMinute), int64(perHour)
|
||||
if settings.PollInterval, err = durationOrDefault(lookup, "PRACTICE_POLL_INTERVAL", defaultPracticePollInterval); err != nil {
|
||||
return PracticeSettings{}, err
|
||||
}
|
||||
if settings.JobLease, err = durationOrDefault(lookup, "PRACTICE_JOB_LEASE", defaultPracticeJobLease); err != nil {
|
||||
return PracticeSettings{}, err
|
||||
}
|
||||
if settings.JobMaxAttempts, err = intOrDefault(lookup, "PRACTICE_JOB_MAX_ATTEMPTS", defaultPracticeJobMaxAttempts); err != nil {
|
||||
return PracticeSettings{}, err
|
||||
}
|
||||
return settings, settings.Validate(requestTimeout)
|
||||
}
|
||||
|
||||
// Validate checks the ranges. They are checked even without a code runner, so
|
||||
// enabling the runner later cannot surface an old mistake.
|
||||
func (settings PracticeSettings) Validate(requestTimeout time.Duration) error {
|
||||
const location = "PracticeSettings.Validate"
|
||||
switch {
|
||||
case settings.RunsPerMinute < 1 || settings.RunsPerMinute > maxPracticeRunsPerMinute:
|
||||
return fmt.Errorf("%s - PRACTICE_RUNS_PER_MINUTE must be between 1 and %d", location, maxPracticeRunsPerMinute)
|
||||
case settings.RunsPerHour < settings.RunsPerMinute || settings.RunsPerHour > maxPracticeRunsPerHour:
|
||||
return fmt.Errorf("%s - PRACTICE_RUNS_PER_HOUR must be between PRACTICE_RUNS_PER_MINUTE and %d", location, maxPracticeRunsPerHour)
|
||||
case settings.PollInterval < minPracticePollInterval || settings.PollInterval > maxPracticePollInterval:
|
||||
return fmt.Errorf("%s - PRACTICE_POLL_INTERVAL must be between %s and %s", location, minPracticePollInterval, maxPracticePollInterval)
|
||||
case settings.JobLease <= requestTimeout+settings.PollInterval || settings.JobLease > maxPracticeJobLease:
|
||||
return fmt.Errorf("%s - PRACTICE_JOB_LEASE must exceed CODE_RUNNER_REQUEST_TIMEOUT plus PRACTICE_POLL_INTERVAL and be at most %s",
|
||||
location, maxPracticeJobLease)
|
||||
case settings.JobMaxAttempts < 1 || settings.JobMaxAttempts > maxPracticeJobMaxAttempts:
|
||||
return fmt.Errorf("%s - PRACTICE_JOB_MAX_ATTEMPTS must be between 1 and %d", location, maxPracticeJobMaxAttempts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLoadFromEnvPracticeDefaults(t *testing.T) {
|
||||
settings, err := LoadFromEnv(testEnvironment(nil))
|
||||
if err != nil {
|
||||
t.Fatalf("LoadFromEnv() error = %v", err)
|
||||
}
|
||||
want := PracticeSettings{RunsPerMinute: 6, RunsPerHour: 60, PollInterval: time.Second, JobLease: 30 * time.Second, JobMaxAttempts: 5}
|
||||
if settings.Practice != want {
|
||||
t.Fatalf("practice defaults = %+v, want %+v", settings.Practice, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFromEnvRejectsInvalidPracticeSettings(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
values map[string]string
|
||||
message string
|
||||
}{
|
||||
"zero runs per minute": {map[string]string{"PRACTICE_RUNS_PER_MINUTE": "0"}, "PRACTICE_RUNS_PER_MINUTE"},
|
||||
"hour below minute": {
|
||||
map[string]string{"PRACTICE_RUNS_PER_MINUTE": "10", "PRACTICE_RUNS_PER_HOUR": "5"}, "PRACTICE_RUNS_PER_HOUR",
|
||||
},
|
||||
"poll too short": {map[string]string{"PRACTICE_POLL_INTERVAL": "1ms"}, "PRACTICE_POLL_INTERVAL"},
|
||||
// The lease must outlast one runner request (10s by default) and a poll.
|
||||
"lease within a request": {map[string]string{"PRACTICE_JOB_LEASE": "10s"}, "PRACTICE_JOB_LEASE"},
|
||||
"no attempts": {map[string]string{"PRACTICE_JOB_MAX_ATTEMPTS": "0"}, "PRACTICE_JOB_MAX_ATTEMPTS"},
|
||||
"malformed duration": {map[string]string{"PRACTICE_JOB_LEASE": "soon"}, "PRACTICE_JOB_LEASE"},
|
||||
}
|
||||
for name, testCase := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
_, err := LoadFromEnv(testEnvironment(testCase.values))
|
||||
if err == nil || !strings.Contains(err.Error(), testCase.message) {
|
||||
t.Fatalf("LoadFromEnv() error = %v, want one naming %s", err, testCase.message)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
-- +goose Up
|
||||
-- The practice queue: the execution jobs of practice submissions become
|
||||
-- durable work items that one worker at a time runs on the code runner.
|
||||
--
|
||||
-- The queue holds at most one running and ten queued jobs. Admission and
|
||||
-- the claim both take the transaction-scoped advisory lock of the queue and
|
||||
-- count the unfinished jobs, so the limits hold across backend instances. A
|
||||
-- job beyond them is never inserted: the command answers busy and stores
|
||||
-- nothing that would consume an attempt.
|
||||
--
|
||||
-- A running job holds a lease. A worker that stops without finishing leaves
|
||||
-- the lease to expire, and the next claim takes the job over with the same
|
||||
-- generation, so the runner, which is idempotent by run ID, returns the run
|
||||
-- it already has instead of starting a second one. Lease and retry times come
|
||||
-- from the application clock.
|
||||
ALTER TABLE assessment_practice_jobs
|
||||
-- Generation of the run key: raised after the runner could not evaluate
|
||||
-- the source, so the next try is a new run.
|
||||
ADD COLUMN generation integer NOT NULL DEFAULT 0,
|
||||
-- Failed tries and expired leases counted so far. A busy runner counts
|
||||
-- nothing.
|
||||
ADD COLUMN attempts integer NOT NULL DEFAULT 0,
|
||||
-- When a worker may claim a queued job: at once, after the wait the runner
|
||||
-- asked for when it was busy, or after the backoff of a failed try.
|
||||
ADD COLUMN available_at timestamptz,
|
||||
ADD COLUMN lease_owner uuid,
|
||||
ADD COLUMN lease_expires_at timestamptz,
|
||||
-- When the running try was claimed; it bounds how long a run may stay
|
||||
-- unfinished on the runner.
|
||||
ADD COLUMN started_at timestamptz,
|
||||
-- Bounded cause of the last failed try; never runner or candidate text.
|
||||
ADD COLUMN last_error_class text;
|
||||
|
||||
UPDATE assessment_practice_jobs SET available_at = created_at;
|
||||
|
||||
ALTER TABLE assessment_practice_jobs
|
||||
ALTER COLUMN available_at SET NOT NULL,
|
||||
ADD CONSTRAINT assessment_practice_jobs_lease_when_running CHECK (
|
||||
(state = 'running') = (lease_owner IS NOT NULL)
|
||||
AND (lease_owner IS NULL) = (lease_expires_at IS NULL)
|
||||
AND (lease_owner IS NULL) = (started_at IS NULL)
|
||||
),
|
||||
ADD CONSTRAINT assessment_practice_jobs_counters CHECK (
|
||||
generation >= 0 AND attempts BETWEEN 0 AND 100
|
||||
),
|
||||
ADD CONSTRAINT assessment_practice_jobs_error_class CHECK (
|
||||
last_error_class IS NULL OR last_error_class IN (
|
||||
'runner_unavailable',
|
||||
'runner_infrastructure_failure',
|
||||
'invalid_request',
|
||||
'run_timeout',
|
||||
'lease_expired'
|
||||
)
|
||||
);
|
||||
|
||||
-- Serves the claim of the next queued job.
|
||||
CREATE INDEX assessment_practice_jobs_queued_idx
|
||||
ON assessment_practice_jobs (available_at, created_at)
|
||||
WHERE state = 'queued';
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX assessment_practice_jobs_queued_idx;
|
||||
ALTER TABLE assessment_practice_jobs
|
||||
DROP CONSTRAINT assessment_practice_jobs_error_class,
|
||||
DROP CONSTRAINT assessment_practice_jobs_counters,
|
||||
DROP CONSTRAINT assessment_practice_jobs_lease_when_running,
|
||||
DROP COLUMN last_error_class,
|
||||
DROP COLUMN started_at,
|
||||
DROP COLUMN lease_expires_at,
|
||||
DROP COLUMN lease_owner,
|
||||
DROP COLUMN available_at,
|
||||
DROP COLUMN attempts,
|
||||
DROP COLUMN generation;
|
||||
@@ -124,12 +124,13 @@ INSERT INTO assessment_practice_submissions (
|
||||
);
|
||||
|
||||
-- Queues the execution job of a submission in the transaction that stores
|
||||
-- the submission.
|
||||
-- the submission. The job is available at once.
|
||||
-- name: InsertAssessmentPracticeJob :exec
|
||||
INSERT INTO assessment_practice_jobs (
|
||||
submission_id,
|
||||
mode,
|
||||
state,
|
||||
available_at,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
@@ -137,6 +138,7 @@ INSERT INTO assessment_practice_jobs (
|
||||
sqlc.arg(mode),
|
||||
'queued',
|
||||
sqlc.arg(created_at),
|
||||
sqlc.arg(created_at),
|
||||
sqlc.arg(created_at)
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
-- The practice queue. Admission and the claim take the same
|
||||
-- transaction-scoped advisory lock, so the count of unfinished jobs and the
|
||||
-- change that depends on it are atomic across backend instances. A command
|
||||
-- takes the lock after its attempt and practice row locks; the claim takes
|
||||
-- it first and then skips job rows that another transaction locks, so a
|
||||
-- claim never waits for a row lock while it holds the queue lock.
|
||||
|
||||
-- name: LockAssessmentPracticeQueue :exec
|
||||
SELECT pg_advisory_xact_lock(hashtextextended('lincodex.assessment.practice_queue', 0));
|
||||
|
||||
-- Counts the queued and running jobs; the caller holds the queue lock.
|
||||
-- name: CountActiveAssessmentPracticeJobs :one
|
||||
SELECT count(*)::integer AS active
|
||||
FROM assessment_practice_jobs AS job
|
||||
WHERE job.state IN ('queued', 'running');
|
||||
|
||||
-- Counts the unfinished debug runs of a practice; the caller holds the
|
||||
-- practice row lock.
|
||||
-- name: CountActiveAssessmentPracticeRuns :one
|
||||
SELECT count(*)::integer AS active
|
||||
FROM assessment_practice_jobs AS job
|
||||
INNER JOIN assessment_practice_submissions AS submission ON job.submission_id = submission.id
|
||||
WHERE
|
||||
submission.practice_id = sqlc.arg(practice_id)
|
||||
AND job.mode = 'public'
|
||||
AND job.state IN ('queued', 'running');
|
||||
|
||||
-- Counts running jobs whose lease has not expired by now, the application
|
||||
-- clock; the caller holds the queue lock.
|
||||
-- name: CountLiveRunningAssessmentPracticeJobs :one
|
||||
SELECT count(*)::integer AS running
|
||||
FROM assessment_practice_jobs AS job
|
||||
WHERE
|
||||
job.state = 'running'
|
||||
AND job.lease_expires_at > sqlc.arg(now)::timestamptz;
|
||||
|
||||
-- Claims one job under the queue lock: first a running job whose lease
|
||||
-- expired (its worker stopped without finishing it), then the next queued
|
||||
-- job, final submissions before debug runs. A takeover keeps the generation,
|
||||
-- so the runner returns the run it already has, and counts one attempt.
|
||||
-- name: ClaimAssessmentPracticeJob :one
|
||||
WITH candidate AS (
|
||||
SELECT
|
||||
job.submission_id,
|
||||
job.state = 'running' AS reclaimed
|
||||
FROM assessment_practice_jobs AS job
|
||||
WHERE
|
||||
(job.state = 'queued' AND job.available_at <= sqlc.arg(now)::timestamptz)
|
||||
OR (job.state = 'running' AND job.lease_expires_at <= sqlc.arg(now)::timestamptz)
|
||||
ORDER BY
|
||||
job.state = 'running' DESC,
|
||||
job.mode = 'final' DESC,
|
||||
job.available_at ASC,
|
||||
job.created_at ASC,
|
||||
job.submission_id ASC
|
||||
LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
|
||||
UPDATE assessment_practice_jobs AS job
|
||||
SET
|
||||
state = 'running',
|
||||
lease_owner = sqlc.arg(lease_owner),
|
||||
lease_expires_at = sqlc.arg(lease_expires_at),
|
||||
started_at = sqlc.arg(now)::timestamptz,
|
||||
attempts = job.attempts + CASE WHEN candidate.reclaimed THEN 1 ELSE 0 END,
|
||||
last_error_class = CASE
|
||||
WHEN candidate.reclaimed THEN 'lease_expired' ELSE job.last_error_class
|
||||
END,
|
||||
updated_at = greatest(job.updated_at, clock_timestamp())
|
||||
FROM candidate
|
||||
WHERE job.submission_id = candidate.submission_id
|
||||
RETURNING
|
||||
job.submission_id,
|
||||
job.mode,
|
||||
job.generation,
|
||||
job.attempts,
|
||||
candidate.reclaimed;
|
||||
|
||||
-- Reads what a claimed job runs: the submission and the task of its
|
||||
-- practice.
|
||||
-- name: GetAssessmentPracticeJobWork :one
|
||||
SELECT
|
||||
submission.id,
|
||||
submission.practice_id,
|
||||
submission.user_id,
|
||||
submission.mode,
|
||||
submission.language,
|
||||
submission.source,
|
||||
submission.custom_tests,
|
||||
submission.created_at,
|
||||
practice.task
|
||||
FROM assessment_practice_submissions AS submission
|
||||
INNER JOIN assessment_practices AS practice ON submission.practice_id = practice.id
|
||||
WHERE submission.id = sqlc.arg(submission_id);
|
||||
|
||||
-- Renews the lease of a running try. The owner and the start time identify
|
||||
-- the try, so a worker whose job was taken over changes nothing.
|
||||
-- name: ExtendAssessmentPracticeJobLease :execrows
|
||||
UPDATE assessment_practice_jobs
|
||||
SET
|
||||
lease_expires_at = sqlc.arg(lease_expires_at),
|
||||
updated_at = greatest(updated_at, clock_timestamp())
|
||||
WHERE
|
||||
submission_id = sqlc.arg(submission_id)
|
||||
AND state = 'running'
|
||||
AND lease_owner = sqlc.arg(lease_owner)
|
||||
AND started_at = sqlc.arg(started_at);
|
||||
|
||||
-- Puts a running try back into the queue: after a busy runner, a failed
|
||||
-- try, or at shutdown. counted adds the try to the attempts.
|
||||
-- name: RequeueAssessmentPracticeJob :execrows
|
||||
UPDATE assessment_practice_jobs
|
||||
SET
|
||||
state = 'queued',
|
||||
available_at = sqlc.arg(available_at),
|
||||
generation = sqlc.arg(generation),
|
||||
attempts = attempts + sqlc.arg(counted)::integer,
|
||||
last_error_class = coalesce(sqlc.narg(error_class), last_error_class),
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
started_at = NULL,
|
||||
updated_at = greatest(updated_at, clock_timestamp())
|
||||
WHERE
|
||||
submission_id = sqlc.arg(submission_id)
|
||||
AND state = 'running'
|
||||
AND lease_owner = sqlc.arg(lease_owner)
|
||||
AND started_at = sqlc.arg(started_at);
|
||||
|
||||
-- Locks a running try for its completion and checks that it still belongs
|
||||
-- to the worker.
|
||||
-- name: LockClaimedAssessmentPracticeJob :one
|
||||
SELECT job.mode
|
||||
FROM assessment_practice_jobs AS job
|
||||
WHERE
|
||||
job.submission_id = sqlc.arg(submission_id)
|
||||
AND job.state = 'running'
|
||||
AND job.lease_owner = sqlc.arg(lease_owner)
|
||||
AND job.started_at = sqlc.arg(started_at)
|
||||
FOR UPDATE;
|
||||
|
||||
-- Stores the result of a submission once; a second result changes nothing.
|
||||
-- name: StoreAssessmentPracticeResult :execrows
|
||||
UPDATE assessment_practice_submissions
|
||||
SET
|
||||
result = sqlc.arg(result),
|
||||
result_at = greatest(created_at, clock_timestamp())
|
||||
WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND result IS NULL;
|
||||
|
||||
-- Ends a running try as finished or failed.
|
||||
-- name: FinishAssessmentPracticeJob :execrows
|
||||
UPDATE assessment_practice_jobs
|
||||
SET
|
||||
state = sqlc.arg(state),
|
||||
finished_at = greatest(created_at, clock_timestamp()),
|
||||
last_error_class = coalesce(sqlc.narg(error_class), last_error_class),
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
started_at = NULL,
|
||||
updated_at = greatest(updated_at, clock_timestamp())
|
||||
WHERE
|
||||
submission_id = sqlc.arg(submission_id)
|
||||
AND state = 'running'
|
||||
AND lease_owner = sqlc.arg(lease_owner)
|
||||
AND started_at = sqlc.arg(started_at);
|
||||
|
||||
-- Moves the practice of a final submission out of pending, but only while
|
||||
-- that submission is the latest final one of the practice.
|
||||
-- name: SettleAssessmentPracticeAfterJob :execrows
|
||||
UPDATE assessment_practices AS practice
|
||||
SET
|
||||
status = sqlc.arg(status),
|
||||
failure_reason = sqlc.narg(failure_reason),
|
||||
updated_at = greatest(practice.updated_at, clock_timestamp())
|
||||
WHERE
|
||||
practice.status = 'pending'
|
||||
AND practice.id = (
|
||||
SELECT submission.practice_id
|
||||
FROM assessment_practice_submissions AS submission
|
||||
WHERE submission.id = sqlc.arg(submission_id)
|
||||
)
|
||||
AND sqlc.arg(submission_id)::uuid = (
|
||||
SELECT latest.id
|
||||
FROM assessment_practice_submissions AS latest
|
||||
WHERE
|
||||
latest.practice_id = practice.id
|
||||
AND latest.mode = 'final'
|
||||
ORDER BY latest.created_at DESC, latest.id DESC
|
||||
LIMIT 1
|
||||
);
|
||||
@@ -42,6 +42,9 @@ func TestAssessmentPracticeSubmissionStorage(t *testing.T) {
|
||||
})
|
||||
owner := newPracticeCandidate(ctx, t, harness, "practice-owner", 10)
|
||||
other := newPracticeCandidate(ctx, t, harness, "practice-other", 20)
|
||||
// firstRun is the debug run that the first case stores; it stays queued,
|
||||
// as no worker runs here, until a later case gives it a result.
|
||||
var firstRun uuid.UUID
|
||||
|
||||
t.Run("debug run is stored with its job and shows no hidden content", func(t *testing.T) {
|
||||
body := practiceRunBody(t, owner.practiceID, "python", practiceSource, []domain.PracticeTest{{Input: "4 5\n", ExpectedOutput: "9\n"}})
|
||||
@@ -58,6 +61,7 @@ func TestAssessmentPracticeSubmissionStorage(t *testing.T) {
|
||||
}
|
||||
assertPracticeResponseIsPublic(t, created)
|
||||
assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1)
|
||||
firstRun = run.ID
|
||||
|
||||
replay := practiceRunRequest(t, harness, owner, body, "run-first")
|
||||
if replay.Code != http.StatusAccepted || decodePracticeRun(t, replay).ID != run.ID {
|
||||
@@ -90,15 +94,9 @@ func TestAssessmentPracticeSubmissionStorage(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("a stored result is shown without hidden groups", func(t *testing.T) {
|
||||
body := practiceRunBody(t, owner.practiceID, "go", "package main\nfunc main() {}\n", nil)
|
||||
created := practiceRunRequest(t, harness, owner, body, "run-with-result")
|
||||
if created.Code != http.StatusAccepted {
|
||||
t.Fatalf("create run = %d %s", created.Code, created.Body.String())
|
||||
}
|
||||
run := decodePracticeRun(t, created)
|
||||
// A result that holds a hidden group, which a debug run never gets,
|
||||
// proves that the presentation drops it.
|
||||
storePracticeResult(t, ctx, harness.pool, run.ID, domain.PracticeRunResult{
|
||||
storePracticeResult(t, ctx, harness.pool, firstRun, domain.PracticeRunResult{
|
||||
Outcome: domain.PracticeOutcomeWrongAnswer, DurationMs: 42,
|
||||
Groups: []domain.PracticeGroupOutcome{
|
||||
{ID: practice.PublicGroupID, Outcome: domain.PracticeOutcomeWrongAnswer, PassedTests: 1, TotalTests: 2, Tests: []domain.PracticeTestOutcome{
|
||||
@@ -108,7 +106,7 @@ func TestAssessmentPracticeSubmissionStorage(t *testing.T) {
|
||||
{ID: "hidden-1", Hidden: true, Outcome: domain.PracticeOutcomeAccepted, PassedTests: 1, TotalTests: 1},
|
||||
},
|
||||
})
|
||||
read := practiceRunRead(t, harness, owner, owner.attemptID, run.ID)
|
||||
read := practiceRunRead(t, harness, owner, owner.attemptID, firstRun)
|
||||
finished := decodePracticeRun(t, read)
|
||||
if read.Code != http.StatusOK || finished.State != "finished" || finished.Result == nil || len(finished.Result.Tests) != 2 {
|
||||
t.Fatalf("finished run = %d %s", read.Code, read.Body.String())
|
||||
@@ -196,6 +194,8 @@ type practiceHarness struct {
|
||||
*assessmentAttemptHTTPHarness
|
||||
service *practice.Service
|
||||
passwordHash domain.PasswordHash
|
||||
// databaseURL names the isolated database of the harness.
|
||||
databaseURL string
|
||||
}
|
||||
|
||||
// newPracticeHarness builds the router on an isolated, migrated database with
|
||||
@@ -225,7 +225,9 @@ func newPracticeHarness(
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
return &practiceHarness{assessmentAttemptHTTPHarness: attemptHarness, service: service, passwordHash: passwordHash}
|
||||
return &practiceHarness{
|
||||
assessmentAttemptHTTPHarness: attemptHarness, service: service, passwordHash: passwordHash, databaseURL: databaseURL,
|
||||
}
|
||||
}
|
||||
|
||||
// practiceCandidate is a candidate whose real attempt is at its main practice.
|
||||
|
||||
@@ -0,0 +1,680 @@
|
||||
//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
|
||||
}
|
||||
@@ -1499,19 +1499,22 @@ func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEsca
|
||||
// `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the
|
||||
// server answers 409 state_conflict.
|
||||
//
|
||||
// Availability. When code practice is not enabled on this server, the server answers 503
|
||||
// service_unavailable and stores nothing.
|
||||
// Limits. Debug runs are bounded by a per-candidate rate limit and by one unfinished run per practice;
|
||||
// either answers 429 rate_limited with Retry-After. The sandbox queue holds one running and ten
|
||||
// waiting runs and submissions together; when it is full the server answers 503 service_unavailable
|
||||
// with Retry-After and stores nothing. When code practice is not enabled on this server, the server
|
||||
// answers 503 service_unavailable without Retry-After and stores nothing.
|
||||
//
|
||||
// Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in
|
||||
// its current state with 202, without starting another run. A different body with the same key answers
|
||||
// 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are
|
||||
// 422 idempotency_key_reused. Refusals (400, 404, 409, 429, 503) are not stored under the key and are
|
||||
// evaluated again.
|
||||
//
|
||||
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
|
||||
// account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422,
|
||||
// replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of
|
||||
// another candidate), the state (409), then the solution against the item (400 with a pointer such as
|
||||
// `/language` or `/source_code`).
|
||||
// another candidate), the state (409), the solution against the item (400 with a pointer such as
|
||||
// `/language` or `/source_code`), the limits (429), then the queue (503).
|
||||
//
|
||||
// POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs
|
||||
func (s *Server) handleCreateMyAssessmentPracticeRunRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -778,6 +778,38 @@ func encodeCreateMyAssessmentPracticeRunResponse(response CreateMyAssessmentPrac
|
||||
|
||||
return nil
|
||||
|
||||
case *TooManyRequestsHeaders:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Retry-After" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Retry-After",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
if val, ok := response.RetryAfter.Get(); ok {
|
||||
return e.EncodeValue(conv.Int32ToString(val))
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Retry-After header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(429)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *ServiceUnavailableHeaders:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
|
||||
|
||||
@@ -32842,6 +32842,7 @@ func (*TooManyRequestsHeaders) cancelMyInvitationRes() {}
|
||||
func (*TooManyRequestsHeaders) confirmEmailByCodeRes() {}
|
||||
func (*TooManyRequestsHeaders) confirmEmailRes() {}
|
||||
func (*TooManyRequestsHeaders) createMyAssessmentAttemptRes() {}
|
||||
func (*TooManyRequestsHeaders) createMyAssessmentPracticeRunRes() {}
|
||||
func (*TooManyRequestsHeaders) createMySupportCaseRes() {}
|
||||
func (*TooManyRequestsHeaders) createOrganizationInvitationRes() {}
|
||||
func (*TooManyRequestsHeaders) createOrganizationNeedRes() {}
|
||||
|
||||
@@ -247,19 +247,22 @@ type Handler interface {
|
||||
// `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the
|
||||
// server answers 409 state_conflict.
|
||||
//
|
||||
// Availability. When code practice is not enabled on this server, the server answers 503
|
||||
// service_unavailable and stores nothing.
|
||||
// Limits. Debug runs are bounded by a per-candidate rate limit and by one unfinished run per practice;
|
||||
// either answers 429 rate_limited with Retry-After. The sandbox queue holds one running and ten
|
||||
// waiting runs and submissions together; when it is full the server answers 503 service_unavailable
|
||||
// with Retry-After and stores nothing. When code practice is not enabled on this server, the server
|
||||
// answers 503 service_unavailable without Retry-After and stores nothing.
|
||||
//
|
||||
// Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in
|
||||
// its current state with 202, without starting another run. A different body with the same key answers
|
||||
// 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are
|
||||
// 422 idempotency_key_reused. Refusals (400, 404, 409, 429, 503) are not stored under the key and are
|
||||
// evaluated again.
|
||||
//
|
||||
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
|
||||
// account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422,
|
||||
// replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of
|
||||
// another candidate), the state (409), then the solution against the item (400 with a pointer such as
|
||||
// `/language` or `/source_code`).
|
||||
// another candidate), the state (409), the solution against the item (400 with a pointer such as
|
||||
// `/language` or `/source_code`), the limits (429), then the queue (503).
|
||||
//
|
||||
// POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs
|
||||
CreateMyAssessmentPracticeRun(ctx context.Context, req *PracticeRunCreate, params CreateMyAssessmentPracticeRunParams) (CreateMyAssessmentPracticeRunRes, error)
|
||||
|
||||
@@ -270,19 +270,22 @@ func (UnimplementedHandler) CreateMyAssessmentAttempt(ctx context.Context, req A
|
||||
// `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the
|
||||
// server answers 409 state_conflict.
|
||||
//
|
||||
// Availability. When code practice is not enabled on this server, the server answers 503
|
||||
// service_unavailable and stores nothing.
|
||||
// Limits. Debug runs are bounded by a per-candidate rate limit and by one unfinished run per practice;
|
||||
// either answers 429 rate_limited with Retry-After. The sandbox queue holds one running and ten
|
||||
// waiting runs and submissions together; when it is full the server answers 503 service_unavailable
|
||||
// with Retry-After and stores nothing. When code practice is not enabled on this server, the server
|
||||
// answers 503 service_unavailable without Retry-After and stores nothing.
|
||||
//
|
||||
// Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in
|
||||
// its current state with 202, without starting another run. A different body with the same key answers
|
||||
// 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are
|
||||
// 422 idempotency_key_reused. Refusals (400, 404, 409, 429, 503) are not stored under the key and are
|
||||
// evaluated again.
|
||||
//
|
||||
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
|
||||
// account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422,
|
||||
// replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of
|
||||
// another candidate), the state (409), then the solution against the item (400 with a pointer such as
|
||||
// `/language` or `/source_code`).
|
||||
// another candidate), the state (409), the solution against the item (400 with a pointer such as
|
||||
// `/language` or `/source_code`), the limits (429), then the queue (503).
|
||||
//
|
||||
// POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs
|
||||
func (UnimplementedHandler) CreateMyAssessmentPracticeRun(ctx context.Context, req *PracticeRunCreate, params CreateMyAssessmentPracticeRunParams) (r CreateMyAssessmentPracticeRunRes, _ error) {
|
||||
|
||||
@@ -115,7 +115,15 @@ func (handler *PracticeHandler) GetMyAssessmentPracticeRun(
|
||||
|
||||
func practiceRunFailure(ctx context.Context, err error) (api.CreateMyAssessmentPracticeRunRes, error) {
|
||||
var fieldError *practice.FieldError
|
||||
var retryError *practice.RetryError
|
||||
switch {
|
||||
case errors.As(err, &retryError) && errors.Is(err, practice.ErrRateLimited):
|
||||
return problem.RateLimited(ctx, wholeSeconds(retryError.RetryAfter)), nil
|
||||
case errors.As(err, &retryError) && errors.Is(err, practice.ErrQueueBusy):
|
||||
busy := problem.New(ctx, api.ProblemCodeServiceUnavailable)
|
||||
return &api.ServiceUnavailableHeaders{
|
||||
RetryAfter: api.NewOptInt32(max(wholeSeconds(retryError.RetryAfter), 1)), Response: busy.Response,
|
||||
}, nil
|
||||
case errors.As(err, &fieldError):
|
||||
return (*api.CreateMyAssessmentPracticeRunBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "/"+fieldError.Field).Response), nil
|
||||
case errors.Is(err, practice.ErrInvalidKey):
|
||||
|
||||
@@ -162,6 +162,26 @@ func (repository assessmentPracticeRepository) LatestFinal(ctx context.Context,
|
||||
return solution, true, nil
|
||||
}
|
||||
|
||||
func (repository assessmentPracticeRepository) LockQueue(ctx context.Context) (int, error) {
|
||||
const location = "assessmentPracticeRepository.LockQueue"
|
||||
if err := repository.queries.LockAssessmentPracticeQueue(ctx); err != nil {
|
||||
return 0, fmt.Errorf("%s - lock queue: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
active, err := repository.queries.CountActiveAssessmentPracticeJobs(ctx)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s - count unfinished jobs: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
return int(active), nil
|
||||
}
|
||||
|
||||
func (repository assessmentPracticeRepository) ActiveRuns(ctx context.Context, practiceID uuid.UUID) (int, error) {
|
||||
active, err := repository.queries.CountActiveAssessmentPracticeRuns(ctx, pgUUID(practiceID))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("assessmentPracticeRepository.ActiveRuns - count unfinished runs: %w", mapAssessmentError(err))
|
||||
}
|
||||
return int(active), nil
|
||||
}
|
||||
|
||||
func (repository assessmentPracticeRepository) Submit(
|
||||
ctx context.Context,
|
||||
submission domain.PracticeSubmission,
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// Job states the worker side of the practice queue writes.
|
||||
const (
|
||||
practiceJobFinished = "finished"
|
||||
practiceJobFailed = "failed"
|
||||
)
|
||||
|
||||
// PracticeJobStore implements outbound.PracticeJobStore with a pgx pool owned
|
||||
// by the caller. Every method is one short transaction or statement, so no
|
||||
// transaction stays open while the runner works.
|
||||
type PracticeJobStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
var _ outbound.PracticeJobStore = (*PracticeJobStore)(nil)
|
||||
|
||||
func NewPracticeJobStore(pool *pgxpool.Pool) *PracticeJobStore {
|
||||
return &PracticeJobStore{pool: pool}
|
||||
}
|
||||
|
||||
func (store *PracticeJobStore) Claim(ctx context.Context, claim outbound.PracticeJobClaim) (outbound.ClaimedPracticeJob, bool, error) {
|
||||
const location = "PracticeJobStore.Claim"
|
||||
if claim.Owner == uuid.Nil || claim.Now.IsZero() || claim.Lease <= 0 || claim.MaxRunning < 1 {
|
||||
return outbound.ClaimedPracticeJob{}, false, errors.New(location + " - owner, now, lease, and running limit must be set")
|
||||
}
|
||||
expiresAt := claim.Now.Add(claim.Lease)
|
||||
var job outbound.ClaimedPracticeJob
|
||||
claimed := false
|
||||
err := store.inTransaction(ctx, func(queries *sqlc.Queries) error {
|
||||
if err := queries.LockAssessmentPracticeQueue(ctx); err != nil {
|
||||
return fmt.Errorf("lock queue: %w", err)
|
||||
}
|
||||
running, err := queries.CountLiveRunningAssessmentPracticeJobs(ctx, timestamp(claim.Now))
|
||||
if err != nil {
|
||||
return fmt.Errorf("count running jobs: %w", err)
|
||||
}
|
||||
if int(running) >= claim.MaxRunning {
|
||||
return nil
|
||||
}
|
||||
row, err := queries.ClaimAssessmentPracticeJob(ctx, sqlc.ClaimAssessmentPracticeJobParams{
|
||||
LeaseOwner: pgUUID(claim.Owner), LeaseExpiresAt: timestamp(expiresAt), Now: timestamp(claim.Now),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("claim job: %w", err)
|
||||
}
|
||||
mode := domain.PracticeSubmissionMode(row.Mode)
|
||||
if !row.SubmissionID.Valid || !mode.IsKnown() || row.Generation < 0 || row.Attempts < 0 {
|
||||
return fmt.Errorf("claimed job is incomplete: %w", domain.ErrInvalidAssessmentPractice)
|
||||
}
|
||||
job = outbound.ClaimedPracticeJob{
|
||||
SubmissionID: row.SubmissionID.Bytes, Mode: mode, Generation: uint32(row.Generation), Attempts: int(row.Attempts),
|
||||
LeaseOwner: claim.Owner, LeaseExpiresAt: expiresAt, StartedAt: claim.Now, Reclaimed: row.Reclaimed,
|
||||
}
|
||||
claimed = true
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.ClaimedPracticeJob{}, false, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
return job, claimed, nil
|
||||
}
|
||||
|
||||
func (store *PracticeJobStore) Work(ctx context.Context, job outbound.ClaimedPracticeJob) (outbound.PracticeJobWork, error) {
|
||||
const location = "PracticeJobStore.Work"
|
||||
row, err := sqlc.New(store.pool).GetAssessmentPracticeJobWork(ctx, pgUUID(job.SubmissionID))
|
||||
if err != nil {
|
||||
return outbound.PracticeJobWork{}, fmt.Errorf("%s - read submission: %w", location, sanitizedDatabaseError(err))
|
||||
}
|
||||
var task domain.PracticeTask
|
||||
if err := json.Unmarshal(row.Task, &task); err != nil {
|
||||
return outbound.PracticeJobWork{}, fmt.Errorf("%s - decode task: %w", location, domain.ErrInvalidAssessmentPractice)
|
||||
}
|
||||
submission := domain.PracticeSubmission{
|
||||
ID: row.ID.Bytes, PracticeID: row.PracticeID.Bytes, UserID: row.UserID.Bytes,
|
||||
Mode: domain.PracticeSubmissionMode(row.Mode), Language: domain.TaskLanguageCode(row.Language),
|
||||
Source: row.Source, CreatedAt: row.CreatedAt.Time.UTC(),
|
||||
}
|
||||
if len(row.CustomTests) > 0 {
|
||||
if err := json.Unmarshal(row.CustomTests, &submission.CustomTests); err != nil {
|
||||
return outbound.PracticeJobWork{}, fmt.Errorf("%s - decode custom tests: %w", location, domain.ErrInvalidAssessmentPractice)
|
||||
}
|
||||
}
|
||||
if err := task.Validate(); err != nil {
|
||||
return outbound.PracticeJobWork{}, fmt.Errorf("%s - validate task: %w", location, err)
|
||||
}
|
||||
if err := submission.Validate(task); err != nil {
|
||||
return outbound.PracticeJobWork{}, fmt.Errorf("%s - validate submission: %w", location, err)
|
||||
}
|
||||
return outbound.PracticeJobWork{Submission: submission, Task: task}, nil
|
||||
}
|
||||
|
||||
func (store *PracticeJobStore) Extend(
|
||||
ctx context.Context,
|
||||
job outbound.ClaimedPracticeJob,
|
||||
expiresAt time.Time,
|
||||
) (outbound.ClaimedPracticeJob, bool, error) {
|
||||
const location = "PracticeJobStore.Extend"
|
||||
if expiresAt.IsZero() {
|
||||
return outbound.ClaimedPracticeJob{}, false, errors.New(location + " - expiry must be set")
|
||||
}
|
||||
renewed, err := sqlc.New(store.pool).ExtendAssessmentPracticeJobLease(ctx, sqlc.ExtendAssessmentPracticeJobLeaseParams{
|
||||
LeaseExpiresAt: timestamp(expiresAt), SubmissionID: pgUUID(job.SubmissionID),
|
||||
LeaseOwner: pgUUID(job.LeaseOwner), StartedAt: timestamp(job.StartedAt),
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.ClaimedPracticeJob{}, false, fmt.Errorf("%s - renew lease: %w", location, sanitizedDatabaseError(err))
|
||||
}
|
||||
if renewed != 1 {
|
||||
return outbound.ClaimedPracticeJob{}, false, nil
|
||||
}
|
||||
job.LeaseExpiresAt = expiresAt
|
||||
return job, true, nil
|
||||
}
|
||||
|
||||
func (store *PracticeJobStore) Requeue(ctx context.Context, job outbound.ClaimedPracticeJob, requeue outbound.PracticeRequeue) (bool, error) {
|
||||
const location = "PracticeJobStore.Requeue"
|
||||
if requeue.AvailableAt.IsZero() || requeue.Generation > math.MaxInt32 {
|
||||
return false, errors.New(location + " - availability must be set and the generation in range")
|
||||
}
|
||||
counted := int32(0)
|
||||
if requeue.Counted {
|
||||
counted = 1
|
||||
}
|
||||
updated, err := sqlc.New(store.pool).RequeueAssessmentPracticeJob(ctx, sqlc.RequeueAssessmentPracticeJobParams{
|
||||
AvailableAt: timestamp(requeue.AvailableAt), Generation: int32(requeue.Generation), Counted: counted,
|
||||
ErrorClass: pgOptionalText(string(requeue.ErrorClass)), SubmissionID: pgUUID(job.SubmissionID),
|
||||
LeaseOwner: pgUUID(job.LeaseOwner), StartedAt: timestamp(job.StartedAt),
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - requeue job: %w", location, sanitizedDatabaseError(err))
|
||||
}
|
||||
return updated == 1, nil
|
||||
}
|
||||
|
||||
func (store *PracticeJobStore) Complete(ctx context.Context, job outbound.ClaimedPracticeJob, result domain.PracticeRunResult) (bool, error) {
|
||||
const location = "PracticeJobStore.Complete"
|
||||
if err := result.Validate(); err != nil {
|
||||
return false, fmt.Errorf("%s - validate result: %w", location, err)
|
||||
}
|
||||
encoded, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - encode result: %w", location, domain.ErrInvalidAssessmentPractice)
|
||||
}
|
||||
held := false
|
||||
err = store.inTransaction(ctx, func(queries *sqlc.Queries) error {
|
||||
mode, locked, err := lockClaimedPracticeJob(ctx, queries, job)
|
||||
if err != nil || !locked {
|
||||
return err
|
||||
}
|
||||
stored, err := queries.StoreAssessmentPracticeResult(ctx, sqlc.StoreAssessmentPracticeResultParams{
|
||||
Result: encoded, ID: pgUUID(job.SubmissionID),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("store result: %w", err)
|
||||
}
|
||||
if stored != 1 {
|
||||
return outbound.ErrPracticeResultExists
|
||||
}
|
||||
if err := finishPracticeJob(ctx, queries, job, practiceJobFinished, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
if mode == domain.PracticeModeFinal {
|
||||
if err := settlePractice(ctx, queries, job, domain.AssessmentPracticeFinished, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
held = true
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
return held, nil
|
||||
}
|
||||
|
||||
func (store *PracticeJobStore) Fail(ctx context.Context, job outbound.ClaimedPracticeJob, class outbound.PracticeJobErrorClass) (bool, error) {
|
||||
const location = "PracticeJobStore.Fail"
|
||||
if class == "" {
|
||||
return false, errors.New(location + " - error class must be set")
|
||||
}
|
||||
held := false
|
||||
err := store.inTransaction(ctx, func(queries *sqlc.Queries) error {
|
||||
mode, locked, err := lockClaimedPracticeJob(ctx, queries, job)
|
||||
if err != nil || !locked {
|
||||
return err
|
||||
}
|
||||
if err := finishPracticeJob(ctx, queries, job, practiceJobFailed, class); err != nil {
|
||||
return err
|
||||
}
|
||||
if mode == domain.PracticeModeFinal {
|
||||
if err := settlePractice(ctx, queries, job, domain.AssessmentPracticeFailed, domain.AssessmentPracticeSandboxError); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
held = true
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
return held, nil
|
||||
}
|
||||
|
||||
// lockClaimedPracticeJob locks the job of a try and reports whether the try
|
||||
// still holds it.
|
||||
func lockClaimedPracticeJob(
|
||||
ctx context.Context,
|
||||
queries *sqlc.Queries,
|
||||
job outbound.ClaimedPracticeJob,
|
||||
) (domain.PracticeSubmissionMode, bool, error) {
|
||||
mode, err := queries.LockClaimedAssessmentPracticeJob(ctx, sqlc.LockClaimedAssessmentPracticeJobParams{
|
||||
SubmissionID: pgUUID(job.SubmissionID), LeaseOwner: pgUUID(job.LeaseOwner), StartedAt: timestamp(job.StartedAt),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("lock job: %w", err)
|
||||
}
|
||||
return domain.PracticeSubmissionMode(mode), true, nil
|
||||
}
|
||||
|
||||
func finishPracticeJob(
|
||||
ctx context.Context,
|
||||
queries *sqlc.Queries,
|
||||
job outbound.ClaimedPracticeJob,
|
||||
state string,
|
||||
class outbound.PracticeJobErrorClass,
|
||||
) error {
|
||||
finished, err := queries.FinishAssessmentPracticeJob(ctx, sqlc.FinishAssessmentPracticeJobParams{
|
||||
State: state, ErrorClass: pgOptionalText(string(class)), SubmissionID: pgUUID(job.SubmissionID),
|
||||
LeaseOwner: pgUUID(job.LeaseOwner), StartedAt: timestamp(job.StartedAt),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("finish job: %w", err)
|
||||
}
|
||||
if finished != 1 {
|
||||
return errors.New("finish job: the locked job changed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// settlePractice moves the practice of a final submission out of pending. It
|
||||
// changes nothing when a later final submission replaced this one.
|
||||
func settlePractice(
|
||||
ctx context.Context,
|
||||
queries *sqlc.Queries,
|
||||
job outbound.ClaimedPracticeJob,
|
||||
status domain.AssessmentPracticeStatus,
|
||||
reason domain.AssessmentPracticeFailureReason,
|
||||
) error {
|
||||
if _, err := queries.SettleAssessmentPracticeAfterJob(ctx, sqlc.SettleAssessmentPracticeAfterJobParams{
|
||||
Status: string(status), FailureReason: pgOptionalText(string(reason)), SubmissionID: pgUUID(job.SubmissionID),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("settle practice: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// inTransaction runs fn in one READ COMMITTED transaction and keeps only the
|
||||
// SQLSTATE of a database error, whose text could quote submitted code.
|
||||
func (store *PracticeJobStore) inTransaction(ctx context.Context, fn func(queries *sqlc.Queries) error) error {
|
||||
tx, err := store.pool.BeginTx(ctx, transactionOptions)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin transaction: %w", sanitizeConnectError(err))
|
||||
}
|
||||
if err := fn(sqlc.New(tx)); err != nil {
|
||||
rollbackErr := rollback(ctx, tx)
|
||||
return errors.Join(sanitizedDatabaseError(err), rollbackErr)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit transaction: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -172,6 +172,7 @@ INSERT INTO assessment_practice_jobs (
|
||||
submission_id,
|
||||
mode,
|
||||
state,
|
||||
available_at,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
@@ -179,6 +180,7 @@ INSERT INTO assessment_practice_jobs (
|
||||
$2,
|
||||
'queued',
|
||||
$3,
|
||||
$3,
|
||||
$3
|
||||
)
|
||||
`
|
||||
@@ -190,7 +192,7 @@ type InsertAssessmentPracticeJobParams struct {
|
||||
}
|
||||
|
||||
// Queues the execution job of a submission in the transaction that stores
|
||||
// the submission.
|
||||
// the submission. The job is available at once.
|
||||
func (q *Queries) InsertAssessmentPracticeJob(ctx context.Context, arg InsertAssessmentPracticeJobParams) error {
|
||||
_, err := q.db.Exec(ctx, insertAssessmentPracticeJob, arg.SubmissionID, arg.Mode, arg.CreatedAt)
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: assessment_practice_queue.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const claimAssessmentPracticeJob = `-- name: ClaimAssessmentPracticeJob :one
|
||||
WITH candidate AS (
|
||||
SELECT
|
||||
job.submission_id,
|
||||
job.state = 'running' AS reclaimed
|
||||
FROM assessment_practice_jobs AS job
|
||||
WHERE
|
||||
(job.state = 'queued' AND job.available_at <= $3::timestamptz)
|
||||
OR (job.state = 'running' AND job.lease_expires_at <= $3::timestamptz)
|
||||
ORDER BY
|
||||
job.state = 'running' DESC,
|
||||
job.mode = 'final' DESC,
|
||||
job.available_at ASC,
|
||||
job.created_at ASC,
|
||||
job.submission_id ASC
|
||||
LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
|
||||
UPDATE assessment_practice_jobs AS job
|
||||
SET
|
||||
state = 'running',
|
||||
lease_owner = $1,
|
||||
lease_expires_at = $2,
|
||||
started_at = $3::timestamptz,
|
||||
attempts = job.attempts + CASE WHEN candidate.reclaimed THEN 1 ELSE 0 END,
|
||||
last_error_class = CASE
|
||||
WHEN candidate.reclaimed THEN 'lease_expired' ELSE job.last_error_class
|
||||
END,
|
||||
updated_at = greatest(job.updated_at, clock_timestamp())
|
||||
FROM candidate
|
||||
WHERE job.submission_id = candidate.submission_id
|
||||
RETURNING
|
||||
job.submission_id,
|
||||
job.mode,
|
||||
job.generation,
|
||||
job.attempts,
|
||||
candidate.reclaimed
|
||||
`
|
||||
|
||||
type ClaimAssessmentPracticeJobParams struct {
|
||||
LeaseOwner pgtype.UUID
|
||||
LeaseExpiresAt pgtype.Timestamptz
|
||||
Now pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type ClaimAssessmentPracticeJobRow struct {
|
||||
SubmissionID pgtype.UUID
|
||||
Mode string
|
||||
Generation int32
|
||||
Attempts int32
|
||||
Reclaimed bool
|
||||
}
|
||||
|
||||
// Claims one job under the queue lock: first a running job whose lease
|
||||
// expired (its worker stopped without finishing it), then the next queued
|
||||
// job, final submissions before debug runs. A takeover keeps the generation,
|
||||
// so the runner returns the run it already has, and counts one attempt.
|
||||
func (q *Queries) ClaimAssessmentPracticeJob(ctx context.Context, arg ClaimAssessmentPracticeJobParams) (ClaimAssessmentPracticeJobRow, error) {
|
||||
row := q.db.QueryRow(ctx, claimAssessmentPracticeJob, arg.LeaseOwner, arg.LeaseExpiresAt, arg.Now)
|
||||
var i ClaimAssessmentPracticeJobRow
|
||||
err := row.Scan(
|
||||
&i.SubmissionID,
|
||||
&i.Mode,
|
||||
&i.Generation,
|
||||
&i.Attempts,
|
||||
&i.Reclaimed,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const countActiveAssessmentPracticeJobs = `-- name: CountActiveAssessmentPracticeJobs :one
|
||||
SELECT count(*)::integer AS active
|
||||
FROM assessment_practice_jobs AS job
|
||||
WHERE job.state IN ('queued', 'running')
|
||||
`
|
||||
|
||||
// Counts the queued and running jobs; the caller holds the queue lock.
|
||||
func (q *Queries) CountActiveAssessmentPracticeJobs(ctx context.Context) (int32, error) {
|
||||
row := q.db.QueryRow(ctx, countActiveAssessmentPracticeJobs)
|
||||
var active int32
|
||||
err := row.Scan(&active)
|
||||
return active, err
|
||||
}
|
||||
|
||||
const countActiveAssessmentPracticeRuns = `-- name: CountActiveAssessmentPracticeRuns :one
|
||||
SELECT count(*)::integer AS active
|
||||
FROM assessment_practice_jobs AS job
|
||||
INNER JOIN assessment_practice_submissions AS submission ON job.submission_id = submission.id
|
||||
WHERE
|
||||
submission.practice_id = $1
|
||||
AND job.mode = 'public'
|
||||
AND job.state IN ('queued', 'running')
|
||||
`
|
||||
|
||||
// Counts the unfinished debug runs of a practice; the caller holds the
|
||||
// practice row lock.
|
||||
func (q *Queries) CountActiveAssessmentPracticeRuns(ctx context.Context, practiceID pgtype.UUID) (int32, error) {
|
||||
row := q.db.QueryRow(ctx, countActiveAssessmentPracticeRuns, practiceID)
|
||||
var active int32
|
||||
err := row.Scan(&active)
|
||||
return active, err
|
||||
}
|
||||
|
||||
const countLiveRunningAssessmentPracticeJobs = `-- name: CountLiveRunningAssessmentPracticeJobs :one
|
||||
SELECT count(*)::integer AS running
|
||||
FROM assessment_practice_jobs AS job
|
||||
WHERE
|
||||
job.state = 'running'
|
||||
AND job.lease_expires_at > $1::timestamptz
|
||||
`
|
||||
|
||||
// Counts running jobs whose lease has not expired by now, the application
|
||||
// clock; the caller holds the queue lock.
|
||||
func (q *Queries) CountLiveRunningAssessmentPracticeJobs(ctx context.Context, now pgtype.Timestamptz) (int32, error) {
|
||||
row := q.db.QueryRow(ctx, countLiveRunningAssessmentPracticeJobs, now)
|
||||
var running int32
|
||||
err := row.Scan(&running)
|
||||
return running, err
|
||||
}
|
||||
|
||||
const extendAssessmentPracticeJobLease = `-- name: ExtendAssessmentPracticeJobLease :execrows
|
||||
UPDATE assessment_practice_jobs
|
||||
SET
|
||||
lease_expires_at = $1,
|
||||
updated_at = greatest(updated_at, clock_timestamp())
|
||||
WHERE
|
||||
submission_id = $2
|
||||
AND state = 'running'
|
||||
AND lease_owner = $3
|
||||
AND started_at = $4
|
||||
`
|
||||
|
||||
type ExtendAssessmentPracticeJobLeaseParams struct {
|
||||
LeaseExpiresAt pgtype.Timestamptz
|
||||
SubmissionID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
StartedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Renews the lease of a running try. The owner and the start time identify
|
||||
// the try, so a worker whose job was taken over changes nothing.
|
||||
func (q *Queries) ExtendAssessmentPracticeJobLease(ctx context.Context, arg ExtendAssessmentPracticeJobLeaseParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, extendAssessmentPracticeJobLease,
|
||||
arg.LeaseExpiresAt,
|
||||
arg.SubmissionID,
|
||||
arg.LeaseOwner,
|
||||
arg.StartedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const finishAssessmentPracticeJob = `-- name: FinishAssessmentPracticeJob :execrows
|
||||
UPDATE assessment_practice_jobs
|
||||
SET
|
||||
state = $1,
|
||||
finished_at = greatest(created_at, clock_timestamp()),
|
||||
last_error_class = coalesce($2, last_error_class),
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
started_at = NULL,
|
||||
updated_at = greatest(updated_at, clock_timestamp())
|
||||
WHERE
|
||||
submission_id = $3
|
||||
AND state = 'running'
|
||||
AND lease_owner = $4
|
||||
AND started_at = $5
|
||||
`
|
||||
|
||||
type FinishAssessmentPracticeJobParams struct {
|
||||
State string
|
||||
ErrorClass pgtype.Text
|
||||
SubmissionID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
StartedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Ends a running try as finished or failed.
|
||||
func (q *Queries) FinishAssessmentPracticeJob(ctx context.Context, arg FinishAssessmentPracticeJobParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, finishAssessmentPracticeJob,
|
||||
arg.State,
|
||||
arg.ErrorClass,
|
||||
arg.SubmissionID,
|
||||
arg.LeaseOwner,
|
||||
arg.StartedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const getAssessmentPracticeJobWork = `-- name: GetAssessmentPracticeJobWork :one
|
||||
SELECT
|
||||
submission.id,
|
||||
submission.practice_id,
|
||||
submission.user_id,
|
||||
submission.mode,
|
||||
submission.language,
|
||||
submission.source,
|
||||
submission.custom_tests,
|
||||
submission.created_at,
|
||||
practice.task
|
||||
FROM assessment_practice_submissions AS submission
|
||||
INNER JOIN assessment_practices AS practice ON submission.practice_id = practice.id
|
||||
WHERE submission.id = $1
|
||||
`
|
||||
|
||||
type GetAssessmentPracticeJobWorkRow struct {
|
||||
ID pgtype.UUID
|
||||
PracticeID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
Mode string
|
||||
Language string
|
||||
Source string
|
||||
CustomTests []byte
|
||||
CreatedAt pgtype.Timestamptz
|
||||
Task []byte
|
||||
}
|
||||
|
||||
// Reads what a claimed job runs: the submission and the task of its
|
||||
// practice.
|
||||
func (q *Queries) GetAssessmentPracticeJobWork(ctx context.Context, submissionID pgtype.UUID) (GetAssessmentPracticeJobWorkRow, error) {
|
||||
row := q.db.QueryRow(ctx, getAssessmentPracticeJobWork, submissionID)
|
||||
var i GetAssessmentPracticeJobWorkRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.PracticeID,
|
||||
&i.UserID,
|
||||
&i.Mode,
|
||||
&i.Language,
|
||||
&i.Source,
|
||||
&i.CustomTests,
|
||||
&i.CreatedAt,
|
||||
&i.Task,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const lockAssessmentPracticeQueue = `-- name: LockAssessmentPracticeQueue :exec
|
||||
|
||||
SELECT pg_advisory_xact_lock(hashtextextended('lincodex.assessment.practice_queue', 0))
|
||||
`
|
||||
|
||||
// The practice queue. Admission and the claim take the same
|
||||
// transaction-scoped advisory lock, so the count of unfinished jobs and the
|
||||
// change that depends on it are atomic across backend instances. A command
|
||||
// takes the lock after its attempt and practice row locks; the claim takes
|
||||
// it first and then skips job rows that another transaction locks, so a
|
||||
// claim never waits for a row lock while it holds the queue lock.
|
||||
func (q *Queries) LockAssessmentPracticeQueue(ctx context.Context) error {
|
||||
_, err := q.db.Exec(ctx, lockAssessmentPracticeQueue)
|
||||
return err
|
||||
}
|
||||
|
||||
const lockClaimedAssessmentPracticeJob = `-- name: LockClaimedAssessmentPracticeJob :one
|
||||
SELECT job.mode
|
||||
FROM assessment_practice_jobs AS job
|
||||
WHERE
|
||||
job.submission_id = $1
|
||||
AND job.state = 'running'
|
||||
AND job.lease_owner = $2
|
||||
AND job.started_at = $3
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type LockClaimedAssessmentPracticeJobParams struct {
|
||||
SubmissionID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
StartedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Locks a running try for its completion and checks that it still belongs
|
||||
// to the worker.
|
||||
func (q *Queries) LockClaimedAssessmentPracticeJob(ctx context.Context, arg LockClaimedAssessmentPracticeJobParams) (string, error) {
|
||||
row := q.db.QueryRow(ctx, lockClaimedAssessmentPracticeJob, arg.SubmissionID, arg.LeaseOwner, arg.StartedAt)
|
||||
var mode string
|
||||
err := row.Scan(&mode)
|
||||
return mode, err
|
||||
}
|
||||
|
||||
const requeueAssessmentPracticeJob = `-- name: RequeueAssessmentPracticeJob :execrows
|
||||
UPDATE assessment_practice_jobs
|
||||
SET
|
||||
state = 'queued',
|
||||
available_at = $1,
|
||||
generation = $2,
|
||||
attempts = attempts + $3::integer,
|
||||
last_error_class = coalesce($4, last_error_class),
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
started_at = NULL,
|
||||
updated_at = greatest(updated_at, clock_timestamp())
|
||||
WHERE
|
||||
submission_id = $5
|
||||
AND state = 'running'
|
||||
AND lease_owner = $6
|
||||
AND started_at = $7
|
||||
`
|
||||
|
||||
type RequeueAssessmentPracticeJobParams struct {
|
||||
AvailableAt pgtype.Timestamptz
|
||||
Generation int32
|
||||
Counted int32
|
||||
ErrorClass pgtype.Text
|
||||
SubmissionID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
StartedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Puts a running try back into the queue: after a busy runner, a failed
|
||||
// try, or at shutdown. counted adds the try to the attempts.
|
||||
func (q *Queries) RequeueAssessmentPracticeJob(ctx context.Context, arg RequeueAssessmentPracticeJobParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, requeueAssessmentPracticeJob,
|
||||
arg.AvailableAt,
|
||||
arg.Generation,
|
||||
arg.Counted,
|
||||
arg.ErrorClass,
|
||||
arg.SubmissionID,
|
||||
arg.LeaseOwner,
|
||||
arg.StartedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const settleAssessmentPracticeAfterJob = `-- name: SettleAssessmentPracticeAfterJob :execrows
|
||||
UPDATE assessment_practices AS practice
|
||||
SET
|
||||
status = $1,
|
||||
failure_reason = $2,
|
||||
updated_at = greatest(practice.updated_at, clock_timestamp())
|
||||
WHERE
|
||||
practice.status = 'pending'
|
||||
AND practice.id = (
|
||||
SELECT submission.practice_id
|
||||
FROM assessment_practice_submissions AS submission
|
||||
WHERE submission.id = $3
|
||||
)
|
||||
AND $3::uuid = (
|
||||
SELECT latest.id
|
||||
FROM assessment_practice_submissions AS latest
|
||||
WHERE
|
||||
latest.practice_id = practice.id
|
||||
AND latest.mode = 'final'
|
||||
ORDER BY latest.created_at DESC, latest.id DESC
|
||||
LIMIT 1
|
||||
)
|
||||
`
|
||||
|
||||
type SettleAssessmentPracticeAfterJobParams struct {
|
||||
Status string
|
||||
FailureReason pgtype.Text
|
||||
SubmissionID pgtype.UUID
|
||||
}
|
||||
|
||||
// Moves the practice of a final submission out of pending, but only while
|
||||
// that submission is the latest final one of the practice.
|
||||
func (q *Queries) SettleAssessmentPracticeAfterJob(ctx context.Context, arg SettleAssessmentPracticeAfterJobParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, settleAssessmentPracticeAfterJob, arg.Status, arg.FailureReason, arg.SubmissionID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const storeAssessmentPracticeResult = `-- name: StoreAssessmentPracticeResult :execrows
|
||||
UPDATE assessment_practice_submissions
|
||||
SET
|
||||
result = $1,
|
||||
result_at = greatest(created_at, clock_timestamp())
|
||||
WHERE
|
||||
id = $2
|
||||
AND result IS NULL
|
||||
`
|
||||
|
||||
type StoreAssessmentPracticeResultParams struct {
|
||||
Result []byte
|
||||
ID pgtype.UUID
|
||||
}
|
||||
|
||||
// Stores the result of a submission once; a second result changes nothing.
|
||||
func (q *Queries) StoreAssessmentPracticeResult(ctx context.Context, arg StoreAssessmentPracticeResultParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, storeAssessmentPracticeResult, arg.Result, arg.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -243,12 +243,19 @@ type AssessmentPractice struct {
|
||||
}
|
||||
|
||||
type AssessmentPracticeJob struct {
|
||||
SubmissionID pgtype.UUID
|
||||
Mode string
|
||||
State string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
FinishedAt pgtype.Timestamptz
|
||||
SubmissionID pgtype.UUID
|
||||
Mode string
|
||||
State string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
FinishedAt pgtype.Timestamptz
|
||||
Generation int32
|
||||
Attempts int32
|
||||
AvailableAt pgtype.Timestamptz
|
||||
LeaseOwner pgtype.UUID
|
||||
LeaseExpiresAt pgtype.Timestamptz
|
||||
StartedAt pgtype.Timestamptz
|
||||
LastErrorClass pgtype.Text
|
||||
}
|
||||
|
||||
type AssessmentPracticeSubmission struct {
|
||||
|
||||
@@ -74,6 +74,11 @@ type Querier interface {
|
||||
// organization already appears in their own access history or is already
|
||||
// hidden. Unknown and unseen organizations produce the same no-row result.
|
||||
CandidateCanSeeOrganization(ctx context.Context, arg CandidateCanSeeOrganizationParams) (CandidateCanSeeOrganizationRow, error)
|
||||
// Claims one job under the queue lock: first a running job whose lease
|
||||
// expired (its worker stopped without finishing it), then the next queued
|
||||
// job, final submissions before debug runs. A takeover keeps the generation,
|
||||
// so the runner returns the run it already has, and counts one attempt.
|
||||
ClaimAssessmentPracticeJob(ctx context.Context, arg ClaimAssessmentPracticeJobParams) (ClaimAssessmentPracticeJobRow, error)
|
||||
// Claims the most overdue delivery that the sending worker may send, in one
|
||||
// statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds
|
||||
// (the literals match the predicate of deliveries_due_idx, so an idle poll
|
||||
@@ -148,6 +153,11 @@ type Querier interface {
|
||||
// returned registration version in the same transaction, rolled back when it
|
||||
// matches no row.
|
||||
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error)
|
||||
// Counts the queued and running jobs; the caller holds the queue lock.
|
||||
CountActiveAssessmentPracticeJobs(ctx context.Context) (int32, error)
|
||||
// Counts the unfinished debug runs of a practice; the caller holds the
|
||||
// practice row lock.
|
||||
CountActiveAssessmentPracticeRuns(ctx context.Context, practiceID pgtype.UUID) (int32, error)
|
||||
// Count events only for the already owner-locked attempt.
|
||||
CountAssessmentSignalEvents(ctx context.Context, attemptID pgtype.UUID) (int64, error)
|
||||
// Counts the hiding records of one candidate for the settings read.
|
||||
@@ -163,6 +173,9 @@ type Querier interface {
|
||||
// row stays attributed to the organization that consumed it.
|
||||
CountCompanyInvitationQuotaHoldingWindow(ctx context.Context, arg CountCompanyInvitationQuotaHoldingWindowParams) (CountCompanyInvitationQuotaHoldingWindowRow, error)
|
||||
CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error)
|
||||
// Counts running jobs whose lease has not expired by now, the application
|
||||
// clock; the caller holds the queue lock.
|
||||
CountLiveRunningAssessmentPracticeJobs(ctx context.Context, now pgtype.Timestamptz) (int32, error)
|
||||
// Counts the invitations of one organization need that wait for an answer:
|
||||
// delivered, viewed, or the planned counter offer. The send counts them under
|
||||
// the organization lock, which every send takes first, so no other send can
|
||||
@@ -272,6 +285,9 @@ type Querier interface {
|
||||
// sets the timeout reason. No row is returned when it lost a race or the
|
||||
// deadline has not passed.
|
||||
ExpireInvitation(ctx context.Context, arg ExpireInvitationParams) (pgtype.UUID, error)
|
||||
// Renews the lease of a running try. The owner and the start time identify
|
||||
// the try, so a worker whose job was taken over changes nothing.
|
||||
ExtendAssessmentPracticeJobLease(ctx context.Context, arg ExtendAssessmentPracticeJobLeaseParams) (int64, error)
|
||||
// Records a failed attempt after its handler transaction rolled back: the
|
||||
// job waits for its retry at retry_at (status failed) or is dead, with a
|
||||
// NULL retry_at. due_at keeps the deadline. The same guard as the
|
||||
@@ -291,6 +307,8 @@ type Querier interface {
|
||||
// made at or after reserved_since. A retry of the delivery inside the
|
||||
// provider's idempotency window reuses it instead of counting again.
|
||||
FindOpenMailQuotaReservation(ctx context.Context, arg FindOpenMailQuotaReservationParams) (FindOpenMailQuotaReservationRow, error)
|
||||
// Ends a running try as finished or failed.
|
||||
FinishAssessmentPracticeJob(ctx context.Context, arg FinishAssessmentPracticeJobParams) (int64, error)
|
||||
// Reads the durable active deletion request when an earlier request already
|
||||
// exists. A completed request does not suppress a later explicit request.
|
||||
GetActiveAccountDeletionRequest(ctx context.Context, subjectID pgtype.UUID) (GetActiveAccountDeletionRequestRow, error)
|
||||
@@ -317,6 +335,9 @@ type Querier interface {
|
||||
GetAssessmentClientSignalTotals(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentClientSignalTotalsRow, error)
|
||||
GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error)
|
||||
GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error)
|
||||
// Reads what a claimed job runs: the submission and the task of its
|
||||
// practice.
|
||||
GetAssessmentPracticeJobWork(ctx context.Context, submissionID pgtype.UUID) (GetAssessmentPracticeJobWorkRow, error)
|
||||
// Reads a debug run of the owner's attempt with the state of its job.
|
||||
GetAssessmentPracticeRun(ctx context.Context, arg GetAssessmentPracticeRunParams) (GetAssessmentPracticeRunRow, error)
|
||||
// The attempt a review job works on: real attempts only.
|
||||
@@ -497,7 +518,7 @@ type Querier interface {
|
||||
InsertAssessmentOriginMark(ctx context.Context, arg InsertAssessmentOriginMarkParams) error
|
||||
InsertAssessmentPractice(ctx context.Context, arg InsertAssessmentPracticeParams) error
|
||||
// Queues the execution job of a submission in the transaction that stores
|
||||
// the submission.
|
||||
// the submission. The job is available at once.
|
||||
InsertAssessmentPracticeJob(ctx context.Context, arg InsertAssessmentPracticeJobParams) error
|
||||
InsertAssessmentPracticeSubmission(ctx context.Context, arg InsertAssessmentPracticeSubmissionParams) error
|
||||
InsertAssessmentReviewRead(ctx context.Context, arg InsertAssessmentReviewReadParams) error
|
||||
@@ -859,6 +880,13 @@ type Querier interface {
|
||||
LockAssessmentCategory(ctx context.Context, category string) error
|
||||
// Locks one practice of the owner's attempt for a state change.
|
||||
LockAssessmentPractice(ctx context.Context, arg LockAssessmentPracticeParams) (LockAssessmentPracticeRow, error)
|
||||
// The practice queue. Admission and the claim take the same
|
||||
// transaction-scoped advisory lock, so the count of unfinished jobs and the
|
||||
// change that depends on it are atomic across backend instances. A command
|
||||
// takes the lock after its attempt and practice row locks; the claim takes
|
||||
// it first and then skips job rows that another transaction locks, so a
|
||||
// claim never waits for a row lock while it holds the queue lock.
|
||||
LockAssessmentPracticeQueue(ctx context.Context) error
|
||||
// Serializes the evaluations of one review. A job takes these locks for every
|
||||
// attempt it will write, in ascending attempt order, before it reads any fact,
|
||||
// so what it reads is what the previous writer committed.
|
||||
@@ -880,6 +908,9 @@ type Querier interface {
|
||||
// keeps the consent-revoked reason after later grants. The returned time is
|
||||
// the effective close time used by the privacy history event.
|
||||
LockCandidatePublicationForConsentRevocation(ctx context.Context, arg LockCandidatePublicationForConsentRevocationParams) (pgtype.Timestamptz, error)
|
||||
// Locks a running try for its completion and checks that it still belongs
|
||||
// to the worker.
|
||||
LockClaimedAssessmentPracticeJob(ctx context.Context, arg LockClaimedAssessmentPracticeJobParams) (string, error)
|
||||
// Locks the delivery row of the lease holder until the transaction ends, so
|
||||
// every path that settles a send takes the delivery lock before the quota
|
||||
// rows, the same order as the claim. No row means that owner no longer holds
|
||||
@@ -1158,6 +1189,9 @@ type Querier interface {
|
||||
ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error)
|
||||
// A new repository starts pending; a known one only records the request.
|
||||
RequestCandidateProjectRepositoryCheck(ctx context.Context, arg RequestCandidateProjectRepositoryCheckParams) error
|
||||
// Puts a running try back into the queue: after a busy runner, a failed
|
||||
// try, or at shutdown. counted adds the try to the attempts.
|
||||
RequeueAssessmentPracticeJob(ctx context.Context, arg RequeueAssessmentPracticeJobParams) (int64, error)
|
||||
// Stores the replay record of a command. A record whose retention has passed
|
||||
// is replaced, so the key is accepted as new after the retention. A live
|
||||
// record is left as it is and nothing is returned; the caller then reads it
|
||||
@@ -1218,6 +1252,9 @@ type Querier interface {
|
||||
// handler, which releases the job row lock so the job can be reclaimed once
|
||||
// its lease expires.
|
||||
SetScheduledJobTransactionTimeouts(ctx context.Context, arg SetScheduledJobTransactionTimeoutsParams) error
|
||||
// Moves the practice of a final submission out of pending, but only while
|
||||
// that submission is the latest final one of the practice.
|
||||
SettleAssessmentPracticeAfterJob(ctx context.Context, arg SettleAssessmentPracticeAfterJobParams) (int64, error)
|
||||
// Starts a claimed attempt right before its handler transaction: it renews
|
||||
// the lease from now and records the start, committed on its own. It
|
||||
// changes nothing when the lease already expired by now or no longer
|
||||
@@ -1229,6 +1266,8 @@ type Querier interface {
|
||||
// fictitious provider attempt, for example when the 23-hour safety cutoff is
|
||||
// reached after the claim but before the provider call.
|
||||
StopUnknownDeliveryRetry(ctx context.Context, arg StopUnknownDeliveryRetryParams) (int64, error)
|
||||
// Stores the result of a submission once; a second result changes nothing.
|
||||
StoreAssessmentPracticeResult(ctx context.Context, arg StoreAssessmentPracticeResultParams) (int64, error)
|
||||
// Records activity on an active session and reports whether it is active.
|
||||
// The row is written only when last_seen_at is older than touch_cutoff, so
|
||||
// frequent requests do not rewrite it. last_seen_at never moves back, and a
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"lincodex/backend/internal/worker/jobrunner"
|
||||
"lincodex/backend/internal/worker/mailsender"
|
||||
"lincodex/backend/internal/worker/outboxrelay"
|
||||
"lincodex/backend/internal/worker/practicequeue"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -37,9 +38,9 @@ type Application struct {
|
||||
// mailSender is the transport selected by EMAIL_PROVIDER. Only the mail
|
||||
// sending worker calls it.
|
||||
mailSender outbound.MailSender
|
||||
// codeRunner is the runner selected by CODE_RUNNER_URL: the disabled one
|
||||
// when unset. Practice usecases receive it from here once they exist.
|
||||
codeRunner outbound.CodeRunner
|
||||
// practiceQueue runs practice jobs on the code runner while the servers
|
||||
// run. It is nil without a configured code runner or database.
|
||||
practiceQueue *practicequeue.Worker
|
||||
// relay publishes outbox events while the servers run. It is nil when
|
||||
// the relay is disabled or the database is not configured.
|
||||
relay *outboxrelay.Relay
|
||||
@@ -156,10 +157,18 @@ func start(ctx context.Context, config config.Config, logger *slog.Logger) (*App
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.start - initialize application: %w", err)
|
||||
}
|
||||
// No dependency needs the runner yet, so it is attached here rather than
|
||||
// injected; the practice usecases will take it from the injector.
|
||||
application.codeRunner = codeRunner
|
||||
return application, cleanup, nil
|
||||
// The worker is the only consumer of the runner, so it is built here
|
||||
// with the runner rather than through the injector.
|
||||
practiceQueue, closeQueue, err := newPracticeQueueWorker(ctx, config, logger, codeRunner)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("bootstrap.start - create practice queue worker: %w", err)
|
||||
}
|
||||
application.practiceQueue = practiceQueue
|
||||
return application, func() {
|
||||
closeQueue()
|
||||
cleanup()
|
||||
}, nil
|
||||
}
|
||||
|
||||
func logLevel(value string) logkit.Level {
|
||||
@@ -223,7 +232,8 @@ func (application *Application) run(ctx context.Context) error {
|
||||
}
|
||||
|
||||
// startWorkers runs the relay, every consumer, the scheduled job worker, the
|
||||
// mail sending worker, and the delivery metrics sampler until ctx ends and returns a channel that
|
||||
// mail sending worker, the delivery metrics sampler, and the practice queue
|
||||
// worker until ctx ends and returns a channel that
|
||||
// closes when all of them have stopped. The workers stop together with the
|
||||
// servers; none of them depends on another.
|
||||
func (application *Application) startWorkers(ctx context.Context) <-chan struct{} {
|
||||
@@ -246,6 +256,9 @@ func (application *Application) startWorkers(ctx context.Context) <-chan struct{
|
||||
if application.deliveryMetrics != nil {
|
||||
workers.Go(func() { application.deliveryMetrics.Run(ctx) })
|
||||
}
|
||||
if application.practiceQueue != nil {
|
||||
workers.Go(func() { application.practiceQueue.Run(ctx) })
|
||||
}
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
defer close(stopped)
|
||||
|
||||
@@ -10,31 +10,54 @@ import (
|
||||
"lincodex/backend/config"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
redisadapter "lincodex/backend/internal/adapter/secondary/redis"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
"lincodex/backend/internal/usecase/practice"
|
||||
"lincodex/backend/internal/worker/practicequeue"
|
||||
"lincodex/backend/internal/worker/retry"
|
||||
)
|
||||
|
||||
// practicePoolMaxConns covers concurrent debug run requests; each holds one
|
||||
// short transaction.
|
||||
const practicePoolMaxConns = 4
|
||||
const (
|
||||
// practicePoolMaxConns covers concurrent debug run requests; each holds
|
||||
// one short transaction.
|
||||
practicePoolMaxConns = 4
|
||||
// practiceQueuePoolMaxConns covers the one job in progress and its
|
||||
// claim: every store call is one short transaction.
|
||||
practiceQueuePoolMaxConns = 2
|
||||
// practiceRunTimeout bounds how long a run may stay unfinished on the
|
||||
// runner. The runner bounds one run by its CPU budget of 300 s plus the
|
||||
// compile phase and the queue of its own slots, so this is far above a
|
||||
// healthy run.
|
||||
practiceRunTimeout = 10 * time.Minute
|
||||
// A failed try waits 2 s, doubling up to a minute, so a short runner
|
||||
// outage costs few attempts.
|
||||
practiceBackoffInitial = 2 * time.Second
|
||||
practiceBackoffMax = time.Minute
|
||||
// practiceStoreTimeout bounds one write of the job state; each is one
|
||||
// short transaction.
|
||||
practiceStoreTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
// newPracticeHandler builds the debug run operations of code practice and the
|
||||
// PostgreSQL pool they own. Nothing connects here. It returns no handler when
|
||||
// DATABASE_URL is unset, and the operations then answer 501. Without a code
|
||||
// runner (CODE_RUNNER_URL unset) the operations answer 503 and store nothing.
|
||||
// The application clock is time.Now.
|
||||
// The rate limit of debug runs uses the Redis limiter. The application clock
|
||||
// is time.Now.
|
||||
func newPracticeHandler(
|
||||
ctx context.Context,
|
||||
settings config.Config,
|
||||
logger *slog.Logger,
|
||||
keyring *identity.Keyring,
|
||||
cache *redisadapter.Cache,
|
||||
) (*v1.PracticeHandler, func(), error) {
|
||||
if settings.DatabaseURL == "" {
|
||||
logger.Warn("code practice operations are not served because DATABASE_URL is not set")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
if keyring == nil {
|
||||
return nil, nil, errors.New("bootstrap.newPracticeHandler - identity keyring must be set")
|
||||
if keyring == nil || cache == nil {
|
||||
return nil, nil, errors.New("bootstrap.newPracticeHandler - identity keyring and Redis cache must be set")
|
||||
}
|
||||
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, practicePoolMaxConns)
|
||||
if err != nil {
|
||||
@@ -45,5 +68,62 @@ func newPracticeHandler(
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPracticeHandler - create service: %w", err)
|
||||
}
|
||||
service.WithRunRateLimit(cache,
|
||||
outbound.RateLimitRule{Window: time.Minute, Limit: settings.Practice.RunsPerMinute},
|
||||
outbound.RateLimitRule{Window: time.Hour, Limit: settings.Practice.RunsPerHour},
|
||||
)
|
||||
return v1.NewPracticeHandler(service), pool.Close, nil
|
||||
}
|
||||
|
||||
// newPracticeQueueWorker builds the worker that runs practice jobs on the code
|
||||
// runner and the PostgreSQL pool it owns. Nothing connects here, so an
|
||||
// unavailable database or runner never blocks startup. It returns no worker
|
||||
// without a code runner or without DATABASE_URL: queued jobs then wait in the
|
||||
// database. The application clock is time.Now.
|
||||
func newPracticeQueueWorker(
|
||||
ctx context.Context,
|
||||
settings config.Config,
|
||||
logger *slog.Logger,
|
||||
runner outbound.CodeRunner,
|
||||
) (*practicequeue.Worker, func(), error) {
|
||||
switch {
|
||||
case !settings.CodeRunner.Enabled():
|
||||
logger.Info("practice queue worker is off because the code runner is disabled")
|
||||
return nil, func() {}, nil
|
||||
case settings.DatabaseURL == "":
|
||||
logger.Warn("practice queue worker skipped because DATABASE_URL is not set")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, practiceQueuePoolMaxConns)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPracticeQueueWorker - create pool: %w", err)
|
||||
}
|
||||
store := postgres.NewPracticeJobStore(pool)
|
||||
workerLogger := logger.With(slog.String("component", "practice_queue"))
|
||||
executor, err := practice.NewExecutor(runner, store, time.Now, practice.ExecutionSettings{
|
||||
PollInterval: settings.Practice.PollInterval,
|
||||
Lease: settings.Practice.JobLease,
|
||||
RunTimeout: practiceRunTimeout,
|
||||
MaxAttempts: settings.Practice.JobMaxAttempts,
|
||||
BackoffInitial: practiceBackoffInitial,
|
||||
BackoffMax: practiceBackoffMax,
|
||||
StoreTimeout: practiceStoreTimeout,
|
||||
}, workerLogger)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPracticeQueueWorker - create executor: %w", err)
|
||||
}
|
||||
worker, err := practicequeue.New(store, executor, workerLogger, practicequeue.Settings{
|
||||
PollInterval: settings.Practice.PollInterval,
|
||||
Lease: settings.Practice.JobLease,
|
||||
StoreTimeout: practiceStoreTimeout,
|
||||
Backoff: retry.Backoff{Initial: practiceBackoffInitial, Max: practiceBackoffMax},
|
||||
}, time.Now)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPracticeQueueWorker - create worker: %w", err)
|
||||
}
|
||||
// The application stops the worker before this cleanup runs, so no job
|
||||
// uses the pool while it closes.
|
||||
return worker, pool.Close, nil
|
||||
}
|
||||
@@ -184,7 +184,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
practiceHandler, cleanup15, err := newPracticeHandler(ctx, config2, logger, keyring)
|
||||
practiceHandler, cleanup15, err := newPracticeHandler(ctx, config2, logger, keyring, cache)
|
||||
if err != nil {
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
|
||||
@@ -74,8 +74,16 @@ type AssessmentPracticeRepository interface {
|
||||
FindByScope(ctx context.Context, userID uuid.UUID, scope [IdempotencyDigestSize]byte) (PracticeSubmissionReplay, bool, error)
|
||||
// LatestFinal returns the latest final submission of a practice, if any.
|
||||
LatestFinal(ctx context.Context, practiceID uuid.UUID) (PracticeFinalSolution, bool, error)
|
||||
// LockQueue takes the transaction-scoped lock of the practice queue and
|
||||
// returns the number of queued and running jobs. Admission and the claim
|
||||
// of the worker take the same lock, so a count and the insert that
|
||||
// depends on it are atomic. Take it after the attempt and practice locks.
|
||||
LockQueue(ctx context.Context) (active int, err error)
|
||||
// ActiveRuns counts the queued and running debug runs of a practice.
|
||||
ActiveRuns(ctx context.Context, practiceID uuid.UUID) (int, error)
|
||||
// Submit stores a submission under the idempotency scope and queues its
|
||||
// execution job in the same transaction.
|
||||
// execution job in the same transaction. The caller holds the queue lock
|
||||
// and has checked its limits.
|
||||
Submit(ctx context.Context, submission domain.PracticeSubmission, scope [IdempotencyDigestSize]byte) error
|
||||
// GetRun reads a debug run of the owner's attempt with the state of its
|
||||
// job. It never returns a final submission; an unknown, foreign, or final
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
// ErrPracticeResultExists reports a completion of a submission that already
|
||||
// has a result. Nothing was written.
|
||||
var ErrPracticeResultExists = errors.New("practice submission already has a result")
|
||||
|
||||
// PracticeJobErrorClass is the bounded cause of a failed or abandoned try of
|
||||
// a practice job. It never carries runner or candidate text.
|
||||
type PracticeJobErrorClass string
|
||||
|
||||
const (
|
||||
// PracticeJobRunnerUnavailable: the runner could not be reached, refused
|
||||
// the token, or answered outside its contract; the try is repeated with
|
||||
// the same run key.
|
||||
PracticeJobRunnerUnavailable PracticeJobErrorClass = "runner_unavailable"
|
||||
// PracticeJobInfrastructureFailure: the runner could not evaluate the
|
||||
// source; the next try uses a new generation.
|
||||
PracticeJobInfrastructureFailure PracticeJobErrorClass = "runner_infrastructure_failure"
|
||||
// PracticeJobInvalidRequest: the stored task or submission cannot form a
|
||||
// valid runner request, a content bug; the job fails at once.
|
||||
PracticeJobInvalidRequest PracticeJobErrorClass = "invalid_request"
|
||||
// PracticeJobRunTimeout: the run stayed unfinished on the runner longer
|
||||
// than the run timeout.
|
||||
PracticeJobRunTimeout PracticeJobErrorClass = "run_timeout"
|
||||
// PracticeJobLeaseExpired: the worker of the try stopped without
|
||||
// finishing it, and another claim took the job over.
|
||||
PracticeJobLeaseExpired PracticeJobErrorClass = "lease_expired"
|
||||
)
|
||||
|
||||
// PracticeJobClaim asks for the next practice job. Now is the application
|
||||
// clock; the database clock never decides whether a lease expired.
|
||||
type PracticeJobClaim struct {
|
||||
Owner uuid.UUID
|
||||
Now time.Time
|
||||
Lease time.Duration
|
||||
// MaxRunning bounds the running jobs whose leases have not expired.
|
||||
MaxRunning int
|
||||
}
|
||||
|
||||
// ClaimedPracticeJob is one running try of a practice job. The owner and the
|
||||
// start time identify the try: every change of the job checks both, so a
|
||||
// worker whose job was taken over changes nothing.
|
||||
type ClaimedPracticeJob struct {
|
||||
SubmissionID uuid.UUID
|
||||
Mode domain.PracticeSubmissionMode
|
||||
Generation uint32
|
||||
Attempts int
|
||||
LeaseOwner uuid.UUID
|
||||
LeaseExpiresAt time.Time
|
||||
StartedAt time.Time
|
||||
// Reclaimed reports that the previous try's lease expired and this
|
||||
// claim took the job over.
|
||||
Reclaimed bool
|
||||
}
|
||||
|
||||
// PracticeJobWork is what a claimed job runs.
|
||||
type PracticeJobWork struct {
|
||||
Submission domain.PracticeSubmission
|
||||
Task domain.PracticeTask
|
||||
}
|
||||
|
||||
// PracticeRequeue puts a running try back into the queue.
|
||||
type PracticeRequeue struct {
|
||||
AvailableAt time.Time
|
||||
Generation uint32
|
||||
// Counted adds the try to the attempts of the job; a busy runner and a
|
||||
// shutdown do not count.
|
||||
Counted bool
|
||||
ErrorClass PracticeJobErrorClass
|
||||
}
|
||||
|
||||
// PracticeJobStore keeps the practice queue for the worker. Each method is
|
||||
// one short transaction; no transaction stays open while the runner works.
|
||||
type PracticeJobStore interface {
|
||||
// Claim takes the next job under the queue lock when fewer than
|
||||
// MaxRunning jobs hold a live lease: a running job whose lease expired
|
||||
// first, then the next queued job that is available, final submissions
|
||||
// before debug runs. claimed is false when there is nothing to run.
|
||||
Claim(ctx context.Context, claim PracticeJobClaim) (job ClaimedPracticeJob, claimed bool, err error)
|
||||
// Work reads the submission and the task of a claimed job. Stored
|
||||
// content that fails validation returns an error wrapping
|
||||
// domain.ErrInvalidAssessmentPractice.
|
||||
Work(ctx context.Context, job ClaimedPracticeJob) (PracticeJobWork, error)
|
||||
// Extend renews the lease of a try until expiresAt. held is false when
|
||||
// the job no longer belongs to the try.
|
||||
Extend(ctx context.Context, job ClaimedPracticeJob, expiresAt time.Time) (renewed ClaimedPracticeJob, held bool, err error)
|
||||
// Requeue puts a try back into the queue; held is false when the job no
|
||||
// longer belongs to the try.
|
||||
Requeue(ctx context.Context, job ClaimedPracticeJob, requeue PracticeRequeue) (held bool, err error)
|
||||
// Complete stores the result of the submission once, finishes the job,
|
||||
// and, for the latest final submission of a pending practice, finishes
|
||||
// the practice, all in one transaction. held is false, with nothing
|
||||
// written, when the job no longer belongs to the try.
|
||||
Complete(ctx context.Context, job ClaimedPracticeJob, result domain.PracticeRunResult) (held bool, err error)
|
||||
// Fail ends the job as failed with the error class and, for the latest
|
||||
// final submission of a pending practice, marks the practice failed with
|
||||
// sandbox_error. It never stores a verdict.
|
||||
Fail(ctx context.Context, job ClaimedPracticeJob, class PracticeJobErrorClass) (held bool, err error)
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
package practice
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// ExecutionOutcome is how one try of a practice job ended. Every claimed job
|
||||
// ends a try with exactly one.
|
||||
type ExecutionOutcome string
|
||||
|
||||
const (
|
||||
// OutcomeFinished: the result is stored, once.
|
||||
OutcomeFinished ExecutionOutcome = "finished"
|
||||
// OutcomeFailed: the infrastructure gave up on the job; nothing was
|
||||
// graded and a final practice can be submitted again.
|
||||
OutcomeFailed ExecutionOutcome = "failed"
|
||||
// OutcomeBusy: the runner had no free slot; the job waits for the time
|
||||
// the runner asked for, and the try does not count.
|
||||
OutcomeBusy ExecutionOutcome = "busy"
|
||||
// OutcomeRetry: the try failed in the infrastructure and the job waits
|
||||
// for its backoff.
|
||||
OutcomeRetry ExecutionOutcome = "retry"
|
||||
// OutcomeLeaseLost: another worker took the job over; this try wrote
|
||||
// nothing.
|
||||
OutcomeLeaseLost ExecutionOutcome = "lease_lost"
|
||||
// OutcomeReleased: the worker stopped and gave the job back unfinished
|
||||
// without counting the try.
|
||||
OutcomeReleased ExecutionOutcome = "released"
|
||||
)
|
||||
|
||||
// Bounds of the wait that a busy runner asks for.
|
||||
const (
|
||||
minBusyWait = time.Second
|
||||
maxBusyWait = time.Minute
|
||||
)
|
||||
|
||||
// ExecutionSettings are the limits of one try; config validates their
|
||||
// ranges.
|
||||
type ExecutionSettings struct {
|
||||
// PollInterval is the wait between two reads of a running run.
|
||||
PollInterval time.Duration
|
||||
// Lease is how long a try holds its job; each poll renews it.
|
||||
Lease time.Duration
|
||||
// RunTimeout bounds how long a run may stay unfinished on the runner
|
||||
// before the try counts as failed.
|
||||
RunTimeout time.Duration
|
||||
// MaxAttempts bounds the failed tries and expired leases of a job before
|
||||
// it fails.
|
||||
MaxAttempts int
|
||||
// BackoffInitial is the wait after the first failed try; it doubles up
|
||||
// to BackoffMax.
|
||||
BackoffInitial time.Duration
|
||||
BackoffMax time.Duration
|
||||
// StoreTimeout bounds one write of the job state.
|
||||
StoreTimeout time.Duration
|
||||
}
|
||||
|
||||
func (settings ExecutionSettings) validate() error {
|
||||
if settings.PollInterval <= 0 || settings.Lease <= settings.PollInterval || settings.RunTimeout <= 0 ||
|
||||
settings.MaxAttempts < 1 || settings.BackoffInitial <= 0 || settings.BackoffMax < settings.BackoffInitial ||
|
||||
settings.StoreTimeout <= 0 {
|
||||
return errors.New("practice.NewExecutor - intervals must be positive, the lease longer than a poll, and attempts at least one")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Executor runs one claimed practice job on the code runner: it submits the
|
||||
// run, polls it while renewing the lease, and stores the result once. An
|
||||
// infrastructure failure is retried and never becomes a verdict; a runner
|
||||
// that could not evaluate the source gets a new generation of the run key.
|
||||
type Executor struct {
|
||||
runner outbound.CodeRunner
|
||||
store outbound.PracticeJobStore
|
||||
clock func() time.Time
|
||||
settings ExecutionSettings
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func NewExecutor(
|
||||
runner outbound.CodeRunner,
|
||||
store outbound.PracticeJobStore,
|
||||
clock func() time.Time,
|
||||
settings ExecutionSettings,
|
||||
logger *slog.Logger,
|
||||
) (*Executor, error) {
|
||||
if runner == nil || store == nil || clock == nil || logger == nil {
|
||||
return nil, errors.New("practice.NewExecutor - runner, store, clock, and logger are required")
|
||||
}
|
||||
if err := settings.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Executor{runner: runner, store: store, clock: clock, settings: settings, logger: logger}, nil
|
||||
}
|
||||
|
||||
// Execute runs one try of a claimed job until the job is finished, failed,
|
||||
// back in the queue, or taken over. The error reports a database failure; the
|
||||
// job is then released or waits for its lease to expire.
|
||||
func (executor *Executor) Execute(ctx context.Context, job outbound.ClaimedPracticeJob) (ExecutionOutcome, error) {
|
||||
if job.Attempts >= executor.settings.MaxAttempts {
|
||||
return executor.fail(ctx, job, outbound.PracticeJobLeaseExpired)
|
||||
}
|
||||
work, err := executor.store.Work(ctx, job)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrInvalidAssessmentPractice):
|
||||
return executor.fail(ctx, job, outbound.PracticeJobInvalidRequest)
|
||||
case err != nil:
|
||||
return executor.release(ctx, job, fmt.Errorf("Executor.Execute - read work: %w", err))
|
||||
}
|
||||
request, err := RunRequest(work.Task, work.Submission, job.Generation)
|
||||
if err != nil {
|
||||
return executor.fail(ctx, job, outbound.PracticeJobInvalidRequest)
|
||||
}
|
||||
status, err := executor.runner.Submit(ctx, request)
|
||||
for {
|
||||
if err != nil {
|
||||
return executor.runnerFailure(ctx, job, err)
|
||||
}
|
||||
switch status.State {
|
||||
case outbound.CodeRunBusy:
|
||||
return executor.requeueBusy(ctx, job, status.RetryAfter)
|
||||
case outbound.CodeRunFinished:
|
||||
return executor.complete(ctx, job, status)
|
||||
case outbound.CodeRunRunning:
|
||||
default:
|
||||
return executor.runnerFailure(ctx, job, outbound.ErrCodeRunnerBadResponse)
|
||||
}
|
||||
if executor.clock().Sub(job.StartedAt) >= executor.settings.RunTimeout {
|
||||
return executor.retry(ctx, job, job.Generation, outbound.PracticeJobRunTimeout)
|
||||
}
|
||||
if !waitFor(ctx, executor.settings.PollInterval) {
|
||||
return executor.release(ctx, job, nil)
|
||||
}
|
||||
renewed, held, extendErr := executor.store.Extend(ctx, job, executor.clock().Add(executor.settings.Lease))
|
||||
switch {
|
||||
case extendErr != nil:
|
||||
return executor.release(ctx, job, fmt.Errorf("Executor.Execute - renew lease: %w", extendErr))
|
||||
case !held:
|
||||
return OutcomeLeaseLost, nil
|
||||
}
|
||||
job = renewed
|
||||
status, err = executor.runner.Poll(ctx, request)
|
||||
if errors.Is(err, outbound.ErrCodeRunNotFound) {
|
||||
// The runner lost the run in a restart or after its retention;
|
||||
// the same key starts it again.
|
||||
status, err = executor.runner.Submit(ctx, request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// runnerFailure decides on a runner error. None of them is a verdict.
|
||||
func (executor *Executor) runnerFailure(ctx context.Context, job outbound.ClaimedPracticeJob, err error) (ExecutionOutcome, error) {
|
||||
switch {
|
||||
case ctx.Err() != nil:
|
||||
return executor.release(ctx, job, nil)
|
||||
case errors.Is(err, outbound.ErrInvalidCodeRunRequest):
|
||||
return executor.fail(ctx, job, outbound.PracticeJobInvalidRequest)
|
||||
case errors.Is(err, outbound.ErrCodeRunnerInfrastructureFailure), errors.Is(err, outbound.ErrCodeRunKeyReused):
|
||||
// The runner keeps its stored failure, or another payload, under the
|
||||
// old run ID, so the next try needs a new one.
|
||||
return executor.retry(ctx, job, job.Generation+1, outbound.PracticeJobInfrastructureFailure)
|
||||
default:
|
||||
// The run may exist on the runner; the same key finds it again.
|
||||
return executor.retry(ctx, job, job.Generation, outbound.PracticeJobRunnerUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
func (executor *Executor) complete(ctx context.Context, job outbound.ClaimedPracticeJob, status outbound.CodeRunStatus) (ExecutionOutcome, error) {
|
||||
if status.Result == nil {
|
||||
return executor.runnerFailure(ctx, job, outbound.ErrCodeRunnerBadResponse)
|
||||
}
|
||||
storeCtx, cancel := executor.storeContext(ctx)
|
||||
defer cancel()
|
||||
held, err := executor.store.Complete(storeCtx, job, runResult(*status.Result))
|
||||
switch {
|
||||
case err != nil:
|
||||
return "", fmt.Errorf("Executor.complete - store result: %w", err)
|
||||
case !held:
|
||||
return OutcomeLeaseLost, nil
|
||||
}
|
||||
executor.logger.Info("practice job finished", jobAttributes(job, slog.String("outcome", string(status.Result.Outcome)))...)
|
||||
return OutcomeFinished, nil
|
||||
}
|
||||
|
||||
func (executor *Executor) requeueBusy(ctx context.Context, job outbound.ClaimedPracticeJob, retryAfter time.Duration) (ExecutionOutcome, error) {
|
||||
wait := min(max(retryAfter, minBusyWait), maxBusyWait)
|
||||
return executor.requeue(ctx, job, outbound.PracticeRequeue{
|
||||
AvailableAt: executor.clock().Add(wait), Generation: job.Generation,
|
||||
}, OutcomeBusy)
|
||||
}
|
||||
|
||||
// retry counts a failed try: the job waits for its backoff, or fails once
|
||||
// the attempts ran out.
|
||||
func (executor *Executor) retry(
|
||||
ctx context.Context,
|
||||
job outbound.ClaimedPracticeJob,
|
||||
generation uint32,
|
||||
class outbound.PracticeJobErrorClass,
|
||||
) (ExecutionOutcome, error) {
|
||||
attempts := job.Attempts + 1
|
||||
if attempts >= executor.settings.MaxAttempts {
|
||||
return executor.fail(ctx, job, class)
|
||||
}
|
||||
executor.logger.Warn("practice job try failed in the infrastructure; retrying",
|
||||
jobAttributes(job, slog.String("error_class", string(class)))...)
|
||||
return executor.requeue(ctx, job, outbound.PracticeRequeue{
|
||||
AvailableAt: executor.clock().Add(executor.backoff(attempts)), Generation: generation, Counted: true, ErrorClass: class,
|
||||
}, OutcomeRetry)
|
||||
}
|
||||
|
||||
func (executor *Executor) requeue(
|
||||
ctx context.Context,
|
||||
job outbound.ClaimedPracticeJob,
|
||||
requeue outbound.PracticeRequeue,
|
||||
outcome ExecutionOutcome,
|
||||
) (ExecutionOutcome, error) {
|
||||
storeCtx, cancel := executor.storeContext(ctx)
|
||||
defer cancel()
|
||||
held, err := executor.store.Requeue(storeCtx, job, requeue)
|
||||
switch {
|
||||
case err != nil:
|
||||
return "", fmt.Errorf("Executor.requeue - requeue job: %w", err)
|
||||
case !held:
|
||||
return OutcomeLeaseLost, nil
|
||||
}
|
||||
return outcome, nil
|
||||
}
|
||||
|
||||
// fail ends the job without a verdict; a final practice becomes failed with
|
||||
// sandbox_error and accepts a solution again.
|
||||
func (executor *Executor) fail(ctx context.Context, job outbound.ClaimedPracticeJob, class outbound.PracticeJobErrorClass) (ExecutionOutcome, error) {
|
||||
storeCtx, cancel := executor.storeContext(ctx)
|
||||
defer cancel()
|
||||
held, err := executor.store.Fail(storeCtx, job, class)
|
||||
switch {
|
||||
case err != nil:
|
||||
return "", fmt.Errorf("Executor.fail - fail job: %w", err)
|
||||
case !held:
|
||||
return OutcomeLeaseLost, nil
|
||||
}
|
||||
executor.logger.Error("practice job failed in the infrastructure; nothing was graded",
|
||||
jobAttributes(job, slog.String("error_class", string(class)))...)
|
||||
return OutcomeFailed, nil
|
||||
}
|
||||
|
||||
// release gives the job back at once without counting the try, at shutdown
|
||||
// or after a database failure. A failed release leaves the job to its lease.
|
||||
func (executor *Executor) release(ctx context.Context, job outbound.ClaimedPracticeJob, cause error) (ExecutionOutcome, error) {
|
||||
outcome, err := executor.requeue(ctx, job, outbound.PracticeRequeue{AvailableAt: executor.clock(), Generation: job.Generation}, OutcomeReleased)
|
||||
if cause != nil {
|
||||
return outcome, errors.Join(cause, err)
|
||||
}
|
||||
return outcome, err
|
||||
}
|
||||
|
||||
// storeContext lets a write of the job state finish after shutdown began, so
|
||||
// a result or a failure is not lost to a restart.
|
||||
func (executor *Executor) storeContext(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(context.WithoutCancel(ctx), executor.settings.StoreTimeout)
|
||||
}
|
||||
|
||||
func (executor *Executor) backoff(attempts int) time.Duration {
|
||||
delay := executor.settings.BackoffInitial
|
||||
for range attempts - 1 {
|
||||
if delay >= executor.settings.BackoffMax/2 {
|
||||
return executor.settings.BackoffMax
|
||||
}
|
||||
delay *= 2
|
||||
}
|
||||
return min(delay, executor.settings.BackoffMax)
|
||||
}
|
||||
|
||||
// runResult keeps what the stored result needs: per-test details of public
|
||||
// groups only. A hidden group keeps its outcome and counts.
|
||||
func runResult(result outbound.CodeRunResult) domain.PracticeRunResult {
|
||||
stored := domain.PracticeRunResult{
|
||||
Outcome: domain.PracticeOutcome(result.Outcome), DurationMs: result.Duration.Milliseconds(),
|
||||
Groups: make([]domain.PracticeGroupOutcome, 0, len(result.Groups)),
|
||||
}
|
||||
if result.Compile != nil && result.Outcome == outbound.CodeOutcomeCompileError {
|
||||
stored.CompileDiagnostic = result.Compile.Diagnostic
|
||||
}
|
||||
for _, group := range result.Groups {
|
||||
outcome := domain.PracticeGroupOutcome{
|
||||
ID: group.ID, Hidden: group.Visibility == outbound.CodeTestHidden, Outcome: domain.PracticeOutcome(group.Outcome),
|
||||
PassedTests: group.PassedTests, TotalTests: group.TotalTests,
|
||||
}
|
||||
if !outcome.Hidden {
|
||||
for _, test := range group.Tests {
|
||||
outcome.Tests = append(outcome.Tests, domain.PracticeTestOutcome{
|
||||
ID: test.ID, Outcome: domain.PracticeOutcome(test.Outcome), TimeMs: test.TimeMs,
|
||||
MemoryKB: test.MemoryKB, Diagnostic: test.Diagnostic,
|
||||
})
|
||||
}
|
||||
}
|
||||
stored.Groups = append(stored.Groups, outcome)
|
||||
}
|
||||
return stored
|
||||
}
|
||||
|
||||
// jobAttributes identify a try in logs without the source, tests, or owner.
|
||||
func jobAttributes(job outbound.ClaimedPracticeJob, extra ...any) []any {
|
||||
return append([]any{
|
||||
slog.String("submission_id", job.SubmissionID.String()),
|
||||
slog.String("mode", string(job.Mode)),
|
||||
slog.Int("generation", int(job.Generation)),
|
||||
slog.Int("attempts", job.Attempts),
|
||||
}, extra...)
|
||||
}
|
||||
|
||||
// waitFor waits for the delay and reports false when ctx ended first.
|
||||
func waitFor(ctx context.Context, delay time.Duration) bool {
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-timer.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package practice
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestExecutorNeverTurnsAnInfrastructureFailureIntoAVerdict(t *testing.T) {
|
||||
now := time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC)
|
||||
cases := []struct {
|
||||
name string
|
||||
submitErr error
|
||||
attempts int
|
||||
wantOutcome ExecutionOutcome
|
||||
wantGeneration uint32
|
||||
wantFailed outbound.PracticeJobErrorClass
|
||||
}{
|
||||
{name: "unreachable runner keeps the run key", submitErr: outbound.ErrCodeRunnerBadResponse,
|
||||
wantOutcome: OutcomeRetry, wantGeneration: 2},
|
||||
{name: "infrastructure failure starts a new run", submitErr: outbound.ErrCodeRunnerInfrastructureFailure,
|
||||
wantOutcome: OutcomeRetry, wantGeneration: 3},
|
||||
{name: "reused key starts a new run", submitErr: outbound.ErrCodeRunKeyReused,
|
||||
wantOutcome: OutcomeRetry, wantGeneration: 3},
|
||||
{name: "invalid request fails without a verdict", submitErr: outbound.ErrInvalidCodeRunRequest,
|
||||
wantOutcome: OutcomeFailed, wantFailed: outbound.PracticeJobInvalidRequest},
|
||||
{name: "last attempt fails without a verdict", submitErr: outbound.ErrCodeRunnerUnavailable, attempts: 2,
|
||||
wantOutcome: OutcomeFailed, wantFailed: outbound.PracticeJobRunnerUnavailable},
|
||||
{name: "exhausted takeover fails at once", attempts: 3,
|
||||
wantOutcome: OutcomeFailed, wantFailed: outbound.PracticeJobLeaseExpired},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
store := &fakeJobStore{}
|
||||
runner := &fakeRunner{submitErr: testCase.submitErr}
|
||||
executor := testExecutor(t, runner, store, now)
|
||||
job := outbound.ClaimedPracticeJob{SubmissionID: uuid.New(), Generation: 2, Attempts: testCase.attempts, StartedAt: now}
|
||||
outcome, err := executor.Execute(t.Context(), job)
|
||||
if err != nil || outcome != testCase.wantOutcome {
|
||||
t.Fatalf("Execute() = %q, error %v; want %q", outcome, err, testCase.wantOutcome)
|
||||
}
|
||||
if store.completed {
|
||||
t.Fatal("an infrastructure failure stored a result")
|
||||
}
|
||||
if testCase.wantFailed != "" && store.failedWith != testCase.wantFailed {
|
||||
t.Fatalf("failed with %q, want %q", store.failedWith, testCase.wantFailed)
|
||||
}
|
||||
if testCase.wantOutcome == OutcomeRetry {
|
||||
if !store.requeue.Counted || store.requeue.Generation != testCase.wantGeneration ||
|
||||
!store.requeue.AvailableAt.Equal(now.Add(time.Second)) {
|
||||
t.Fatalf("requeue = %+v, want a counted try at generation %d after the first backoff", store.requeue, testCase.wantGeneration)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorHandlesPollFailuresAndShutdown(t *testing.T) {
|
||||
now := time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC)
|
||||
store := &fakeJobStore{}
|
||||
runner := &fakeRunner{pollErr: outbound.ErrCodeRunNotFound, submits: []outbound.CodeRunState{outbound.CodeRunRunning, outbound.CodeRunFinished}}
|
||||
executor := testExecutor(t, runner, store, now)
|
||||
job := outbound.ClaimedPracticeJob{SubmissionID: uuid.New(), StartedAt: now}
|
||||
if outcome, err := executor.Execute(t.Context(), job); err != nil || outcome != OutcomeFinished || !store.completed {
|
||||
t.Fatalf("Execute() = %q, error %v, completed %v; want the resubmitted run finished", outcome, err, store.completed)
|
||||
}
|
||||
if runner.submitCalls != 2 || runner.pollCalls != 1 {
|
||||
t.Fatalf("submits = %d, polls = %d; want a resubmit after the lost run", runner.submitCalls, runner.pollCalls)
|
||||
}
|
||||
|
||||
store = &fakeJobStore{}
|
||||
runner = &fakeRunner{pollErr: outbound.ErrCodeRunnerInfrastructureFailure, submits: []outbound.CodeRunState{outbound.CodeRunRunning}}
|
||||
executor = testExecutor(t, runner, store, now)
|
||||
if outcome, err := executor.Execute(t.Context(), job); err != nil || outcome != OutcomeRetry || store.requeue.Generation != job.Generation+1 {
|
||||
t.Fatalf("Execute() after a failed poll = %q, error %v, requeue %+v; want a retry on a new generation", outcome, err, store.requeue)
|
||||
}
|
||||
|
||||
store = &fakeJobStore{}
|
||||
runner = &fakeRunner{submits: []outbound.CodeRunState{outbound.CodeRunRunning}}
|
||||
executor = testExecutor(t, runner, store, now)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if outcome, err := executor.Execute(ctx, job); err != nil || outcome != OutcomeReleased {
|
||||
t.Fatalf("Execute() at shutdown = %q, error %v; want released", outcome, err)
|
||||
}
|
||||
if store.requeue.Counted || store.requeue.Generation != job.Generation {
|
||||
t.Fatalf("release = %+v, want an uncounted requeue on the same key", store.requeue)
|
||||
}
|
||||
}
|
||||
|
||||
func testExecutor(t *testing.T, runner outbound.CodeRunner, store outbound.PracticeJobStore, now time.Time) *Executor {
|
||||
t.Helper()
|
||||
executor, err := NewExecutor(runner, store, func() time.Time { return now }, ExecutionSettings{
|
||||
PollInterval: time.Millisecond, Lease: time.Minute, RunTimeout: time.Hour, MaxAttempts: 3,
|
||||
BackoffInitial: time.Second, BackoffMax: 4 * time.Second, StoreTimeout: time.Second,
|
||||
}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("NewExecutor() error = %v", err)
|
||||
}
|
||||
return executor
|
||||
}
|
||||
|
||||
type fakeRunner struct {
|
||||
submitErr error
|
||||
pollErr error
|
||||
submits []outbound.CodeRunState
|
||||
submitCalls int
|
||||
pollCalls int
|
||||
}
|
||||
|
||||
func (runner *fakeRunner) Submit(_ context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) {
|
||||
runner.submitCalls++
|
||||
if runner.submitErr != nil {
|
||||
return outbound.CodeRunStatus{}, runner.submitErr
|
||||
}
|
||||
state := runner.submits[min(runner.submitCalls, len(runner.submits))-1]
|
||||
return fakeStatus(state, request), nil
|
||||
}
|
||||
|
||||
func (runner *fakeRunner) Poll(_ context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) {
|
||||
runner.pollCalls++
|
||||
if runner.pollErr != nil {
|
||||
return outbound.CodeRunStatus{}, runner.pollErr
|
||||
}
|
||||
return fakeStatus(outbound.CodeRunFinished, request), nil
|
||||
}
|
||||
|
||||
func fakeStatus(state outbound.CodeRunState, request outbound.CodeRunRequest) outbound.CodeRunStatus {
|
||||
if state != outbound.CodeRunFinished {
|
||||
return outbound.CodeRunStatus{State: state}
|
||||
}
|
||||
result := outbound.CodeRunResult{Outcome: outbound.CodeOutcomeAccepted}
|
||||
for _, group := range request.Groups {
|
||||
result.Groups = append(result.Groups, outbound.CodeGroupResult{
|
||||
ID: group.ID, Visibility: group.Visibility, Outcome: outbound.CodeOutcomeAccepted,
|
||||
PassedTests: len(group.Tests), TotalTests: len(group.Tests),
|
||||
})
|
||||
}
|
||||
return outbound.CodeRunStatus{State: state, Result: &result}
|
||||
}
|
||||
|
||||
type fakeJobStore struct {
|
||||
requeue outbound.PracticeRequeue
|
||||
failedWith outbound.PracticeJobErrorClass
|
||||
completed bool
|
||||
}
|
||||
|
||||
func (store *fakeJobStore) Claim(context.Context, outbound.PracticeJobClaim) (outbound.ClaimedPracticeJob, bool, error) {
|
||||
return outbound.ClaimedPracticeJob{}, false, errors.New("not used")
|
||||
}
|
||||
|
||||
func (store *fakeJobStore) Work(_ context.Context, job outbound.ClaimedPracticeJob) (outbound.PracticeJobWork, error) {
|
||||
return outbound.PracticeJobWork{Task: testTask(), Submission: domain.PracticeSubmission{
|
||||
ID: job.SubmissionID, PracticeID: uuid.New(), UserID: uuid.New(), Mode: domain.PracticeModeFinal,
|
||||
Language: domain.TaskLanguagePython, Source: "print(1)\n", CreatedAt: time.Now(),
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func (store *fakeJobStore) Extend(_ context.Context, job outbound.ClaimedPracticeJob, expiresAt time.Time) (outbound.ClaimedPracticeJob, bool, error) {
|
||||
job.LeaseExpiresAt = expiresAt
|
||||
return job, true, nil
|
||||
}
|
||||
|
||||
func (store *fakeJobStore) Requeue(_ context.Context, _ outbound.ClaimedPracticeJob, requeue outbound.PracticeRequeue) (bool, error) {
|
||||
store.requeue = requeue
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (store *fakeJobStore) Complete(context.Context, outbound.ClaimedPracticeJob, domain.PracticeRunResult) (bool, error) {
|
||||
store.completed = true
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (store *fakeJobStore) Fail(_ context.Context, _ outbound.ClaimedPracticeJob, class outbound.PracticeJobErrorClass) (bool, error) {
|
||||
store.failedWith = class
|
||||
return true, nil
|
||||
}
|
||||
@@ -6,6 +6,7 @@ package practice
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -25,6 +26,29 @@ const (
|
||||
maxIdempotencyKeyBytes = 255
|
||||
)
|
||||
|
||||
// Limits of the practice queue. The runner runs one program at a time, so one
|
||||
// job runs and ten wait; a command beyond them is answered busy and stores
|
||||
// nothing.
|
||||
const (
|
||||
MaxRunningJobs = 1
|
||||
MaxQueuedJobs = 10
|
||||
// queueCapacity counts the running and the queued jobs together, as
|
||||
// admission sees them: a job counts until it is finished.
|
||||
queueCapacity = MaxRunningJobs + MaxQueuedJobs
|
||||
// queueBusyRetryAfter is the wait a full queue announces. Runs take
|
||||
// seconds, so a slot frees up within it most of the time.
|
||||
queueBusyRetryAfter = 10 * time.Second
|
||||
// activeRunRetryAfter is the wait announced while the previous debug run
|
||||
// of the practice is unfinished.
|
||||
activeRunRetryAfter = 2 * time.Second
|
||||
// maxActiveRunsPerPractice keeps one candidate from filling the queue
|
||||
// with debug runs of one practice.
|
||||
maxActiveRunsPerPractice = 1
|
||||
// runBucketLabel separates the rate limit counters of debug runs from
|
||||
// other uses of the keyed digest.
|
||||
runBucketLabel = "lincodex/practice/run-bucket/v1"
|
||||
)
|
||||
|
||||
// Request fields that a FieldError names. The HTTP adapter turns them into
|
||||
// pointers of its own body.
|
||||
const (
|
||||
@@ -53,8 +77,26 @@ var (
|
||||
// ErrUnavailable reports that code practice cannot run now, for example
|
||||
// because the code runner is disabled. Nothing was stored or graded.
|
||||
ErrUnavailable = errors.New("code practice unavailable")
|
||||
// ErrQueueBusy reports that the practice queue is full. Nothing was
|
||||
// stored; RetryError carries the wait.
|
||||
ErrQueueBusy = errors.New("practice queue is full")
|
||||
// ErrRateLimited reports a debug run beyond the technical limits: the
|
||||
// rate limit of the candidate, or an unfinished run of the practice.
|
||||
// Nothing was stored; RetryError carries the wait.
|
||||
ErrRateLimited = errors.New("practice run limit reached")
|
||||
)
|
||||
|
||||
// RetryError is a refusal that a later retry can pass, with the wait the
|
||||
// caller announces.
|
||||
type RetryError struct {
|
||||
Err error
|
||||
RetryAfter time.Duration
|
||||
}
|
||||
|
||||
func (retryError *RetryError) Error() string { return retryError.Err.Error() }
|
||||
|
||||
func (retryError *RetryError) Unwrap() error { return retryError.Err }
|
||||
|
||||
// FieldError names the request field that ErrInvalidRequest is about.
|
||||
type FieldError struct {
|
||||
Field string
|
||||
@@ -80,6 +122,10 @@ type Service struct {
|
||||
// enabled is false when no code runner is configured: practice then
|
||||
// answers unavailable and stores nothing.
|
||||
enabled bool
|
||||
// limiter and runRules bound the debug runs of one candidate; without a
|
||||
// limiter only the queue limits apply.
|
||||
limiter outbound.RateLimiter
|
||||
runRules []outbound.RateLimitRule
|
||||
}
|
||||
|
||||
func NewService(transactor outbound.Transactor, keyring Keyring, clock func() time.Time, enabled bool) (*Service, error) {
|
||||
@@ -89,6 +135,13 @@ func NewService(transactor outbound.Transactor, keyring Keyring, clock func() ti
|
||||
return &Service{transactor: transactor, keyring: keyring, clock: clock, enabled: enabled}, nil
|
||||
}
|
||||
|
||||
// WithRunRateLimit bounds the debug runs of one candidate by the rules, all
|
||||
// counted at once. A limiter failure refuses the run as unavailable.
|
||||
func (service *Service) WithRunRateLimit(limiter outbound.RateLimiter, rules ...outbound.RateLimitRule) *Service {
|
||||
service.limiter, service.runRules = limiter, rules
|
||||
return service
|
||||
}
|
||||
|
||||
// RunCommand asks for a debug run of a solution against the public examples
|
||||
// and the candidate's own tests.
|
||||
type RunCommand struct {
|
||||
@@ -126,6 +179,10 @@ type FinalResult struct {
|
||||
// Unchanged reports that the same solution was already submitted and
|
||||
// nothing was stored.
|
||||
Unchanged bool
|
||||
// RetryAfter is set when the queue was full: the practice is failed with
|
||||
// sandbox_busy, the solution was not stored, and it can be submitted
|
||||
// again after the wait.
|
||||
RetryAfter time.Duration
|
||||
}
|
||||
|
||||
type canonicalRequest struct {
|
||||
@@ -200,6 +257,9 @@ func (service *Service) submitRunInTransaction(
|
||||
if err != nil {
|
||||
return RunResult{}, fmt.Errorf("%s - build submission: %w", location, err)
|
||||
}
|
||||
if err := service.admitRun(ctx, repository, command.ActorID, practice.ID); err != nil {
|
||||
return RunResult{}, fmt.Errorf("%s - admit run: %w", location, err)
|
||||
}
|
||||
if err := repository.Submit(ctx, submission, request.record.Scope); err != nil {
|
||||
return RunResult{}, fmt.Errorf("%s - store run: %w", location, err)
|
||||
}
|
||||
@@ -271,6 +331,20 @@ func (service *Service) submitFinalInTransaction(
|
||||
if !practice.Status.AcceptsFinalSubmission() {
|
||||
return finalRepeat(ctx, repository, practice, submission)
|
||||
}
|
||||
active, err := repository.LockQueue(ctx)
|
||||
if err != nil {
|
||||
return FinalResult{}, fmt.Errorf("%s - lock queue: %w", location, err)
|
||||
}
|
||||
if active >= queueCapacity {
|
||||
// The full queue consumes nothing: the solution is not stored, and
|
||||
// the failed practice accepts it again.
|
||||
practice.Status, practice.FailureReason, practice.SubmittedAt =
|
||||
domain.AssessmentPracticeFailed, domain.AssessmentPracticeSandboxBusy, now
|
||||
if err := repository.SaveState(ctx, practice, now); err != nil {
|
||||
return FinalResult{}, fmt.Errorf("%s - mark practice busy: %w", location, err)
|
||||
}
|
||||
return FinalResult{Practice: practice.View(), RetryAfter: queueBusyRetryAfter}, nil
|
||||
}
|
||||
if err := repository.Submit(ctx, submission, request.record.Scope); err != nil {
|
||||
return FinalResult{}, fmt.Errorf("%s - store final submission: %w", location, err)
|
||||
}
|
||||
@@ -281,6 +355,46 @@ func (service *Service) submitFinalInTransaction(
|
||||
return FinalResult{Practice: practice.View()}, nil
|
||||
}
|
||||
|
||||
// admitRun applies the limits of a debug run in its transaction, which holds
|
||||
// the practice lock: one unfinished run per practice, the rate limit of the
|
||||
// candidate, then the queue capacity under the queue lock. A refusal stores
|
||||
// nothing.
|
||||
func (service *Service) admitRun(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentPracticeRepository,
|
||||
actorID uuid.UUID,
|
||||
practiceID uuid.UUID,
|
||||
) error {
|
||||
const location = "Service.admitRun"
|
||||
running, err := repository.ActiveRuns(ctx, practiceID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - count unfinished runs: %w", location, err)
|
||||
}
|
||||
if running >= maxActiveRunsPerPractice {
|
||||
return fmt.Errorf("%s - a run of the practice is unfinished: %w", location,
|
||||
&RetryError{Err: ErrRateLimited, RetryAfter: activeRunRetryAfter})
|
||||
}
|
||||
if service.limiter != nil {
|
||||
digest := service.keyring.Fingerprint([]byte(runBucketLabel + "\x00" + actorID.String()))
|
||||
decision, err := service.limiter.Take(ctx, "practice:run:"+hex.EncodeToString(digest[:]), service.runRules...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - take rate limit: %w: %w", location, ErrUnavailable, err)
|
||||
}
|
||||
if !decision.Allowed {
|
||||
return fmt.Errorf("%s - rate limit reached: %w", location,
|
||||
&RetryError{Err: ErrRateLimited, RetryAfter: decision.RetryAfter})
|
||||
}
|
||||
}
|
||||
active, err := repository.LockQueue(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - lock queue: %w", location, err)
|
||||
}
|
||||
if active >= queueCapacity {
|
||||
return fmt.Errorf("%s - queue is full: %w", location, &RetryError{Err: ErrQueueBusy, RetryAfter: queueBusyRetryAfter})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// finalRepeat answers a final submission to a pending or finished practice:
|
||||
// the stored solution sent again changes nothing, anything else conflicts.
|
||||
func finalRepeat(
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
// Package practicequeue runs the practice queue: it claims one practice job
|
||||
// at a time under a lease and hands it to the practice executor, which runs
|
||||
// it on the code runner. The queue is not the scheduled job runtime because a
|
||||
// practice try waits for an external run for seconds or minutes, while a
|
||||
// scheduled job runs its handler inside the transaction that completes it;
|
||||
// here no transaction stays open while the runner works.
|
||||
package practicequeue
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/practice"
|
||||
"lincodex/backend/internal/worker/retry"
|
||||
)
|
||||
|
||||
// Executor runs one claimed job.
|
||||
type Executor interface {
|
||||
Execute(ctx context.Context, job outbound.ClaimedPracticeJob) (practice.ExecutionOutcome, error)
|
||||
}
|
||||
|
||||
// Settings are the worker limits; config validates their ranges.
|
||||
type Settings struct {
|
||||
// PollInterval is the wait after a pass that found nothing to run.
|
||||
PollInterval time.Duration
|
||||
// Lease is how long a claimed job belongs to this worker before another
|
||||
// may take it over; the executor renews it while the run lasts.
|
||||
Lease time.Duration
|
||||
// StoreTimeout bounds one claim.
|
||||
StoreTimeout time.Duration
|
||||
// Backoff spaces passes while the database fails.
|
||||
Backoff retry.Backoff
|
||||
}
|
||||
|
||||
func (settings Settings) validate() error {
|
||||
if settings.PollInterval <= 0 || settings.Lease <= 0 || settings.StoreTimeout <= 0 ||
|
||||
settings.Backoff.Initial <= 0 || settings.Backoff.Max < settings.Backoff.Initial {
|
||||
return errors.New("practicequeue.New - poll interval, lease, store timeout, and backoff must be positive")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Worker claims practice jobs. Several workers may run against one database:
|
||||
// the claim keeps at most practice.MaxRunningJobs jobs running across all of
|
||||
// them.
|
||||
type Worker struct {
|
||||
owner uuid.UUID
|
||||
store outbound.PracticeJobStore
|
||||
executor Executor
|
||||
logger *slog.Logger
|
||||
settings Settings
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// New builds a worker with a random lease owner ID. clock is the application
|
||||
// clock that every lease decision uses.
|
||||
func New(store outbound.PracticeJobStore, executor Executor, logger *slog.Logger, settings Settings, clock func() time.Time) (*Worker, error) {
|
||||
if store == nil || executor == nil || logger == nil || clock == nil {
|
||||
return nil, errors.New("practicequeue.New - store, executor, logger, and clock are required")
|
||||
}
|
||||
if err := settings.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
owner := uuid.New()
|
||||
return &Worker{
|
||||
owner: owner, store: store, executor: executor, settings: settings, clock: clock,
|
||||
logger: logger.With(slog.String("lease_owner", owner.String())),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RunOnce claims one job and runs it. claimed is false when nothing could be
|
||||
// claimed: the queue is empty, nothing is available yet, or the running limit
|
||||
// is reached. Tests call it to drive the queue step by step; Run repeats it.
|
||||
func (worker *Worker) RunOnce(ctx context.Context) (outcome practice.ExecutionOutcome, claimed bool, err error) {
|
||||
claimCtx, cancel := context.WithTimeout(ctx, worker.settings.StoreTimeout)
|
||||
job, claimed, err := worker.store.Claim(claimCtx, outbound.PracticeJobClaim{
|
||||
Owner: worker.owner, Now: worker.clock(), Lease: worker.settings.Lease, MaxRunning: practice.MaxRunningJobs,
|
||||
})
|
||||
cancel()
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("Worker.RunOnce - claim job: %w", err)
|
||||
}
|
||||
if !claimed {
|
||||
return "", false, nil
|
||||
}
|
||||
if job.Reclaimed {
|
||||
worker.logger.Info("practice job taken over after its lease expired",
|
||||
slog.String("submission_id", job.SubmissionID.String()), slog.Int("attempts", job.Attempts))
|
||||
}
|
||||
outcome, err = worker.executor.Execute(ctx, job)
|
||||
if err != nil {
|
||||
return outcome, true, fmt.Errorf("Worker.RunOnce - execute job: %w", err)
|
||||
}
|
||||
return outcome, true, nil
|
||||
}
|
||||
|
||||
// Run claims and runs jobs until ctx ends. After a pass that ran a job the
|
||||
// next claim follows at once; otherwise the worker waits PollInterval, and
|
||||
// after a database failure Backoff, which grows across consecutive failures.
|
||||
// A job in progress when ctx ends is given back to the queue unfinished.
|
||||
func (worker *Worker) Run(ctx context.Context) {
|
||||
worker.logger.Info("practice queue worker started",
|
||||
slog.Duration("poll_interval", worker.settings.PollInterval), slog.Duration("lease", worker.settings.Lease))
|
||||
defer worker.logger.Info("practice queue worker stopped")
|
||||
failures := 0
|
||||
for ctx.Err() == nil {
|
||||
outcome, claimed, err := worker.RunOnce(ctx)
|
||||
var delay time.Duration
|
||||
switch {
|
||||
case err != nil && ctx.Err() == nil:
|
||||
failures++
|
||||
delay = worker.settings.Backoff.Delay(failures)
|
||||
worker.logger.Warn("practice queue pass failed in the database; the job is released or waits for its lease",
|
||||
slog.Int("consecutive_failures", failures), slog.Duration("retry_in", delay), slog.Any("error", err))
|
||||
case claimed:
|
||||
failures = 0
|
||||
worker.logger.Debug("practice job try ended", slog.String("outcome", string(outcome)))
|
||||
default:
|
||||
failures = 0
|
||||
delay = worker.settings.PollInterval
|
||||
}
|
||||
if delay > 0 && !retry.Wait(ctx, delay) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user