feat(runner): add the own code runner contract, client and nsjail service
This commit is contained in:
1 parent
5e1db37746
commit
cdf6bcbb91
109 files changed
+24084
-28
No files matched your search
@@ -0,0 +1,347 @@
|
||||
// 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"
|
||||
"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)
|
||||
}
|
||||
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)
|
||||
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 step. 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
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
func (j *Judge) evaluateGroup(ctx context.Context, language Language, box *sandbox.Box, limits Limits, group Group) GroupResult {
|
||||
result := GroupResult{
|
||||
ID: group.ID,
|
||||
Visibility: group.Visibility,
|
||||
Outcome: Accepted,
|
||||
Total: len(group.Tests),
|
||||
Tests: make([]TestResult, 0, len(group.Tests)),
|
||||
}
|
||||
check, err := checker.New(group.Checker)
|
||||
if err != nil {
|
||||
j.logger.ErrorContext(ctx, "group has an unknown checker", 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),
|
||||
BoxDir: box.Dir(),
|
||||
}, 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)
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package judge
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/runner/internal/checker"
|
||||
"lincodex/runner/internal/sandbox"
|
||||
)
|
||||
|
||||
// scriptedExecutor answers runs from a script keyed by the stdin of a test;
|
||||
// the compile step has no stdin.
|
||||
type scriptedExecutor struct {
|
||||
root string
|
||||
results map[string]sandbox.Result
|
||||
errs map[string]error
|
||||
runs []string
|
||||
boxes []string
|
||||
}
|
||||
|
||||
func (e *scriptedExecutor) NewBox(fileName string, content []byte) (*sandbox.Box, error) {
|
||||
box, err := sandbox.CreateBox(e.root, fileName, content)
|
||||
if err == nil {
|
||||
e.boxes = append(e.boxes, box.Dir())
|
||||
}
|
||||
return box, err
|
||||
}
|
||||
|
||||
func (e *scriptedExecutor) Run(_ context.Context, spec sandbox.Spec, _ sandbox.Limits) (sandbox.Result, error) {
|
||||
key := string(spec.Stdin)
|
||||
e.runs = append(e.runs, key)
|
||||
if err := e.errs[key]; err != nil {
|
||||
return sandbox.Result{}, err
|
||||
}
|
||||
if result, ok := e.results[key]; ok {
|
||||
return result, nil
|
||||
}
|
||||
return sandbox.Result{}, nil
|
||||
}
|
||||
|
||||
func newScripted(t *testing.T) *scriptedExecutor {
|
||||
t.Helper()
|
||||
return &scriptedExecutor{root: t.TempDir(), results: map[string]sandbox.Result{}, errs: map[string]error{}}
|
||||
}
|
||||
|
||||
func output(text string) sandbox.Result {
|
||||
return sandbox.Result{Stdout: []byte(text), CPUTime: 20 * time.Millisecond, WallTime: 30 * time.Millisecond, PeakMemoryKB: 9000}
|
||||
}
|
||||
|
||||
func discardLogger() *slog.Logger {
|
||||
return slog.New(slog.DiscardHandler)
|
||||
}
|
||||
|
||||
func twoGroupRequest() Request {
|
||||
return Request{
|
||||
Language: "python3",
|
||||
Source: "print(sum(map(int, input().split())))",
|
||||
Limits: Limits{TimeLimit: time.Second, MemoryBytes: 64 << 20, OutputBytes: 64 << 10},
|
||||
Groups: []Group{
|
||||
{ID: "public", Visibility: Public, Checker: checker.Spec{Kind: checker.Exact}, Tests: []Test{
|
||||
{ID: "t1", Input: "1 2", ExpectedOutput: "3\n"},
|
||||
{ID: "t2", Input: "2 2", ExpectedOutput: "4\n"},
|
||||
}},
|
||||
{ID: "hidden-1", Visibility: Hidden, Checker: checker.Spec{Kind: checker.Tokens}, Tests: []Test{
|
||||
{ID: "t1", Input: "5 5", ExpectedOutput: "10"},
|
||||
{ID: "t2", Input: "6 6", ExpectedOutput: "12"},
|
||||
}},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunAcceptsCorrectOutputAndRecordsUsage(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
executor := newScripted(t)
|
||||
executor.results["1 2"] = output("3\n")
|
||||
executor.results["2 2"] = output("4")
|
||||
executor.results["5 5"] = output("10\n")
|
||||
executor.results["6 6"] = output(" 12 ")
|
||||
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
|
||||
|
||||
if result.Outcome != Accepted || result.Compile == nil || result.Compile.Outcome != Accepted {
|
||||
t.Fatalf("result = %+v, want accepted with a passed compile step", result)
|
||||
}
|
||||
for _, group := range result.Groups {
|
||||
if group.Outcome != Accepted || group.Passed != 2 || group.Total != 2 {
|
||||
t.Fatalf("group %+v, want 2 of 2 accepted", group)
|
||||
}
|
||||
if group.MaxCPUTime != 20*time.Millisecond || group.MaxMemoryKB != 9000 {
|
||||
t.Fatalf("group usage %v %d, want the recorded usage", group.MaxCPUTime, group.MaxMemoryKB)
|
||||
}
|
||||
}
|
||||
assertBoxesRemoved(t, executor)
|
||||
}
|
||||
|
||||
func TestRunStopsAGroupAtItsFirstFailureAndKeepsDiagnosticsPublicOnly(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
executor := newScripted(t)
|
||||
crash := sandbox.Result{ExitCode: 1, Stderr: []byte("Traceback: ValueError")}
|
||||
executor.results["1 2"] = crash
|
||||
executor.results["5 5"] = crash
|
||||
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
|
||||
|
||||
if result.Outcome != RuntimeError {
|
||||
t.Fatalf("outcome = %s, want runtime_error", result.Outcome)
|
||||
}
|
||||
public, hidden := result.Groups[0], result.Groups[1]
|
||||
if len(public.Tests) != 1 || public.Passed != 0 || public.Tests[0].Diagnostic != "Traceback: ValueError" {
|
||||
t.Fatalf("public group %+v, want one failed test with its diagnostic", public)
|
||||
}
|
||||
if len(hidden.Tests) != 1 || hidden.Tests[0].Diagnostic != "" {
|
||||
t.Fatalf("hidden group %+v, want one failed test without a diagnostic", hidden)
|
||||
}
|
||||
if slices.Contains(executor.runs, "2 2") || slices.Contains(executor.runs, "6 6") {
|
||||
t.Fatalf("runs %q include tests after a failure", executor.runs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunMapsSandboxTerminationsToOutcomes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
result sandbox.Result
|
||||
outcome Outcome
|
||||
}{
|
||||
{"cpu time", sandbox.Result{Termination: sandbox.TerminationCPUTime, Signal: 9}, TimeLimitExceeded},
|
||||
{"wall time", sandbox.Result{Termination: sandbox.TerminationWallTime, Signal: 9}, TimeLimitExceeded},
|
||||
{"memory", sandbox.Result{Termination: sandbox.TerminationMemory, Signal: 9}, MemoryLimitExceeded},
|
||||
{"output", sandbox.Result{Termination: sandbox.TerminationOutput, Signal: 9, Stdout: []byte("3\n")}, OutputLimitExceeded},
|
||||
{"processes", sandbox.Result{Termination: sandbox.TerminationProcesses, ExitCode: 1}, RuntimeError},
|
||||
{"signal", sandbox.Result{Signal: 31, ExitCode: -1}, RuntimeError},
|
||||
{"wrong answer", output("4\n"), WrongAnswer},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
executor := newScripted(t)
|
||||
executor.results["1 2"] = tc.result
|
||||
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
|
||||
got := result.Groups[0].Tests[0]
|
||||
if got.Outcome != tc.outcome || got.Limit != tc.result.Termination {
|
||||
t.Fatalf("test result %+v, want %s with limit %q", got, tc.outcome, tc.result.Termination)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunReportsCompileErrorsWithoutRunningTests(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
executor := newScripted(t)
|
||||
executor.results[""] = 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)
|
||||
}
|
||||
for _, group := range result.Groups {
|
||||
if group.Outcome != CompileError || len(group.Tests) != 0 || group.Total != 2 {
|
||||
t.Fatalf("group %+v, want compile_error without tests", group)
|
||||
}
|
||||
}
|
||||
assertBoxesRemoved(t, executor)
|
||||
}
|
||||
|
||||
func TestRunTurnsSandboxFailuresIntoInfrastructureFailure(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
executor := newScripted(t)
|
||||
executor.results["1 2"] = output("3\n")
|
||||
executor.errs["2 2"] = errors.New("nsjail failed")
|
||||
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
|
||||
|
||||
if result.Outcome != InfrastructureFailure {
|
||||
t.Fatalf("outcome = %s, want infrastructure_failure", result.Outcome)
|
||||
}
|
||||
for _, group := range result.Groups {
|
||||
if group.Outcome != InfrastructureFailure || len(group.Tests) != 0 {
|
||||
t.Fatalf("group %+v, want infrastructure_failure without partial tests", group)
|
||||
}
|
||||
}
|
||||
assertBoxesRemoved(t, executor)
|
||||
}
|
||||
|
||||
func TestExcerptKeepsTheTailAsValidUTF8(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
text := append(bytes.Repeat([]byte("ж"), 10), 0xff, 'x')
|
||||
if got := excerpt(text, 7); got != "ж\uFFFDx" {
|
||||
t.Fatalf("excerpt = %q, want the last whole runes within 7 bytes", got)
|
||||
}
|
||||
}
|
||||
|
||||
func assertBoxesRemoved(t *testing.T, executor *scriptedExecutor) {
|
||||
t.Helper()
|
||||
for _, dir := range executor.boxes {
|
||||
if _, err := os.Stat(dir); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("box %s still exists: %v", dir, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package judge
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"lincodex/runner/internal/sandbox"
|
||||
)
|
||||
|
||||
// Language describes how the sandbox checks and runs a source file.
|
||||
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.
|
||||
CompileLimits sandbox.Limits
|
||||
// Run is the command of every test; the test input is its stdin.
|
||||
Run []string
|
||||
}
|
||||
|
||||
// pythonSyntaxCheck compiles the source without running it and prints only
|
||||
// the exception line, so that a syntax error is a compile_error with a short
|
||||
// message. compile() never executes the program.
|
||||
const pythonSyntaxCheck = `import sys, traceback
|
||||
path = sys.argv[1]
|
||||
try:
|
||||
with open(path, "rb") as stream:
|
||||
compile(stream.read(), "main.py", "exec", dont_inherit=True)
|
||||
except (SyntaxError, ValueError) as error:
|
||||
sys.stderr.write("".join(traceback.format_exception_only(type(error), error)))
|
||||
sys.exit(1)
|
||||
`
|
||||
|
||||
// Limits of the Python syntax check. A 64 KiB source compiles far below
|
||||
// them; a pathological source fails with compile_error.
|
||||
const (
|
||||
pythonCompileCPU = 5 * time.Second
|
||||
pythonCompileWall = 10 * time.Second
|
||||
pythonCompileMemory = 256 << 20
|
||||
pythonCompileOutput = 64 << 10
|
||||
)
|
||||
|
||||
// Python3 returns the Python 3 language for the interpreter at path. The
|
||||
// interpreter runs in isolated mode (-I: no environment variables, no user
|
||||
// site directory, no script directory on sys.path) and never writes
|
||||
// bytecode (-B).
|
||||
func Python3(interpreter string) Language {
|
||||
source := sandbox.BoxPath + "/main.py"
|
||||
return Language{
|
||||
ID: "python3",
|
||||
SourceFile: "main.py",
|
||||
Compile: []string{interpreter, "-I", "-B", "-c", pythonSyntaxCheck, source},
|
||||
CompileLimits: sandbox.Limits{
|
||||
CPUTime: pythonCompileCPU,
|
||||
WallTime: pythonCompileWall,
|
||||
MemoryBytes: pythonCompileMemory,
|
||||
OutputBytes: pythonCompileOutput,
|
||||
},
|
||||
Run: []string{interpreter, "-I", "-B", source},
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user