feat(runner): compile Go and check answers per test group

This commit is contained in:
shira committed 2026-10-11 08:59:29 +03:00
1 parent e95c681165
commit afee564bf4
61 files changed
+2592 -143

No files matched your search

+136
View File
@@ -0,0 +1,136 @@
package judge
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"log/slog"
"slices"
"time"
"lincodex/runner/internal/checker"
"lincodex/runner/internal/sandbox"
)
// Limits of one custom checker call. They belong to the task family, not to
// the candidate's limits, and they never count toward the candidate's time.
const (
checkerCPU = 5 * time.Second
checkerWall = 10 * time.Second
checkerMemory = 256 << 20
checkerOutput = 64 << 10
)
// Exit statuses of a custom checker program.
const (
checkerAccepts = 0
checkerRejects = 1
)
// Files a custom checker receives, as arguments, under sandbox.CheckPath.
var checkFileNames = []string{"input", "expected", "actual"}
var errCheckerFailed = errors.New("custom checker failed")
// checkerSet builds the checkers of one run. A custom checker program is
// compiled once per run and reused by every group that names it.
type checkerSet struct {
judge *Judge
custom map[[sha256.Size]byte]*customChecker
}
func newCheckerSet(judge *Judge) *checkerSet {
return &checkerSet{judge: judge, custom: make(map[[sha256.Size]byte]*customChecker)}
}
func (s *checkerSet) get(ctx context.Context, spec checker.Spec) (checker.Checker, error) {
if spec.Kind != checker.Custom {
return checker.New(spec)
}
if spec.Program == nil {
return nil, errors.New("judge.checkerSet.get - custom checker without a program")
}
key := sha256.Sum256([]byte(spec.Program.Language + "\x00" + spec.Program.Source))
if existing, ok := s.custom[key]; ok {
return existing, nil
}
built, err := s.build(ctx, *spec.Program)
if err != nil {
return nil, err
}
s.custom[key] = built
return built, nil
}
// build compiles a checker program in its own box. Its diagnostics are not
// returned: the checker is task family content, so a failure is a failure
// of the runner, not of the candidate.
func (s *checkerSet) build(ctx context.Context, program checker.Program) (*customChecker, error) {
language, ok := s.judge.languages[program.Language]
if !ok {
return nil, fmt.Errorf("judge.checkerSet.build - unsupported checker language %q", program.Language)
}
box, err := s.judge.executor.NewBox(language.SourceFile, []byte(program.Source))
if err != nil {
return nil, fmt.Errorf("judge.checkerSet.build - box: %w", err)
}
compile, ok := s.judge.compile(ctx, language, box)
if !ok {
return nil, errors.Join(fmt.Errorf("judge.checkerSet.build - compile: %s", compile.Outcome), box.Remove())
}
return &customChecker{executor: s.judge.executor, language: language, box: box}, nil
}
func (s *checkerSet) close(ctx context.Context) {
for _, built := range s.custom {
if err := built.box.Remove(); err != nil {
s.judge.logger.ErrorContext(ctx, "cannot remove the checker directory", slog.Any("error", err))
}
}
}
// customChecker runs a family checker program in the sandbox with the same
// isolation as a candidate program. It sees the input, the expected output,
// and the actual output as read-only files and answers with its exit
// status; its own output is discarded and never returned.
type customChecker struct {
executor Executor
language Language
box *sandbox.Box
}
func (c *customChecker) Check(ctx context.Context, input checker.Input) (accepted bool, err error) {
mount, remove, err := c.box.AddCheckFiles(map[string][]byte{
checkFileNames[0]: input.TestInput,
checkFileNames[1]: input.Expected,
checkFileNames[2]: input.Actual,
})
if err != nil {
return false, err
}
defer func() {
err = errors.Join(err, remove())
}()
argv := slices.Clone(c.language.Run)
for _, name := range checkFileNames {
argv = append(argv, sandbox.CheckPath+"/"+name)
}
run, err := c.executor.Run(ctx, sandbox.Spec{
Argv: argv,
Mounts: append(c.box.Mounts(false), mount),
Env: c.language.RunEnv,
}, sandbox.Limits{CPUTime: checkerCPU, WallTime: checkerWall, MemoryBytes: checkerMemory, OutputBytes: checkerOutput})
if err != nil {
return false, fmt.Errorf("judge.customChecker.Check - run: %w", err)
}
if run.Termination == sandbox.TerminationNone && run.Signal == 0 {
switch run.ExitCode {
case checkerAccepts:
return true, nil
case checkerRejects:
return false, nil
}
}
return false, fmt.Errorf("judge.customChecker.Check - exit %d, signal %d, limit %q: %w", run.ExitCode, run.Signal, run.Termination, errCheckerFailed)
}
+28 -16
View File
@@ -7,6 +7,7 @@ import (
"context"
"fmt"
"log/slog"
"slices"
"strings"
"time"
"unicode/utf8"
@@ -171,9 +172,11 @@ func (j *Judge) evaluate(ctx context.Context, request Request) Result {
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)
groupResult := j.evaluateGroup(ctx, language, box, request.Limits, group, checkers)
if groupResult.Outcome == InfrastructureFailure {
return failedRun(request, InfrastructureFailure, compile)
}
@@ -185,31 +188,39 @@ func (j *Judge) evaluate(ctx context.Context, request Request) Result {
return result
}
// compile runs the language's compile step. ok is false when no test may run.
// 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
}
run, err := j.executor.Run(ctx, sandbox.Spec{Argv: language.Compile, BoxDir: box.Dir()}, language.CompileLimits)
if err != nil {
j.logger.ErrorContext(ctx, "compile step failed in the sandbox", slog.Any("error", err))
return &CompileResult{Outcome: InfrastructureFailure}, false
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
}
}
if run.Termination == sandbox.TerminationNone && run.ExitCode == 0 && run.Signal == 0 {
return &CompileResult{Outcome: Accepted}, true
}
diagnostic := compileDiagnostic(run)
return &CompileResult{Outcome: CompileError, Diagnostic: diagnostic}, 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."
}
return excerpt(run.Stderr, maxCompileDiagnostic)
// 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) GroupResult {
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,
@@ -217,9 +228,9 @@ func (j *Judge) evaluateGroup(ctx context.Context, language Language, box *sandb
Total: len(group.Tests),
Tests: make([]TestResult, 0, len(group.Tests)),
}
check, err := checker.New(group.Checker)
check, err := checkers.get(ctx, group.Checker)
if err != nil {
j.logger.ErrorContext(ctx, "group has an unknown checker", slog.Any("error", err))
j.logger.ErrorContext(ctx, "group checker is not available", slog.Any("error", err))
result.Outcome = InfrastructureFailure
return result
}
@@ -254,7 +265,8 @@ func (j *Judge) evaluateTest(
run, err := j.executor.Run(ctx, sandbox.Spec{
Argv: language.Run,
Stdin: []byte(test.Input),
BoxDir: box.Dir(),
Mounts: box.Mounts(false),
Env: language.RunEnv,
}, sandbox.Limits{
CPUTime: limits.TimeLimit,
WallTime: wallTimeLimit(limits.TimeLimit),
+136 -12
View File
@@ -6,7 +6,9 @@ import (
"errors"
"log/slog"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
@@ -14,18 +16,23 @@ import (
"lincodex/runner/internal/sandbox"
)
// scriptedExecutor answers runs from a script keyed by the stdin of a test;
// the compile step has no stdin.
// scriptedExecutor answers test runs from a script keyed by the stdin of a
// test, compile steps from compileResults in order, and custom checker runs
// from checkerExits keyed by the actual output the checker reads.
type scriptedExecutor struct {
root string
results map[string]sandbox.Result
errs map[string]error
runs []string
boxes []string
root string
results map[string]sandbox.Result
errs map[string]error
compileResults []sandbox.Result
checkerExits map[string]int
runs []string
compileSteps [][]string
checkerRuns int
boxes []string
}
func (e *scriptedExecutor) NewBox(fileName string, content []byte) (*sandbox.Box, error) {
box, err := sandbox.CreateBox(e.root, fileName, content)
box, err := sandbox.CreateBox(e.root, fileName, content, sandbox.Owner{UID: -1, GID: -1})
if err == nil {
e.boxes = append(e.boxes, box.Dir())
}
@@ -33,6 +40,19 @@ func (e *scriptedExecutor) NewBox(fileName string, content []byte) (*sandbox.Box
}
func (e *scriptedExecutor) Run(_ context.Context, spec sandbox.Spec, _ sandbox.Limits) (sandbox.Result, error) {
for _, mount := range spec.Mounts {
if mount.Target == sandbox.CheckPath {
return e.runChecker(mount)
}
if mount.Target == sandbox.OutPath && mount.Writable {
index := len(e.compileSteps)
e.compileSteps = append(e.compileSteps, spec.Argv)
if index < len(e.compileResults) {
return e.compileResults[index], nil
}
return sandbox.Result{}, nil
}
}
key := string(spec.Stdin)
e.runs = append(e.runs, key)
if err := e.errs[key]; err != nil {
@@ -44,9 +64,22 @@ func (e *scriptedExecutor) Run(_ context.Context, spec sandbox.Spec, _ sandbox.L
return sandbox.Result{}, nil
}
func (e *scriptedExecutor) runChecker(mount sandbox.Mount) (sandbox.Result, error) {
e.checkerRuns++
actual, err := os.ReadFile(filepath.Join(mount.Source, "actual"))
if err != nil {
return sandbox.Result{}, err
}
exit, ok := e.checkerExits[string(actual)]
if !ok {
exit = 3
}
return sandbox.Result{ExitCode: exit}, nil
}
func newScripted(t *testing.T) *scriptedExecutor {
t.Helper()
return &scriptedExecutor{root: t.TempDir(), results: map[string]sandbox.Result{}, errs: map[string]error{}}
return &scriptedExecutor{root: t.TempDir(), results: map[string]sandbox.Result{}, errs: map[string]error{}, checkerExits: map[string]int{}}
}
func output(text string) sandbox.Result {
@@ -157,14 +190,14 @@ func TestRunReportsCompileErrorsWithoutRunningTests(t *testing.T) {
t.Parallel()
executor := newScripted(t)
executor.results[""] = sandbox.Result{ExitCode: 1, Stderr: []byte("SyntaxError: invalid syntax\n")}
executor.compileResults = []sandbox.Result{{ExitCode: 1, Stderr: []byte("SyntaxError: invalid syntax\n")}}
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
if result.Outcome != CompileError || result.Compile.Diagnostic != "SyntaxError: invalid syntax\n" {
t.Fatalf("result = %+v, want compile_error with the diagnostic", result)
}
if len(executor.runs) != 1 {
t.Fatalf("runs = %q, want only the compile step", executor.runs)
if len(executor.runs) != 0 || len(executor.compileSteps) != 1 {
t.Fatalf("runs = %q after %d compile steps, want only the compile step", executor.runs, len(executor.compileSteps))
}
for _, group := range result.Groups {
if group.Outcome != CompileError || len(group.Tests) != 0 || group.Total != 2 {
@@ -210,3 +243,94 @@ func assertBoxesRemoved(t *testing.T, executor *scriptedExecutor) {
}
}
}
func goRequest(groups ...Group) Request {
return Request{
Language: "go",
Source: "package main\nfunc main() {}\n",
Limits: Limits{TimeLimit: time.Second, MemoryBytes: 64 << 20, OutputBytes: 64 << 10},
Groups: groups,
}
}
func TestGoCompilesAndLinksBeforeTheTests(t *testing.T) {
t.Parallel()
executor := newScripted(t)
executor.results["1"] = output("1\n")
group := Group{ID: "public", Visibility: Public, Checker: checker.Spec{Kind: checker.Exact}, Tests: []Test{{ID: "t1", Input: "1", ExpectedOutput: "1\n"}}}
result := New(executor, discardLogger(), Go("/usr/local/lib/lincodex-runner/go")).Run(t.Context(), goRequest(group))
if result.Outcome != Accepted || len(executor.compileSteps) != 2 {
t.Fatalf("result %+v after %d compile steps, want accepted after compile and link", result, len(executor.compileSteps))
}
if !strings.HasSuffix(executor.compileSteps[0][0], "/compile") || !strings.HasSuffix(executor.compileSteps[1][0], "/link") {
t.Fatalf("compile steps = %q", executor.compileSteps)
}
}
func TestGoCompileErrorRunsNoTest(t *testing.T) {
t.Parallel()
for _, failing := range []int{0, 1} {
executor := newScripted(t)
executor.compileResults = make([]sandbox.Result, failing+1)
executor.compileResults[failing] = sandbox.Result{ExitCode: 2, Stderr: []byte("main.go:2:14: declared and not used: x\n")}
group := Group{ID: "hidden-1", Visibility: Hidden, Checker: checker.Spec{Kind: checker.Exact}, Tests: []Test{{ID: "t1", Input: "1", ExpectedOutput: "1"}}}
result := New(executor, discardLogger(), Go("/go")).Run(t.Context(), goRequest(group))
if result.Outcome != CompileError || !strings.Contains(result.Compile.Diagnostic, "declared and not used") {
t.Fatalf("step %d: result %+v, want compile_error with the diagnostic", failing, result)
}
if len(executor.runs) != 0 || len(result.Groups[0].Tests) != 0 || result.Groups[0].Outcome != CompileError {
t.Fatalf("step %d: tests ran after a compile error: %q", failing, executor.runs)
}
}
}
func TestCustomCheckerDecidesByExitStatusAndIsCompiledOnce(t *testing.T) {
t.Parallel()
executor := newScripted(t)
executor.results["a"] = output("good\n")
executor.results["b"] = output("bad\n")
executor.checkerExits["good\n"] = 0
executor.checkerExits["bad\n"] = 1
custom := checker.Spec{Kind: checker.Custom, Program: &checker.Program{Language: "python3", Source: "import sys\n"}}
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), Request{
Language: "python3",
Source: "print('x')",
Limits: Limits{TimeLimit: time.Second, MemoryBytes: 64 << 20, OutputBytes: 64 << 10},
Groups: []Group{
{ID: "public", Visibility: Public, Checker: custom, Tests: []Test{{ID: "t1", Input: "a", ExpectedOutput: "e"}}},
{ID: "hidden-1", Visibility: Hidden, Checker: custom, Tests: []Test{{ID: "t1", Input: "b", ExpectedOutput: "e"}}},
},
})
if result.Groups[0].Outcome != Accepted || result.Groups[1].Outcome != WrongAnswer {
t.Fatalf("groups = %+v, want accepted then wrong_answer", result.Groups)
}
// One syntax check for the solution and one for the shared checker.
if len(executor.compileSteps) != 2 || executor.checkerRuns != 2 {
t.Fatalf("compile steps %d, checker runs %d; want 2 and 2", len(executor.compileSteps), executor.checkerRuns)
}
assertBoxesRemoved(t, executor)
}
func TestFailingCustomCheckerIsAnInfrastructureFailure(t *testing.T) {
t.Parallel()
executor := newScripted(t)
executor.results["a"] = output("unknown\n")
custom := checker.Spec{Kind: checker.Custom, Program: &checker.Program{Language: "python3", Source: "raise SystemExit(3)\n"}}
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), Request{
Language: "python3",
Source: "print('x')",
Limits: Limits{TimeLimit: time.Second, MemoryBytes: 64 << 20, OutputBytes: 64 << 10},
Groups: []Group{{ID: "public", Visibility: Public, Checker: custom, Tests: []Test{{ID: "t1", Input: "a", ExpectedOutput: "e"}}}},
})
if result.Outcome != InfrastructureFailure {
t.Fatalf("outcome = %s, want infrastructure_failure", result.Outcome)
}
assertBoxesRemoved(t, executor)
}
+72 -9
View File
@@ -1,22 +1,36 @@
package judge
import (
"path/filepath"
"time"
"lincodex/runner/internal/sandbox"
)
// Language describes how the sandbox checks and runs a source file.
// Step is one command of a compile phase.
type Step struct {
Argv []string
// WorkDir is the working directory in the jail; empty means the default.
WorkDir string
}
// Language describes how the sandbox builds and runs a source file. Every
// step runs in its own jail: compile steps may write sandbox.OutPath, test
// runs see it read-only.
type Language struct {
ID string
// SourceFile is the file name of the source inside sandbox.BoxPath.
SourceFile string
// Compile is the optional compile or syntax check command.
Compile []string
// CompileLimits bound the compile step; they do not depend on the run.
// Compile is the optional compile phase; the first failing step ends it.
Compile []Step
// CompileLimits bound every compile step; they do not depend on the run.
CompileLimits sandbox.Limits
CompileEnv []string
// Run is the command of every test; the test input is its stdin.
Run []string
Run []string
RunEnv []string
// Requires lists host files the language needs; startup checks them.
Requires []string
}
// pythonSyntaxCheck compiles the source without running it and prints only
@@ -38,7 +52,7 @@ const (
pythonCompileCPU = 5 * time.Second
pythonCompileWall = 10 * time.Second
pythonCompileMemory = 256 << 20
pythonCompileOutput = 64 << 10
compileOutput = 64 << 10
)
// Python3 returns the Python 3 language for the interpreter at path. The
@@ -50,13 +64,62 @@ func Python3(interpreter string) Language {
return Language{
ID: "python3",
SourceFile: "main.py",
Compile: []string{interpreter, "-I", "-B", "-c", pythonSyntaxCheck, source},
Compile: []Step{{Argv: []string{interpreter, "-I", "-B", "-c", pythonSyntaxCheck, source}}},
CompileLimits: sandbox.Limits{
CPUTime: pythonCompileCPU,
WallTime: pythonCompileWall,
MemoryBytes: pythonCompileMemory,
OutputBytes: pythonCompileOutput,
OutputBytes: compileOutput,
},
Run: []string{interpreter, "-I", "-B", source},
Run: []string{interpreter, "-I", "-B", source},
Requires: []string{interpreter},
}
}
// Limits of the Go compile and link steps: the compiler and the linker of
// one file with the prebuilt standard library need well under a second and
// a few hundred MiB; the binary may be tens of MiB.
const (
goCompileCPU = 20 * time.Second
goCompileWall = 40 * time.Second
goCompileMemory = 768 << 20
goCompileFileSize = 64 << 20
)
// goEnv keeps the Go runtime on one processor, which matches the one-CPU
// cgroup quota and bounds the number of runtime threads.
var goEnv = []string{"GOMAXPROCS=1", "TMPDIR=" + sandbox.ScratchPath}
// Go returns the Go language for the tool directory built into the runner
// image: the compile and link tools and an importcfg that maps every
// standard library package to a prebuilt archive. The build therefore needs
// no Go build cache and no network, can import only the standard library,
// and has no cgo.
func Go(toolDir string) Language {
compiler := filepath.Join(toolDir, "compile")
linker := filepath.Join(toolDir, "link")
importcfg := filepath.Join(toolDir, "importcfg")
archive := sandbox.OutPath + "/main.a"
binary := sandbox.OutPath + "/main"
return Language{
ID: "go",
SourceFile: "main.go",
Compile: []Step{
// Compiling from the box with a relative path keeps host-free
// file names such as main.go:3:2 in diagnostics.
{Argv: []string{compiler, "-o", archive, "-p", "main", "-complete", "-pack", "-importcfg", importcfg, "main.go"}, WorkDir: sandbox.BoxPath},
{Argv: []string{linker, "-o", binary, "-importcfg", importcfg, "-buildmode=exe", "-s", "-w", archive}},
},
CompileLimits: sandbox.Limits{
CPUTime: goCompileCPU,
WallTime: goCompileWall,
MemoryBytes: goCompileMemory,
OutputBytes: compileOutput,
FileSizeBytes: goCompileFileSize,
},
CompileEnv: goEnv,
Run: []string{binary},
RunEnv: goEnv,
Requires: []string{compiler, linker, importcfg},
}
}