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

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