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

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

No files matched your search

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