Files

334 lines
13 KiB
Go

package practice
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"github.com/google/uuid"
"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) {
// A finished run names the runner run that the stored result belongs to;
// a status without a result or a valid run ID is outside the contract.
runnerRunID, idErr := uuid.Parse(status.RunID)
if status.Result == nil || idErr != nil || runnerRunID == uuid.Nil {
return executor.runnerFailure(ctx, job, outbound.ErrCodeRunnerBadResponse)
}
storeCtx, cancel := executor.storeContext(ctx)
defer cancel()
held, err := executor.store.Complete(storeCtx, job, runnerRunID, 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)), slog.String("runner_run_id", runnerRunID.String()))...)
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
}
}