Files
lincodex/backend/internal/port/outbound/code_runner.go
T

517 lines
19 KiB
Go

package outbound
import (
"context"
"errors"
"fmt"
"log/slog"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
// Bounds of the code runner contract (api/runner). They are checked before a
// request leaves the process, so a task family that breaks one fails in the
// caller's tests instead of as a runner rejection in production.
const (
// MaxCodeRunGroups and MaxCodeRunTestsPerGroup also bound a result.
MaxCodeRunGroups = 4
MaxCodeRunTestsPerGroup = 50
maxCodeRunSourceBytes = 65536
maxCodeRunTestTextBytes = 262144
minCodeRunTimeLimitMs = 100
maxCodeRunTimeLimitMs = 10000
minCodeRunMemoryLimitMB = 32
maxCodeRunMemoryLimitMB = 512
minCodeRunOutputLimitKB = 1
maxCodeRunOutputLimitKB = 1024
maxCodeRunAbsTolerance = 1_000_000_000
maxCodeRunRelTolerance = 1
// maxCodeRunCPUBudgetMs bounds tests multiplied by the time limit of one
// run, as the runner does.
maxCodeRunCPUBudgetMs = 300000
// maxCodeRunPayloadBytes is the default runner request limit (8 MiB)
// minus room for the JSON structure around the texts.
maxCodeRunPayloadBytes = 8<<20 - 64<<10
redactedCodeRunRequest = "[redacted code run request]"
redactedCodeRunResultLog = "[code run result]"
)
var (
// ErrCodeRunnerUnavailable is the umbrella of every failure that leaves a
// submission without a verdict although the candidate did nothing wrong:
// the runner is disabled, unreachable, too slow, refuses the service
// token, fails with a server error, answers outside the contract, or
// reports that it could not evaluate the source. Nothing is graded and
// the caller must not score, fail, or accept the submission; it reports
// the service as unavailable and retries later. Check it with errors.Is
// before the specific errors below.
ErrCodeRunnerUnavailable = errors.New("code runner unavailable")
// ErrCodeRunnerDisabled means CODE_RUNNER_URL is not set, so no request
// was made. It is an unavailable runner, never a verdict.
ErrCodeRunnerDisabled = fmt.Errorf("code runner is disabled: %w", ErrCodeRunnerUnavailable)
// ErrCodeRunnerUnauthorized means the runner refused the service token
// (401). It points at deployment configuration and needs an operator, not
// a retry.
ErrCodeRunnerUnauthorized = fmt.Errorf("code runner refused the service token: %w", ErrCodeRunnerUnavailable)
// ErrCodeRunnerBadResponse means the runner answered, but not as the
// contract says: a malformed or oversized body, a wrong content type, an
// unexpected status, or a result that contradicts the request or itself.
// The run may exist on the runner, so a retry with the same key is
// harmless.
ErrCodeRunnerBadResponse = fmt.Errorf("code runner answered outside its contract: %w", ErrCodeRunnerUnavailable)
// ErrCodeRunnerInfrastructureFailure means the runner finished the run
// with the outcome infrastructure_failure: it could not evaluate the
// source. The runner keeps that result under the run ID, so the same key
// would return it again; the caller starts the next try with a higher
// CodeRunKey.Generation.
ErrCodeRunnerInfrastructureFailure = fmt.Errorf("code runner could not evaluate the source: %w", ErrCodeRunnerUnavailable)
// ErrInvalidCodeRunRequest reports a request that fails
// CodeRunRequest.Validate, or that the runner rejected as invalid
// (400, 413). It is a caller or task content bug. Nothing ran, and it is
// not a candidate's wrong answer.
ErrInvalidCodeRunRequest = errors.New("invalid code run request")
// ErrCodeRunNotFound means the runner does not hold the run: it was
// forgotten after its retention time or lost in a restart. Submit the
// request again with the same key; the runner starts a new run.
ErrCodeRunNotFound = errors.New("code run not found")
// ErrCodeRunKeyReused means the runner already holds a run under this
// key with a different payload (422). The payload of one key must not
// change; the caller bumps CodeRunKey.Generation to run the new payload.
ErrCodeRunKeyReused = errors.New("code run key reused with another payload")
)
var codeRunTestKeyPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,31}$`)
// CodeLanguage is a language the runner can compile or interpret.
type CodeLanguage string
const (
CodeLanguagePython3 CodeLanguage = "python3"
CodeLanguageGo CodeLanguage = "go"
)
// CodeCheckerKind says how the runner compares program output with the
// expected output of a test.
type CodeCheckerKind string
const (
// CodeCheckerExact compares the texts after line-ending and trailing
// white space normalization.
CodeCheckerExact CodeCheckerKind = "exact"
// CodeCheckerTokens compares whitespace-separated tokens.
CodeCheckerTokens CodeCheckerKind = "tokens"
// CodeCheckerNumbers compares tokens and accepts numeric tokens within
// AbsTolerance or RelTolerance.
CodeCheckerNumbers CodeCheckerKind = "numbers"
// CodeCheckerCustom runs the checker program of the task family.
CodeCheckerCustom CodeCheckerKind = "custom"
)
// CodeTestVisibility says whether the person who wrote the source may see
// details of a test. Hidden tests never carry program output or diagnostics.
type CodeTestVisibility string
const (
CodeTestPublic CodeTestVisibility = "public"
CodeTestHidden CodeTestVisibility = "hidden"
)
// CodeRunKey identifies one logical run. The adapter turns it into the opaque
// run ID the runner stores, so the runner never sees these values and every
// retry of the same key reuses the same run.
type CodeRunKey struct {
// AttemptItemID is the assessment attempt item the source answers.
AttemptItemID uuid.UUID
// SubmissionID identifies the submission of that item.
SubmissionID uuid.UUID
// Generation is 0 for the first try. After ErrCodeRunnerInfrastructureFailure
// the caller increments it; the runner would return the stored failure for
// the old key.
Generation uint32
}
// CodeRunLimits are the technical limits applied to every test of a run.
type CodeRunLimits struct {
// TimeLimitMs is the CPU time per test.
TimeLimitMs int32
// MemoryLimitMB is the memory of the test's processes.
MemoryLimitMB int32
// OutputLimitKB is the standard output per test.
OutputLimitKB int32
}
// CodeChecker configures the comparison of a group.
type CodeChecker struct {
Kind CodeCheckerKind
// AbsTolerance and RelTolerance apply to CodeCheckerNumbers only; zero
// means unset, and at least one must be positive.
AbsTolerance float64
RelTolerance float64
// Program is the checker program of CodeCheckerCustom only.
Program *CodeCheckerProgram
}
// CodeCheckerProgram is the checker program of a task family.
type CodeCheckerProgram struct {
Language CodeLanguage
Source string
}
// CodeTest is one input and the output the checker expects.
type CodeTest struct {
// ID is an opaque label such as "1" or "hidden-1" that is unique in its
// group. It is not a database identifier.
ID string
Input string
ExpectedOutput string
}
// CodeTestGroup is a set of tests with one checker. A group stops at its
// first failed test.
type CodeTestGroup struct {
// ID is an opaque label such as "public" or "hidden-1" that is unique in
// the run.
ID string
Visibility CodeTestVisibility
Checker CodeChecker
Tests []CodeTest
}
// CodeRunRequest is one source with its limits and test groups. It carries
// nothing about the candidate: the runner receives only code, tests, and
// technical limits.
//
// String, GoString, Format, and LogValue redact the whole request, because
// the source is candidate work and the tests of hidden groups are secret task
// content. Read the fields directly where they are needed.
type CodeRunRequest struct {
Key CodeRunKey
Language CodeLanguage
Source string
Limits CodeRunLimits
Groups []CodeTestGroup
}
func (request CodeRunRequest) String() string { return redactedCodeRunRequest }
func (request CodeRunRequest) GoString() string { return redactedCodeRunRequest }
// Format redacts every verb; without it %+v would print the fields.
func (request CodeRunRequest) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(redactedCodeRunRequest))
}
func (request CodeRunRequest) LogValue() slog.Value { return slog.StringValue(redactedCodeRunRequest) }
// Validate reports a request that the runner would reject, using the rules of
// the runner contract. Errors wrap ErrInvalidCodeRunRequest and name only the
// field, never source or test text.
func (request CodeRunRequest) Validate() error {
if request.Key.AttemptItemID == uuid.Nil || request.Key.SubmissionID == uuid.Nil {
return invalidCodeRunRequest("key must name the attempt item and the submission")
}
if !validCodeLanguage(request.Language) {
return invalidCodeRunRequest("language must be python3 or go")
}
if err := validateCodeText("source", request.Source, maxCodeRunSourceBytes, true); err != nil {
return err
}
if err := request.Limits.validate(); err != nil {
return err
}
if len(request.Groups) < 1 || len(request.Groups) > MaxCodeRunGroups {
return invalidCodeRunRequest("groups must have 1 to 4 entries")
}
size := len(request.Source)
seenGroups := make(map[string]struct{}, len(request.Groups))
totalTests := 0
for _, group := range request.Groups {
if _, duplicate := seenGroups[group.ID]; duplicate {
return invalidCodeRunRequest("group IDs must be unique")
}
seenGroups[group.ID] = struct{}{}
groupSize, err := group.validate()
if err != nil {
return err
}
size += groupSize
totalTests += len(group.Tests)
}
// The runner stops a test at its CPU limit and bounds the whole run.
if totalTests*int(request.Limits.TimeLimitMs) > maxCodeRunCPUBudgetMs {
return invalidCodeRunRequest("tests multiplied by the time limit must not exceed 300000 ms")
}
if size > maxCodeRunPayloadBytes {
return invalidCodeRunRequest("payload must fit the runner request limit")
}
return nil
}
func (limits CodeRunLimits) validate() error {
switch {
case limits.TimeLimitMs < minCodeRunTimeLimitMs || limits.TimeLimitMs > maxCodeRunTimeLimitMs:
return invalidCodeRunRequest("time limit must be 100 to 10000 ms")
case limits.MemoryLimitMB < minCodeRunMemoryLimitMB || limits.MemoryLimitMB > maxCodeRunMemoryLimitMB:
return invalidCodeRunRequest("memory limit must be 32 to 512 MiB")
case limits.OutputLimitKB < minCodeRunOutputLimitKB || limits.OutputLimitKB > maxCodeRunOutputLimitKB:
return invalidCodeRunRequest("output limit must be 1 to 1024 KiB")
}
return nil
}
// validate checks one group and returns the bytes of text it carries.
func (group CodeTestGroup) validate() (int, error) {
if !codeRunTestKeyPattern.MatchString(group.ID) {
return 0, invalidCodeRunRequest("group ID must match [a-z0-9][a-z0-9_-]{0,31}")
}
if group.Visibility != CodeTestPublic && group.Visibility != CodeTestHidden {
return 0, invalidCodeRunRequest("group visibility must be public or hidden")
}
size, err := group.Checker.validate()
if err != nil {
return 0, err
}
if len(group.Tests) < 1 || len(group.Tests) > MaxCodeRunTestsPerGroup {
return 0, invalidCodeRunRequest("group must have 1 to 50 tests")
}
seenTests := make(map[string]struct{}, len(group.Tests))
for _, test := range group.Tests {
if !codeRunTestKeyPattern.MatchString(test.ID) {
return 0, invalidCodeRunRequest("test ID must match [a-z0-9][a-z0-9_-]{0,31}")
}
if _, duplicate := seenTests[test.ID]; duplicate {
return 0, invalidCodeRunRequest("test IDs must be unique in a group")
}
seenTests[test.ID] = struct{}{}
if err := validateCodeText("test input", test.Input, maxCodeRunTestTextBytes, false); err != nil {
return 0, err
}
if err := validateCodeText("test expected output", test.ExpectedOutput, maxCodeRunTestTextBytes, false); err != nil {
return 0, err
}
size += len(test.Input) + len(test.ExpectedOutput)
}
return size, nil
}
// validate checks one checker and returns the bytes of program source.
func (checker CodeChecker) validate() (int, error) {
hasTolerance := checker.AbsTolerance != 0 || checker.RelTolerance != 0
switch checker.Kind {
case CodeCheckerExact, CodeCheckerTokens:
if hasTolerance || checker.Program != nil {
return 0, invalidCodeRunRequest("checker exact and tokens take no tolerance or program")
}
case CodeCheckerNumbers:
if err := checker.validateNumbers(); err != nil {
return 0, err
}
case CodeCheckerCustom:
if hasTolerance {
return 0, invalidCodeRunRequest("checker custom takes no tolerance")
}
if checker.Program == nil || !validCodeLanguage(checker.Program.Language) {
return 0, invalidCodeRunRequest("checker custom needs a program in python3 or go")
}
if err := validateCodeText("checker program", checker.Program.Source, maxCodeRunSourceBytes, true); err != nil {
return 0, err
}
return len(checker.Program.Source), nil
default:
return 0, invalidCodeRunRequest("checker kind must be exact, tokens, numbers, or custom")
}
return 0, nil
}
func (checker CodeChecker) validateNumbers() error {
if checker.Program != nil {
return invalidCodeRunRequest("checker numbers takes no program")
}
// NaN fails every comparison, so the negated range checks reject it.
if !(checker.AbsTolerance >= 0 && checker.AbsTolerance <= maxCodeRunAbsTolerance) ||
!(checker.RelTolerance >= 0 && checker.RelTolerance <= maxCodeRunRelTolerance) ||
(checker.AbsTolerance == 0 && checker.RelTolerance == 0) {
return invalidCodeRunRequest("checker numbers needs a positive tolerance within its range")
}
return nil
}
func validCodeLanguage(language CodeLanguage) bool {
return language == CodeLanguagePython3 || language == CodeLanguageGo
}
func validateCodeText(name, text string, maxBytes int, required bool) error {
switch {
case required && strings.TrimSpace(text) == "":
return invalidCodeRunRequest(name + " must not be empty")
case len(text) > maxBytes:
return invalidCodeRunRequest(fmt.Sprintf("%s must have at most %d bytes", name, maxBytes))
case !utf8.ValidString(text):
return invalidCodeRunRequest(name + " must be valid UTF-8")
case strings.ContainsRune(text, 0):
return invalidCodeRunRequest(name + " must not contain NUL")
}
return nil
}
func invalidCodeRunRequest(reason string) error {
return fmt.Errorf("CodeRunRequest.Validate - %s: %w", reason, ErrInvalidCodeRunRequest)
}
// CodeRunState is what a runner call established about a run. The zero value
// is not a state and must never be read as progress or acceptance.
type CodeRunState string
const (
// CodeRunRunning means the runner holds the run and has no result yet.
// Poll again later.
CodeRunRunning CodeRunState = "running"
// CodeRunFinished means Result holds the final, validated result.
CodeRunFinished CodeRunState = "finished"
// CodeRunBusy means every sandbox slot is busy or the runner is draining.
// The runner stored nothing; submit again with the same key after
// RetryAfter. Only Submit reports it, and it is a capacity signal, not a
// failure of the candidate or of the runner.
CodeRunBusy CodeRunState = "busy"
)
// CodeRunOutcome is the verdict of a test, a group, a compile step, or a run.
// It has no value for the runner's infrastructure_failure, which is
// ErrCodeRunnerInfrastructureFailure: a failure to evaluate says nothing about
// the program.
type CodeRunOutcome string
const (
CodeOutcomeAccepted CodeRunOutcome = "accepted"
CodeOutcomeWrongAnswer CodeRunOutcome = "wrong_answer"
CodeOutcomeCompileError CodeRunOutcome = "compile_error"
CodeOutcomeTimeLimitExceeded CodeRunOutcome = "time_limit_exceeded"
CodeOutcomeMemoryLimitExceeded CodeRunOutcome = "memory_limit_exceeded"
CodeOutcomeOutputLimitExceeded CodeRunOutcome = "output_limit_exceeded"
CodeOutcomeRuntimeError CodeRunOutcome = "runtime_error"
)
// CodeTerminationLimit is the limit that stopped a test.
type CodeTerminationLimit string
const (
CodeLimitCPUTime CodeTerminationLimit = "cpu_time"
CodeLimitWallTime CodeTerminationLimit = "wall_time"
CodeLimitMemory CodeTerminationLimit = "memory"
CodeLimitOutput CodeTerminationLimit = "output"
CodeLimitProcesses CodeTerminationLimit = "processes"
)
// CodeCompileResult is the compile phase of a run. Only compile_error carries
// a diagnostic, which can quote the source but never test data.
type CodeCompileResult struct {
Outcome CodeRunOutcome
Diagnostic string
}
// CodeTestResult is the result of one evaluated test.
type CodeTestResult struct {
ID string
Outcome CodeRunOutcome
TimeMs int64
WallTimeMs int64
MemoryKB int64
// ExitCode is set when the program exited normally; Signal when a signal
// killed it. Limit is empty unless a limit stopped the test.
ExitCode *int32
Signal *int32
Limit CodeTerminationLimit
Diagnostic string
}
// CodeGroupResult is the result of one group. Tests lists the evaluated tests
// only: the tests after the first failed one are not run.
type CodeGroupResult struct {
ID string
Visibility CodeTestVisibility
Outcome CodeRunOutcome
PassedTests int
TotalTests int
MaxTimeMs int64
MaxMemoryKB int64
Tests []CodeTestResult
}
// CodeRunResult is the validated final result of a run. The caller computes
// the score from the groups; the runner only reports which ones passed.
type CodeRunResult struct {
Outcome CodeRunOutcome
Compile *CodeCompileResult
Groups []CodeGroupResult
Duration time.Duration
}
// LogValue summarizes the result without diagnostics, which can quote the
// candidate's source.
func (result CodeRunResult) LogValue() slog.Value {
return slog.GroupValue(
slog.String("outcome", string(result.Outcome)),
slog.Int("groups", len(result.Groups)),
slog.Duration("duration", result.Duration),
)
}
func (result CodeRunResult) String() string { return redactedCodeRunResultLog }
// CodeRunStatus is the state of a run after one runner call.
type CodeRunStatus struct {
State CodeRunState
// RunID is the opaque ID the runner holds the run under. It identifies no
// user, attempt, or task; it is safe to log and matches the runner's logs.
RunID string
// RetryAfter is the runner's wait hint for CodeRunBusy only.
RetryAfter time.Duration
// Result is set for CodeRunFinished only.
Result *CodeRunResult
}
// CodeRunner runs candidate code against test groups in the own sandboxed
// runner service (api/runner). Judge0 is not used.
//
// Both methods make exactly one runner call and never retry or sleep; queueing,
// backoff, and polling belong to the caller. Submit is idempotent by
// request.Key: the same key with the same payload returns the current state of
// one run and never runs it twice. Poll reads that run without sending the
// payload again.
//
// A nil error comes with a state of running, finished, or (Submit only) busy.
// A finished state always holds a validated result. An error means that
// nothing was graded:
// - ErrInvalidCodeRunRequest: the request is invalid, nothing was sent.
// - ErrCodeRunnerUnavailable (including the disabled, unauthorized,
// bad-response, and infrastructure-failure forms): no verdict could be
// obtained. It is never a wrong answer and never a reason to fail the
// candidate.
// - ErrCodeRunNotFound (Poll): the runner lost the run; Submit again.
// - ErrCodeRunKeyReused: the key was used with another payload.
// - the context error when ctx ended.
//
// The returned status is zero when err is not nil. Errors and logs never
// include source, tests, program output, or the token.
type CodeRunner interface {
Submit(ctx context.Context, request CodeRunRequest) (CodeRunStatus, error)
Poll(ctx context.Context, request CodeRunRequest) (CodeRunStatus, error)
}