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