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
@@ -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(
|
||||
|
||||
Reference in new issue
Block a user