feat(practice): queue practice runs with one running and ten waiting

This commit is contained in:
shira committed 2026-10-11 15:01:07 +03:00
1 parent 51770eea6c
commit 754c745fba
40 files changed
+3040 -70

No files matched your search

@@ -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
}