feat(practice): add the code runner port and its TLS client
This commit is contained in:
1 parent
53a125f2b5
commit
facc1789b1
24 files changed
+3374
-6
No files matched your search
@@ -0,0 +1,516 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package outbound_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const sourceMarker = "source-marker-7f3a"
|
||||
|
||||
func validCodeRunRequest() outbound.CodeRunRequest {
|
||||
return outbound.CodeRunRequest{
|
||||
Key: outbound.CodeRunKey{AttemptItemID: uuid.New(), SubmissionID: uuid.New()},
|
||||
Language: outbound.CodeLanguageGo,
|
||||
Source: "package main // " + sourceMarker,
|
||||
Limits: outbound.CodeRunLimits{TimeLimitMs: 1000, MemoryLimitMB: 128, OutputLimitKB: 64},
|
||||
Groups: []outbound.CodeTestGroup{
|
||||
{
|
||||
ID: "public", Visibility: outbound.CodeTestPublic,
|
||||
Checker: outbound.CodeChecker{Kind: outbound.CodeCheckerExact},
|
||||
Tests: []outbound.CodeTest{{ID: "1", Input: "1\n", ExpectedOutput: "2\n"}},
|
||||
},
|
||||
{
|
||||
ID: "hidden-1", Visibility: outbound.CodeTestHidden,
|
||||
Checker: outbound.CodeChecker{Kind: outbound.CodeCheckerNumbers, AbsTolerance: 1e-6},
|
||||
Tests: []outbound.CodeTest{{ID: "1", Input: "hidden-input-marker\n", ExpectedOutput: "hidden-output-marker\n"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeRunRequestValidateAcceptsAContractRequest(t *testing.T) {
|
||||
if err := validCodeRunRequest().Validate(); err != nil {
|
||||
t.Fatalf("Validate() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeRunRequestValidateRejectsWhatTheRunnerRejects(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*outbound.CodeRunRequest)
|
||||
}{
|
||||
{"no attempt item", func(r *outbound.CodeRunRequest) { r.Key.AttemptItemID = uuid.Nil }},
|
||||
{"no submission", func(r *outbound.CodeRunRequest) { r.Key.SubmissionID = uuid.Nil }},
|
||||
{"unknown language", func(r *outbound.CodeRunRequest) { r.Language = "java" }},
|
||||
{"empty source", func(r *outbound.CodeRunRequest) { r.Source = " \n" }},
|
||||
{"source above 64 KiB", func(r *outbound.CodeRunRequest) { r.Source = strings.Repeat("a", 65537) }},
|
||||
{"source not UTF-8", func(r *outbound.CodeRunRequest) { r.Source = "\xff\xfe" }},
|
||||
{"source with NUL", func(r *outbound.CodeRunRequest) { r.Source = "a\x00b" }},
|
||||
{"time limit below range", func(r *outbound.CodeRunRequest) { r.Limits.TimeLimitMs = 99 }},
|
||||
{"time limit above range", func(r *outbound.CodeRunRequest) { r.Limits.TimeLimitMs = 10001 }},
|
||||
{"memory below range", func(r *outbound.CodeRunRequest) { r.Limits.MemoryLimitMB = 31 }},
|
||||
{"memory above range", func(r *outbound.CodeRunRequest) { r.Limits.MemoryLimitMB = 513 }},
|
||||
{"output below range", func(r *outbound.CodeRunRequest) { r.Limits.OutputLimitKB = 0 }},
|
||||
{"output above range", func(r *outbound.CodeRunRequest) { r.Limits.OutputLimitKB = 1025 }},
|
||||
{"no groups", func(r *outbound.CodeRunRequest) { r.Groups = nil }},
|
||||
{"five groups", func(r *outbound.CodeRunRequest) {
|
||||
for index := range 3 {
|
||||
group := r.Groups[0]
|
||||
group.ID = fmt.Sprintf("extra-%d", index)
|
||||
r.Groups = append(r.Groups, group)
|
||||
}
|
||||
}},
|
||||
{"duplicate group ID", func(r *outbound.CodeRunRequest) { r.Groups[1].ID = r.Groups[0].ID }},
|
||||
{"group ID with capitals", func(r *outbound.CodeRunRequest) { r.Groups[0].ID = "Public" }},
|
||||
{"unknown visibility", func(r *outbound.CodeRunRequest) { r.Groups[0].Visibility = "secret" }},
|
||||
{"group without tests", func(r *outbound.CodeRunRequest) { r.Groups[0].Tests = nil }},
|
||||
{"fifty one tests", func(r *outbound.CodeRunRequest) {
|
||||
r.Limits.TimeLimitMs = 100
|
||||
r.Groups[0].Tests = nil
|
||||
for index := range 51 {
|
||||
r.Groups[0].Tests = append(r.Groups[0].Tests, outbound.CodeTest{ID: fmt.Sprintf("t%d", index)})
|
||||
}
|
||||
}},
|
||||
{"duplicate test ID", func(r *outbound.CodeRunRequest) {
|
||||
r.Groups[0].Tests = append(r.Groups[0].Tests, r.Groups[0].Tests[0])
|
||||
}},
|
||||
{"test input too large", func(r *outbound.CodeRunRequest) { r.Groups[0].Tests[0].Input = strings.Repeat("a", 262145) }},
|
||||
{"expected output too large", func(r *outbound.CodeRunRequest) { r.Groups[0].Tests[0].ExpectedOutput = strings.Repeat("a", 262145) }},
|
||||
{"CPU budget above 300 s", func(r *outbound.CodeRunRequest) {
|
||||
r.Limits.TimeLimitMs = 10000
|
||||
for index := range 30 {
|
||||
r.Groups[0].Tests = append(r.Groups[0].Tests, outbound.CodeTest{ID: fmt.Sprintf("t%d", index+2)})
|
||||
}
|
||||
}},
|
||||
{"unknown checker", func(r *outbound.CodeRunRequest) { r.Groups[0].Checker.Kind = "regex" }},
|
||||
{"exact with tolerance", func(r *outbound.CodeRunRequest) { r.Groups[0].Checker.AbsTolerance = 1 }},
|
||||
{"numbers without tolerance", func(r *outbound.CodeRunRequest) { r.Groups[1].Checker.AbsTolerance = 0 }},
|
||||
{"numbers with NaN tolerance", func(r *outbound.CodeRunRequest) { r.Groups[1].Checker.AbsTolerance = math.NaN() }},
|
||||
{"numbers with negative tolerance", func(r *outbound.CodeRunRequest) { r.Groups[1].Checker.RelTolerance = -1 }},
|
||||
{"numbers with relative tolerance above 1", func(r *outbound.CodeRunRequest) { r.Groups[1].Checker.RelTolerance = 2 }},
|
||||
{"numbers with a program", func(r *outbound.CodeRunRequest) {
|
||||
r.Groups[1].Checker.Program = &outbound.CodeCheckerProgram{Language: outbound.CodeLanguageGo, Source: "package main"}
|
||||
}},
|
||||
{"custom without program", func(r *outbound.CodeRunRequest) {
|
||||
r.Groups[0].Checker = outbound.CodeChecker{Kind: outbound.CodeCheckerCustom}
|
||||
}},
|
||||
{"custom with tolerance", func(r *outbound.CodeRunRequest) {
|
||||
r.Groups[0].Checker = outbound.CodeChecker{
|
||||
Kind: outbound.CodeCheckerCustom, AbsTolerance: 1,
|
||||
Program: &outbound.CodeCheckerProgram{Language: outbound.CodeLanguageGo, Source: "package main"},
|
||||
}
|
||||
}},
|
||||
{"custom with empty program", func(r *outbound.CodeRunRequest) {
|
||||
r.Groups[0].Checker = outbound.CodeChecker{Kind: outbound.CodeCheckerCustom, Program: &outbound.CodeCheckerProgram{Language: outbound.CodeLanguageGo}}
|
||||
}},
|
||||
{"payload above the runner limit", func(r *outbound.CodeRunRequest) {
|
||||
r.Limits.TimeLimitMs = 100
|
||||
r.Groups = r.Groups[:1]
|
||||
r.Groups[0].Tests = nil
|
||||
for index := range 50 {
|
||||
r.Groups[0].Tests = append(r.Groups[0].Tests, outbound.CodeTest{
|
||||
ID: fmt.Sprintf("t%d", index), Input: strings.Repeat("a", 262144), ExpectedOutput: strings.Repeat("b", 262144),
|
||||
})
|
||||
}
|
||||
}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
request := validCodeRunRequest()
|
||||
test.change(&request)
|
||||
|
||||
err := request.Validate()
|
||||
|
||||
if !errors.Is(err, outbound.ErrInvalidCodeRunRequest) {
|
||||
t.Fatalf("Validate() error = %v, want ErrInvalidCodeRunRequest", err)
|
||||
}
|
||||
for _, marker := range []string{sourceMarker, "hidden-input-marker", "hidden-output-marker"} {
|
||||
if strings.Contains(err.Error(), marker) {
|
||||
t.Fatalf("Validate() error exposes %q: %v", marker, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeRunRequestIsRedactedInEveryRendering(t *testing.T) {
|
||||
request := validCodeRunRequest()
|
||||
renderings := []string{
|
||||
request.String(), request.GoString(), request.LogValue().String(),
|
||||
fmt.Sprintf("%v", request), fmt.Sprintf("%+v", request), fmt.Sprintf("%#v", request), fmt.Sprint(request),
|
||||
slog.Group("run", slog.Any("request", request)).Value.String(),
|
||||
}
|
||||
for _, rendered := range renderings {
|
||||
for _, marker := range []string{sourceMarker, "hidden-input-marker", "hidden-output-marker", request.Key.AttemptItemID.String()} {
|
||||
if strings.Contains(rendered, marker) {
|
||||
t.Fatalf("rendering %q exposes %q", rendered, marker)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeRunnerFailuresShareTheUnavailableUmbrella(t *testing.T) {
|
||||
for name, err := range map[string]error{
|
||||
"disabled": outbound.ErrCodeRunnerDisabled,
|
||||
"unauthorized": outbound.ErrCodeRunnerUnauthorized,
|
||||
"bad response": outbound.ErrCodeRunnerBadResponse,
|
||||
"infrastructure failure": outbound.ErrCodeRunnerInfrastructureFailure,
|
||||
} {
|
||||
if !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("%s is not under ErrCodeRunnerUnavailable", name)
|
||||
}
|
||||
}
|
||||
for name, err := range map[string]error{
|
||||
"invalid request": outbound.ErrInvalidCodeRunRequest,
|
||||
"not found": outbound.ErrCodeRunNotFound,
|
||||
"key reused": outbound.ErrCodeRunKeyReused,
|
||||
} {
|
||||
if errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("%s must not read as an unavailable runner", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user