Files

360 lines
11 KiB
Go

// Package judge evaluates one source against its test groups in the sandbox
// and turns sandbox results into contract outcomes.
package judge
import (
"bytes"
"context"
"fmt"
"log/slog"
"slices"
"strings"
"time"
"unicode/utf8"
"lincodex/runner/internal/checker"
"lincodex/runner/internal/sandbox"
)
// Outcome is the result of a test, a group, a compile step, or a run.
type Outcome string
const (
Accepted Outcome = "accepted"
WrongAnswer Outcome = "wrong_answer"
CompileError Outcome = "compile_error"
TimeLimitExceeded Outcome = "time_limit_exceeded"
MemoryLimitExceeded Outcome = "memory_limit_exceeded"
OutputLimitExceeded Outcome = "output_limit_exceeded"
RuntimeError Outcome = "runtime_error"
InfrastructureFailure Outcome = "infrastructure_failure"
)
// Visibility tells whether results may carry program diagnostics.
type Visibility string
const (
Public Visibility = "public"
Hidden Visibility = "hidden"
)
// Contract limits of a test result.
const (
maxCompileDiagnostic = 4096
maxTestDiagnostic = 2048
)
// Request is one run. It holds no identifiers of people or product records.
// The JSON tags define the encoding of the idempotency fingerprint.
type Request struct {
Language string `json:"language"`
Source string `json:"source"`
Limits Limits `json:"limits"`
Groups []Group `json:"groups"`
}
// Limits apply to every test of a run.
type Limits struct {
TimeLimit time.Duration `json:"time_limit"`
MemoryBytes int64 `json:"memory_bytes"`
OutputBytes int64 `json:"output_bytes"`
}
// Group is a set of tests with one checker.
type Group struct {
ID string `json:"id"`
Visibility Visibility `json:"visibility"`
Checker checker.Spec `json:"checker"`
Tests []Test `json:"tests"`
}
// Test is one input and its expected output.
type Test struct {
ID string `json:"id"`
Input string `json:"input"`
ExpectedOutput string `json:"expected_output"`
}
// Result is the evaluation of a run.
type Result struct {
Outcome Outcome
Compile *CompileResult
Groups []GroupResult
Duration time.Duration
}
// CompileResult is the outcome of the compile or syntax check step.
type CompileResult struct {
Outcome Outcome
Diagnostic string
}
// GroupResult is the evaluation of one group.
type GroupResult struct {
ID string
Visibility Visibility
Outcome Outcome
Passed int
Total int
MaxCPUTime time.Duration
MaxMemoryKB int64
Tests []TestResult
}
// TestResult is the evaluation of one test.
type TestResult struct {
ID string
Outcome Outcome
CPUTime time.Duration
WallTime time.Duration
MemoryKB int64
ExitCode *int
Signal *int
Limit sandbox.Termination
Diagnostic string
}
// Executor is the sandbox used by the judge.
type Executor interface {
NewBox(fileName string, content []byte) (*sandbox.Box, error)
Run(ctx context.Context, spec sandbox.Spec, limits sandbox.Limits) (sandbox.Result, error)
}
// Judge evaluates requests with one executor and a set of languages.
type Judge struct {
executor Executor
languages map[string]Language
logger *slog.Logger
}
// New returns a judge for the given languages.
func New(executor Executor, logger *slog.Logger, languages ...Language) *Judge {
byID := make(map[string]Language, len(languages))
for _, language := range languages {
byID[language.ID] = language
}
return &Judge{executor: executor, languages: byID, logger: logger}
}
// Supports reports whether the judge knows the language.
func (j *Judge) Supports(language string) bool {
_, ok := j.languages[language]
return ok
}
// Run evaluates a request. Failures of the runner become
// infrastructure_failure; they never look like an outcome of the program.
func (j *Judge) Run(ctx context.Context, request Request) Result {
started := time.Now()
result := j.evaluate(ctx, request)
result.Duration = time.Since(started)
return result
}
func (j *Judge) evaluate(ctx context.Context, request Request) Result {
language, ok := j.languages[request.Language]
if !ok {
j.logger.ErrorContext(ctx, "run has an unsupported language")
return failedRun(request, InfrastructureFailure, nil)
}
box, err := j.executor.NewBox(language.SourceFile, []byte(request.Source))
if err != nil {
j.logger.ErrorContext(ctx, "cannot create the run directory", slog.Any("error", err))
return failedRun(request, InfrastructureFailure, nil)
}
defer func() {
if err := box.Remove(); err != nil {
j.logger.ErrorContext(ctx, "cannot remove the run directory", slog.Any("error", err))
}
}()
compile, ok := j.compile(ctx, language, box)
if !ok {
return failedRun(request, compile.Outcome, compile)
}
checkers := newCheckerSet(j)
defer checkers.close(ctx)
result := Result{Outcome: Accepted, Compile: compile, Groups: make([]GroupResult, 0, len(request.Groups))}
for _, group := range request.Groups {
groupResult := j.evaluateGroup(ctx, language, box, request.Limits, group, checkers)
if groupResult.Outcome == InfrastructureFailure {
return failedRun(request, InfrastructureFailure, compile)
}
if result.Outcome == Accepted && groupResult.Outcome != Accepted {
result.Outcome = groupResult.Outcome
}
result.Groups = append(result.Groups, groupResult)
}
return result
}
// compile runs the language's compile steps. ok is false when no test may
// run.
func (j *Judge) compile(ctx context.Context, language Language, box *sandbox.Box) (*CompileResult, bool) {
if len(language.Compile) == 0 {
return nil, true
}
for _, step := range language.Compile {
run, err := j.executor.Run(ctx, sandbox.Spec{
Argv: step.Argv,
Mounts: box.Mounts(true),
Env: language.CompileEnv,
WorkDir: step.WorkDir,
}, language.CompileLimits)
if err != nil {
j.logger.ErrorContext(ctx, "compile step failed in the sandbox", slog.Any("error", err))
return &CompileResult{Outcome: InfrastructureFailure}, false
}
if run.Termination != sandbox.TerminationNone || run.ExitCode != 0 || run.Signal != 0 {
return &CompileResult{Outcome: CompileError, Diagnostic: compileDiagnostic(run)}, false
}
}
return &CompileResult{Outcome: Accepted}, true
}
func compileDiagnostic(run sandbox.Result) string {
if run.Termination != sandbox.TerminationNone {
return "The compile step exceeded its " + strings.ReplaceAll(string(run.Termination), "_", " ") + " limit."
}
// The Go compiler reports errors on stdout, the Python check on stderr.
return excerpt(append(slices.Clone(run.Stdout), run.Stderr...), maxCompileDiagnostic)
}
func (j *Judge) evaluateGroup(ctx context.Context, language Language, box *sandbox.Box, limits Limits, group Group, checkers *checkerSet) GroupResult {
result := GroupResult{
ID: group.ID,
Visibility: group.Visibility,
Outcome: Accepted,
Total: len(group.Tests),
Tests: make([]TestResult, 0, len(group.Tests)),
}
check, err := checkers.get(ctx, group.Checker)
if err != nil {
j.logger.ErrorContext(ctx, "group checker is not available", slog.Any("error", err))
result.Outcome = InfrastructureFailure
return result
}
for _, test := range group.Tests {
testResult, err := j.evaluateTest(ctx, language, box, limits, group.Visibility, check, test)
if err != nil {
j.logger.ErrorContext(ctx, "test failed in the sandbox", slog.Any("error", err))
result.Outcome = InfrastructureFailure
return result
}
result.Tests = append(result.Tests, testResult)
result.MaxCPUTime = max(result.MaxCPUTime, testResult.CPUTime)
result.MaxMemoryKB = max(result.MaxMemoryKB, testResult.MemoryKB)
if testResult.Outcome != Accepted {
result.Outcome = testResult.Outcome
return result
}
result.Passed++
}
return result
}
func (j *Judge) evaluateTest(
ctx context.Context,
language Language,
box *sandbox.Box,
limits Limits,
visibility Visibility,
check checker.Checker,
test Test,
) (TestResult, error) {
run, err := j.executor.Run(ctx, sandbox.Spec{
Argv: language.Run,
Stdin: []byte(test.Input),
Mounts: box.Mounts(false),
Env: language.RunEnv,
}, sandbox.Limits{
CPUTime: limits.TimeLimit,
WallTime: wallTimeLimit(limits.TimeLimit),
MemoryBytes: limits.MemoryBytes,
OutputBytes: limits.OutputBytes,
})
if err != nil {
return TestResult{}, err
}
result := TestResult{
ID: test.ID,
Outcome: outcomeOf(run),
CPUTime: run.CPUTime,
WallTime: run.WallTime,
MemoryKB: run.PeakMemoryKB,
Limit: run.Termination,
}
if run.Signal != 0 {
result.Signal = &run.Signal
} else {
result.ExitCode = &run.ExitCode
}
if result.Outcome == Accepted {
accepted, err := check.Check(ctx, checker.Input{
TestInput: []byte(test.Input),
Expected: []byte(test.ExpectedOutput),
Actual: run.Stdout,
})
if err != nil {
return TestResult{}, fmt.Errorf("judge.Judge.evaluateTest - checker: %w", err)
}
if !accepted {
result.Outcome = WrongAnswer
}
}
if visibility == Public && result.Outcome != Accepted && result.Outcome != WrongAnswer {
result.Diagnostic = excerpt(run.Stderr, maxTestDiagnostic)
}
return result, nil
}
// wallTimeLimit allows blocking and startup on top of the CPU limit.
func wallTimeLimit(cpu time.Duration) time.Duration {
const startupAllowance = 500 * time.Millisecond
return 2*cpu + startupAllowance
}
// outcomeOf maps how a program ended to an outcome before checking output.
func outcomeOf(run sandbox.Result) Outcome {
switch run.Termination {
case sandbox.TerminationMemory:
return MemoryLimitExceeded
case sandbox.TerminationOutput:
return OutputLimitExceeded
case sandbox.TerminationCPUTime, sandbox.TerminationWallTime:
return TimeLimitExceeded
case sandbox.TerminationProcesses:
return RuntimeError
case sandbox.TerminationNone:
}
if run.Signal != 0 || run.ExitCode != 0 {
return RuntimeError
}
return Accepted
}
// failedRun gives every group the outcome of a run that stopped early.
func failedRun(request Request, outcome Outcome, compile *CompileResult) Result {
result := Result{Outcome: outcome, Compile: compile, Groups: make([]GroupResult, 0, len(request.Groups))}
for _, group := range request.Groups {
result.Groups = append(result.Groups, GroupResult{
ID: group.ID,
Visibility: group.Visibility,
Outcome: outcome,
Total: len(group.Tests),
Tests: []TestResult{},
})
}
return result
}
// excerpt returns the last limit bytes of text as valid UTF-8.
func excerpt(text []byte, limit int) string {
text = bytes.ToValidUTF8(text, []byte("�"))
for len(text) > limit {
_, size := utf8.DecodeRune(text)
text = text[size:]
}
return string(text)
}