feat(runner): compile Go and check answers per test group
This commit is contained in:
1 parent
e95c681165
commit
afee564bf4
61 files changed
+2592
-143
No files matched your search
+25
-2
@@ -19,16 +19,39 @@ RUN go mod download
|
||||
COPY . ./
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -trimpath -ldflags="-s -w" -o /out/lincodex-runner ./cmd/runner
|
||||
|
||||
# The Go toolchain for candidate code: the compile and link tools and every
|
||||
# standard library package prebuilt without cgo, with an importcfg that maps
|
||||
# import paths to the archives. A build in the jail then needs no build
|
||||
# cache, no module download, and nothing writable outside its output.
|
||||
FROM ${GO_IMAGE} AS gostd
|
||||
|
||||
ENV GOTOOLCHAIN=local
|
||||
ARG GO_TOOL_DIR=/usr/local/lib/lincodex-runner/go
|
||||
RUN set -eu; \
|
||||
out=/out/go; \
|
||||
mkdir -p "$out/std"; \
|
||||
CGO_ENABLED=0 go list -trimpath -export -f '{{if .Export}}{{.ImportPath}} {{.Export}}{{end}}' std > /tmp/std.txt; \
|
||||
while read -r package archive; do \
|
||||
target="$out/std/$package.a"; \
|
||||
mkdir -p "$(dirname "$target")"; \
|
||||
cp "$archive" "$target"; \
|
||||
printf 'packagefile %s=%s/std/%s.a\n' "$package" "$GO_TOOL_DIR" "$package" >> "$out/importcfg"; \
|
||||
done < /tmp/std.txt; \
|
||||
cp "$(go env GOTOOLDIR)/compile" "$(go env GOTOOLDIR)/link" "$out/"
|
||||
|
||||
FROM ${RUNTIME_IMAGE}
|
||||
|
||||
# The runtime is the Python base plus nsjail. Package installers are removed,
|
||||
# so a jailed program finds no pip, and nothing is installed at run time.
|
||||
# The runtime is the Python base plus nsjail and the Go compile tools.
|
||||
# Package installers are removed, so a jailed program finds no pip, and
|
||||
# nothing is installed at run time.
|
||||
RUN apk upgrade --no-cache \
|
||||
&& apk add --no-cache nsjail \
|
||||
&& python -m pip uninstall --yes pip \
|
||||
&& python -c "import ensurepip, shutil; shutil.rmtree(ensurepip.__path__[0])" \
|
||||
&& install -d -m 0711 /var/lib/lincodex-runner/work
|
||||
|
||||
COPY --from=gostd /out/go /usr/local/lib/lincodex-runner/go
|
||||
|
||||
# The binary lives outside /usr and /lib, which are the only host paths
|
||||
# mounted into a jail.
|
||||
COPY --from=build /out/lincodex-runner /opt/lincodex-runner/lincodex-runner
|
||||
|
||||
@@ -14,13 +14,16 @@ COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . ./
|
||||
RUN CGO_ENABLED=0 GOOS=linux go test -c -tags sandbox -o /out/isolation.test ./internal/isolationtest
|
||||
RUN CGO_ENABLED=0 GOOS=linux go test -c -tags sandbox -o /out/isolation.test ./internal/isolationtest \
|
||||
&& CGO_ENABLED=0 GOOS=linux go test -c -tags sandbox -o /out/judge.test ./internal/judgetest
|
||||
|
||||
FROM ${RUNNER_IMAGE}
|
||||
|
||||
COPY --from=build /out/isolation.test /opt/lincodex-runner-tests/isolation.test
|
||||
COPY --from=build /out/isolation.test /out/judge.test /opt/lincodex-runner-tests/
|
||||
COPY testdata/hostile /opt/lincodex-runner-tests/testdata/hostile
|
||||
ENV RUNNER_HOSTILE_FIXTURES=/opt/lincodex-runner-tests/testdata/hostile
|
||||
COPY testdata/judge /opt/lincodex-runner-tests/testdata/judge
|
||||
ENV RUNNER_HOSTILE_FIXTURES=/opt/lincodex-runner-tests/testdata/hostile \
|
||||
RUNNER_JUDGE_FIXTURES=/opt/lincodex-runner-tests/testdata/judge
|
||||
|
||||
HEALTHCHECK NONE
|
||||
ENTRYPOINT ["/opt/lincodex-runner-tests/isolation.test", "-test.v", "-test.count=1"]
|
||||
ENTRYPOINT ["/bin/sh", "-c", "set -e; for suite in judge isolation; do /opt/lincodex-runner-tests/$suite.test -test.v -test.count=1; done"]
|
||||
+1
-1
@@ -89,7 +89,7 @@ image: ## Build the runner image for local development
|
||||
test-sandbox: image ## Run the hostile-program isolation tests in a privileged dev container
|
||||
$(DOCKER) build --file Dockerfile.sandbox-test --build-arg RUNNER_IMAGE="$(RUNNER_IMAGE)" --tag "$(SANDBOX_TEST_IMAGE)" .
|
||||
$(DOCKER) run --rm --privileged --cgroupns=private --network=none \
|
||||
--tmpfs /var/lib/lincodex-runner/work:size=64m,mode=0711 \
|
||||
--tmpfs /var/lib/lincodex-runner/work:size=128m,mode=0711,exec \
|
||||
"$(SANDBOX_TEST_IMAGE)"
|
||||
|
||||
.PHONY: check
|
||||
|
||||
+3
-2
@@ -2,12 +2,13 @@
|
||||
|
||||
[Русский](README.md) | English
|
||||
|
||||
A separate Go service that runs untrusted candidate code in nsjail and checks it against public and hidden tests. It currently supports Python 3 and the `exact` and `tokens` checkers. The backend calls it through the internal `api/runner/` contract over TLS with a bearer token; no backend use case calls it yet.
|
||||
A separate Go service that runs untrusted candidate code in nsjail and checks it against public and hidden tests. It supports Python 3 and Go (a separate compile phase with a prebuilt standard library) and the `exact`, `tokens`, `numbers`, and `custom` (a family program in nsjail) checkers. The backend calls it through the internal `api/runner/` contract over TLS with a bearer token; no backend use case calls it yet.
|
||||
|
||||
- `cmd/runner/` is the entry point and the container `healthcheck`.
|
||||
- `internal/sandbox/` holds nsjail, cgroup v2, seccomp, run directories, and stopping on limits.
|
||||
- `internal/judge/` holds languages, the syntax check step, and test and group outcomes.
|
||||
- `internal/checker/` holds the checker interface and the `exact` and `tokens` comparisons.
|
||||
- `internal/checker/` holds the checker interface and the `exact`, `tokens`, and `numbers` comparisons; the custom checker lives in `internal/judge/`.
|
||||
- `internal/judgetest/` and `testdata/judge/` are reference Python and Go solutions with their expected group results.
|
||||
- `internal/jobs/` keeps runs in memory, makes them idempotent by run ID, and bounds concurrent runs.
|
||||
- `internal/server/` is the HTTP API on the generated ogen server (`internal/api/`, from `codegen/ogen.yml`).
|
||||
- `internal/isolationtest/` and `testdata/hostile/` are the isolation tests and the shared hostile programs.
|
||||
|
||||
+3
-2
@@ -2,12 +2,13 @@
|
||||
|
||||
Русский | [English](README.en.md)
|
||||
|
||||
Отдельный Go-сервис, который запускает недоверенный код кандидата в nsjail и проверяет его на публичных и скрытых тестах. Сейчас поддерживается Python 3; checker `exact` и `tokens`. Backend вызывает его по внутреннему контракту `api/runner/` с TLS и bearer-токеном; ни один usecase backend пока не использует его.
|
||||
Отдельный Go-сервис, который запускает недоверенный код кандидата в nsjail и проверяет его на публичных и скрытых тестах. Поддерживаются Python 3 и Go (отдельная фаза компиляции с заранее собранной стандартной библиотекой); checker `exact`, `tokens`, `numbers` и `custom` (программа семейства в nsjail). Backend вызывает его по внутреннему контракту `api/runner/` с TLS и bearer-токеном; ни один usecase backend пока не использует его.
|
||||
|
||||
- `cmd/runner/` - точка входа и `healthcheck` для контейнера.
|
||||
- `internal/sandbox/` - nsjail, cgroup v2, seccomp, рабочие каталоги и остановка по лимитам.
|
||||
- `internal/judge/` - языки, шаг проверки синтаксиса, исходы тестов и групп.
|
||||
- `internal/checker/` - интерфейс checker и сравнения `exact` и `tokens`.
|
||||
- `internal/checker/` - интерфейс checker и сравнения `exact`, `tokens` и `numbers`; custom checker находится в `internal/judge/`.
|
||||
- `internal/judgetest/` и `testdata/judge/` - эталонные решения на Python и Go с ожидаемыми результатами групп.
|
||||
- `internal/jobs/` - прогоны в памяти, идемпотентность по run ID и лимит параллельных прогонов.
|
||||
- `internal/server/` - HTTP API на сгенерированном ogen-сервере (`internal/api/`, из `codegen/ogen.yml`).
|
||||
- `internal/isolationtest/` и `testdata/hostile/` - тесты изоляции и общие враждебные программы.
|
||||
|
||||
@@ -521,8 +521,9 @@ func (s *Server) handleGetRunnerReadyzRequest(args [0]string, argsEscaped bool,
|
||||
// memory for a bounded time after they finish; an ID that was forgotten or lost in a restart starts a
|
||||
// new run. Requests above the configured body limit (8 MiB by default) answer 413 `payload_too_large`.
|
||||
// Semantic rules that the schema cannot express answer 400 `validation_failed`: group IDs are unique
|
||||
// in a run, test IDs are unique in a group, and the number of tests multiplied by
|
||||
// `limits.time_limit_ms` does not exceed 300000.
|
||||
// in a run, test IDs are unique in a group, the number of tests multiplied by `limits.time_limit_ms`
|
||||
// does not exceed 300000, a `numbers` checker has a positive tolerance, a `custom` checker has a
|
||||
// program, and no other kind carries tolerances or a program.
|
||||
//
|
||||
// PUT /v1/runs/{run_id}
|
||||
func (s *Server) handleSubmitRunRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -25,10 +25,31 @@ func (s *Checker) encodeFields(e *jx.Encoder) {
|
||||
e.FieldStart("kind")
|
||||
s.Kind.Encode(e)
|
||||
}
|
||||
{
|
||||
if s.AbsTolerance.Set {
|
||||
e.FieldStart("abs_tolerance")
|
||||
s.AbsTolerance.Encode(e)
|
||||
}
|
||||
}
|
||||
{
|
||||
if s.RelTolerance.Set {
|
||||
e.FieldStart("rel_tolerance")
|
||||
s.RelTolerance.Encode(e)
|
||||
}
|
||||
}
|
||||
{
|
||||
if s.Program.Set {
|
||||
e.FieldStart("program")
|
||||
s.Program.Encode(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfChecker = [1]string{
|
||||
var jsonFieldsNameOfChecker = [4]string{
|
||||
0: "kind",
|
||||
1: "abs_tolerance",
|
||||
2: "rel_tolerance",
|
||||
3: "program",
|
||||
}
|
||||
|
||||
// Decode decodes Checker from json.
|
||||
@@ -50,6 +71,36 @@ func (s *Checker) Decode(d *jx.Decoder) error {
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"kind\"")
|
||||
}
|
||||
case "abs_tolerance":
|
||||
if err := func() error {
|
||||
s.AbsTolerance.Reset()
|
||||
if err := s.AbsTolerance.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"abs_tolerance\"")
|
||||
}
|
||||
case "rel_tolerance":
|
||||
if err := func() error {
|
||||
s.RelTolerance.Reset()
|
||||
if err := s.RelTolerance.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"rel_tolerance\"")
|
||||
}
|
||||
case "program":
|
||||
if err := func() error {
|
||||
s.Program.Reset()
|
||||
if err := s.Program.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"program\"")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unexpected field %q", k)
|
||||
}
|
||||
@@ -126,6 +177,10 @@ func (s *CheckerKind) Decode(d *jx.Decoder) error {
|
||||
*s = CheckerKindExact
|
||||
case CheckerKindTokens:
|
||||
*s = CheckerKindTokens
|
||||
case CheckerKindNumbers:
|
||||
*s = CheckerKindNumbers
|
||||
case CheckerKindCustom:
|
||||
*s = CheckerKindCustom
|
||||
default:
|
||||
*s = CheckerKind(v)
|
||||
}
|
||||
@@ -146,6 +201,117 @@ func (s *CheckerKind) UnmarshalJSON(data []byte) error {
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *CheckerProgram) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *CheckerProgram) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("language")
|
||||
s.Language.Encode(e)
|
||||
}
|
||||
{
|
||||
e.FieldStart("source")
|
||||
e.Str(s.Source)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfCheckerProgram = [2]string{
|
||||
0: "language",
|
||||
1: "source",
|
||||
}
|
||||
|
||||
// Decode decodes CheckerProgram from json.
|
||||
func (s *CheckerProgram) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode CheckerProgram to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "language":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
if err := s.Language.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"language\"")
|
||||
}
|
||||
case "source":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.Source = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"source\"")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unexpected field %q", k)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode CheckerProgram")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000011,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfCheckerProgram) {
|
||||
name = jsonFieldsNameOfCheckerProgram[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *CheckerProgram) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *CheckerProgram) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *CompileResult) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
@@ -552,6 +718,39 @@ func (s *GroupResult) UnmarshalJSON(data []byte) error {
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes CheckerProgram as json.
|
||||
func (o OptCheckerProgram) Encode(e *jx.Encoder) {
|
||||
if !o.Set {
|
||||
return
|
||||
}
|
||||
o.Value.Encode(e)
|
||||
}
|
||||
|
||||
// Decode decodes CheckerProgram from json.
|
||||
func (o *OptCheckerProgram) Decode(d *jx.Decoder) error {
|
||||
if o == nil {
|
||||
return errors.New("invalid: unable to decode OptCheckerProgram to nil")
|
||||
}
|
||||
o.Set = true
|
||||
if err := o.Value.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s OptCheckerProgram) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *OptCheckerProgram) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes CompileResult as json.
|
||||
func (o OptCompileResult) Encode(e *jx.Encoder) {
|
||||
if !o.Set {
|
||||
@@ -585,6 +784,41 @@ func (s *OptCompileResult) UnmarshalJSON(data []byte) error {
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes float64 as json.
|
||||
func (o OptFloat64) Encode(e *jx.Encoder) {
|
||||
if !o.Set {
|
||||
return
|
||||
}
|
||||
e.Float64(float64(o.Value))
|
||||
}
|
||||
|
||||
// Decode decodes float64 from json.
|
||||
func (o *OptFloat64) Decode(d *jx.Decoder) error {
|
||||
if o == nil {
|
||||
return errors.New("invalid: unable to decode OptFloat64 to nil")
|
||||
}
|
||||
o.Set = true
|
||||
v, err := d.Float64()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
o.Value = float64(v)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s OptFloat64) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *OptFloat64) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes int32 as json.
|
||||
func (o OptInt32) Encode(e *jx.Encoder) {
|
||||
if !o.Set {
|
||||
@@ -1243,6 +1477,8 @@ func (s *RunLanguage) Decode(d *jx.Decoder) error {
|
||||
switch RunLanguage(v) {
|
||||
case RunLanguagePython3:
|
||||
*s = RunLanguagePython3
|
||||
case RunLanguageGo:
|
||||
*s = RunLanguageGo
|
||||
default:
|
||||
*s = RunLanguage(v)
|
||||
}
|
||||
|
||||
@@ -38,11 +38,17 @@ func (s *BearerAuth) SetRoles(val []string) {
|
||||
s.Roles = val
|
||||
}
|
||||
|
||||
// How the standard output of a test is compared with `expected_output`. Future kinds, such as a float
|
||||
// tolerance or a custom checker, add a `kind` value and their own optional parameters to this object.
|
||||
// How the standard output of a test is compared with `expected_output`. `numbers` requires
|
||||
// `abs_tolerance`, `rel_tolerance`, or both; `custom` requires `program`. Other kinds take no
|
||||
// parameter. New kinds add a `kind` value and their own optional parameters.
|
||||
// Ref: #/components/schemas/Checker
|
||||
type Checker struct {
|
||||
Kind CheckerKind `json:"kind"`
|
||||
// Largest accepted absolute difference of two numeric tokens.
|
||||
AbsTolerance OptFloat64 `json:"abs_tolerance"`
|
||||
// Largest accepted difference of two numeric tokens relative to the expected value.
|
||||
RelTolerance OptFloat64 `json:"rel_tolerance"`
|
||||
Program OptCheckerProgram `json:"program"`
|
||||
}
|
||||
|
||||
// GetKind returns the value of Kind.
|
||||
@@ -50,21 +56,56 @@ func (s *Checker) GetKind() CheckerKind {
|
||||
return s.Kind
|
||||
}
|
||||
|
||||
// GetAbsTolerance returns the value of AbsTolerance.
|
||||
func (s *Checker) GetAbsTolerance() OptFloat64 {
|
||||
return s.AbsTolerance
|
||||
}
|
||||
|
||||
// GetRelTolerance returns the value of RelTolerance.
|
||||
func (s *Checker) GetRelTolerance() OptFloat64 {
|
||||
return s.RelTolerance
|
||||
}
|
||||
|
||||
// GetProgram returns the value of Program.
|
||||
func (s *Checker) GetProgram() OptCheckerProgram {
|
||||
return s.Program
|
||||
}
|
||||
|
||||
// SetKind sets the value of Kind.
|
||||
func (s *Checker) SetKind(val CheckerKind) {
|
||||
s.Kind = val
|
||||
}
|
||||
|
||||
// SetAbsTolerance sets the value of AbsTolerance.
|
||||
func (s *Checker) SetAbsTolerance(val OptFloat64) {
|
||||
s.AbsTolerance = val
|
||||
}
|
||||
|
||||
// SetRelTolerance sets the value of RelTolerance.
|
||||
func (s *Checker) SetRelTolerance(val OptFloat64) {
|
||||
s.RelTolerance = val
|
||||
}
|
||||
|
||||
// SetProgram sets the value of Program.
|
||||
func (s *Checker) SetProgram(val OptCheckerProgram) {
|
||||
s.Program = val
|
||||
}
|
||||
|
||||
// - exact: both texts are equal after replacing CRLF with LF, removing trailing spaces and tabs at
|
||||
// the end of each line, and removing trailing empty lines.
|
||||
// - tokens: both texts split on ASCII whitespace give the same sequence of tokens.
|
||||
// - numbers: like tokens, but two finite numeric tokens are equal when their difference is within
|
||||
// abs_tolerance or within rel_tolerance times the expected value; other tokens must be equal.
|
||||
// - custom: the checker program of the task family decides in the sandbox.
|
||||
//
|
||||
// Ref: #/components/schemas/CheckerKind
|
||||
type CheckerKind string
|
||||
|
||||
const (
|
||||
CheckerKindExact CheckerKind = "exact"
|
||||
CheckerKindTokens CheckerKind = "tokens"
|
||||
CheckerKindExact CheckerKind = "exact"
|
||||
CheckerKindTokens CheckerKind = "tokens"
|
||||
CheckerKindNumbers CheckerKind = "numbers"
|
||||
CheckerKindCustom CheckerKind = "custom"
|
||||
)
|
||||
|
||||
// AllValues returns all CheckerKind values.
|
||||
@@ -72,6 +113,8 @@ func (CheckerKind) AllValues() []CheckerKind {
|
||||
return []CheckerKind{
|
||||
CheckerKindExact,
|
||||
CheckerKindTokens,
|
||||
CheckerKindNumbers,
|
||||
CheckerKindCustom,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +125,10 @@ func (s CheckerKind) MarshalText() ([]byte, error) {
|
||||
return []byte(s), nil
|
||||
case CheckerKindTokens:
|
||||
return []byte(s), nil
|
||||
case CheckerKindNumbers:
|
||||
return []byte(s), nil
|
||||
case CheckerKindCustom:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
@@ -96,11 +143,48 @@ func (s *CheckerKind) UnmarshalText(data []byte) error {
|
||||
case CheckerKindTokens:
|
||||
*s = CheckerKindTokens
|
||||
return nil
|
||||
case CheckerKindNumbers:
|
||||
*s = CheckerKindNumbers
|
||||
return nil
|
||||
case CheckerKindCustom:
|
||||
*s = CheckerKindCustom
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// Checker program of the task family. It runs in the sandbox with the same isolation as the solution
|
||||
// and fixed limits of its own (5 s CPU, 256 MiB). Its arguments are the paths of three read-only
|
||||
// files: the test input, the expected output, and the actual output. Exit status 0 accepts, 1 rejects,
|
||||
// and anything else, a signal, or a limit is a checker failure, which makes the run
|
||||
// infrastructure_failure. Its own output is discarded and never returned.
|
||||
// Ref: #/components/schemas/CheckerProgram
|
||||
type CheckerProgram struct {
|
||||
Language RunLanguage `json:"language"`
|
||||
Source string `json:"source"`
|
||||
}
|
||||
|
||||
// GetLanguage returns the value of Language.
|
||||
func (s *CheckerProgram) GetLanguage() RunLanguage {
|
||||
return s.Language
|
||||
}
|
||||
|
||||
// GetSource returns the value of Source.
|
||||
func (s *CheckerProgram) GetSource() string {
|
||||
return s.Source
|
||||
}
|
||||
|
||||
// SetLanguage sets the value of Language.
|
||||
func (s *CheckerProgram) SetLanguage(val RunLanguage) {
|
||||
s.Language = val
|
||||
}
|
||||
|
||||
// SetSource sets the value of Source.
|
||||
func (s *CheckerProgram) SetSource(val string) {
|
||||
s.Source = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/CompileResult
|
||||
type CompileResult struct {
|
||||
Outcome RunOutcome `json:"outcome"`
|
||||
@@ -233,6 +317,52 @@ func (s *GroupResult) SetTests(val []TestResult) {
|
||||
s.Tests = val
|
||||
}
|
||||
|
||||
// NewOptCheckerProgram returns new OptCheckerProgram with value set to v.
|
||||
func NewOptCheckerProgram(v CheckerProgram) OptCheckerProgram {
|
||||
return OptCheckerProgram{
|
||||
Value: v,
|
||||
Set: true,
|
||||
}
|
||||
}
|
||||
|
||||
// OptCheckerProgram is optional CheckerProgram.
|
||||
type OptCheckerProgram struct {
|
||||
Value CheckerProgram
|
||||
Set bool
|
||||
}
|
||||
|
||||
// IsSet returns true if OptCheckerProgram was set.
|
||||
func (o OptCheckerProgram) IsSet() bool { return o.Set }
|
||||
|
||||
// Reset unsets value.
|
||||
func (o *OptCheckerProgram) Reset() {
|
||||
var v CheckerProgram
|
||||
o.Value = v
|
||||
o.Set = false
|
||||
}
|
||||
|
||||
// SetTo sets value to v.
|
||||
func (o *OptCheckerProgram) SetTo(v CheckerProgram) {
|
||||
o.Set = true
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// Get returns value and boolean that denotes whether value was set.
|
||||
func (o OptCheckerProgram) Get() (v CheckerProgram, ok bool) {
|
||||
if !o.Set {
|
||||
return v, false
|
||||
}
|
||||
return o.Value, true
|
||||
}
|
||||
|
||||
// Or returns value if set, or given parameter if does not.
|
||||
func (o OptCheckerProgram) Or(d CheckerProgram) CheckerProgram {
|
||||
if v, ok := o.Get(); ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// NewOptCompileResult returns new OptCompileResult with value set to v.
|
||||
func NewOptCompileResult(v CompileResult) OptCompileResult {
|
||||
return OptCompileResult{
|
||||
@@ -279,6 +409,52 @@ func (o OptCompileResult) Or(d CompileResult) CompileResult {
|
||||
return d
|
||||
}
|
||||
|
||||
// NewOptFloat64 returns new OptFloat64 with value set to v.
|
||||
func NewOptFloat64(v float64) OptFloat64 {
|
||||
return OptFloat64{
|
||||
Value: v,
|
||||
Set: true,
|
||||
}
|
||||
}
|
||||
|
||||
// OptFloat64 is optional float64.
|
||||
type OptFloat64 struct {
|
||||
Value float64
|
||||
Set bool
|
||||
}
|
||||
|
||||
// IsSet returns true if OptFloat64 was set.
|
||||
func (o OptFloat64) IsSet() bool { return o.Set }
|
||||
|
||||
// Reset unsets value.
|
||||
func (o *OptFloat64) Reset() {
|
||||
var v float64
|
||||
o.Value = v
|
||||
o.Set = false
|
||||
}
|
||||
|
||||
// SetTo sets value to v.
|
||||
func (o *OptFloat64) SetTo(v float64) {
|
||||
o.Set = true
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// Get returns value and boolean that denotes whether value was set.
|
||||
func (o OptFloat64) Get() (v float64, ok bool) {
|
||||
if !o.Set {
|
||||
return v, false
|
||||
}
|
||||
return o.Value, true
|
||||
}
|
||||
|
||||
// Or returns value if set, or given parameter if does not.
|
||||
func (o OptFloat64) Or(d float64) float64 {
|
||||
if v, ok := o.Get(); ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// NewOptInt32 returns new OptInt32 with value set to v.
|
||||
func NewOptInt32(v int32) OptInt32 {
|
||||
return OptInt32{
|
||||
@@ -868,18 +1044,23 @@ func (s *ProblemStatusCode) SetResponse(val Problem) {
|
||||
}
|
||||
|
||||
// Language and runtime of the source. `python3` runs the Python 3 interpreter of the runner image with
|
||||
// isolated mode and no bytecode writes; a syntax check runs first and fails with compile_error.
|
||||
// isolated mode and no bytecode writes; a syntax check runs first and fails with compile_error. `go`
|
||||
// compiles one `package main` file with the Go toolchain of the runner image against a prebuilt
|
||||
// standard library (no modules, no cgo, no network) in a separate compile phase with its own limits; a
|
||||
// compile or link error is compile_error and no test runs.
|
||||
// Ref: #/components/schemas/RunLanguage
|
||||
type RunLanguage string
|
||||
|
||||
const (
|
||||
RunLanguagePython3 RunLanguage = "python3"
|
||||
RunLanguageGo RunLanguage = "go"
|
||||
)
|
||||
|
||||
// AllValues returns all RunLanguage values.
|
||||
func (RunLanguage) AllValues() []RunLanguage {
|
||||
return []RunLanguage{
|
||||
RunLanguagePython3,
|
||||
RunLanguageGo,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -888,6 +1069,8 @@ func (s RunLanguage) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case RunLanguagePython3:
|
||||
return []byte(s), nil
|
||||
case RunLanguageGo:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
@@ -899,6 +1082,9 @@ func (s *RunLanguage) UnmarshalText(data []byte) error {
|
||||
case RunLanguagePython3:
|
||||
*s = RunLanguagePython3
|
||||
return nil
|
||||
case RunLanguageGo:
|
||||
*s = RunLanguageGo
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
|
||||
@@ -44,8 +44,9 @@ type Handler interface {
|
||||
// memory for a bounded time after they finish; an ID that was forgotten or lost in a restart starts a
|
||||
// new run. Requests above the configured body limit (8 MiB by default) answer 413 `payload_too_large`.
|
||||
// Semantic rules that the schema cannot express answer 400 `validation_failed`: group IDs are unique
|
||||
// in a run, test IDs are unique in a group, and the number of tests multiplied by
|
||||
// `limits.time_limit_ms` does not exceed 300000.
|
||||
// in a run, test IDs are unique in a group, the number of tests multiplied by `limits.time_limit_ms`
|
||||
// does not exceed 300000, a `numbers` checker has a positive tolerance, a `custom` checker has a
|
||||
// program, and no other kind carries tolerances or a program.
|
||||
//
|
||||
// PUT /v1/runs/{run_id}
|
||||
SubmitRun(ctx context.Context, req *RunRequest, params SubmitRunParams) (SubmitRunRes, error)
|
||||
|
||||
@@ -58,8 +58,9 @@ func (UnimplementedHandler) GetRunnerReadyz(ctx context.Context) (r GetRunnerRea
|
||||
// memory for a bounded time after they finish; an ID that was forgotten or lost in a restart starts a
|
||||
// new run. Requests above the configured body limit (8 MiB by default) answer 413 `payload_too_large`.
|
||||
// Semantic rules that the schema cannot express answer 400 `validation_failed`: group IDs are unique
|
||||
// in a run, test IDs are unique in a group, and the number of tests multiplied by
|
||||
// `limits.time_limit_ms` does not exceed 300000.
|
||||
// in a run, test IDs are unique in a group, the number of tests multiplied by `limits.time_limit_ms`
|
||||
// does not exceed 300000, a `numbers` checker has a positive tolerance, a `custom` checker has a
|
||||
// program, and no other kind carries tolerances or a program.
|
||||
//
|
||||
// PUT /v1/runs/{run_id}
|
||||
func (UnimplementedHandler) SubmitRun(ctx context.Context, req *RunRequest, params SubmitRunParams) (r SubmitRunRes, _ error) {
|
||||
|
||||
@@ -26,6 +26,80 @@ func (s *Checker) Validate() error {
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := s.AbsTolerance.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.Float{
|
||||
MinSet: true,
|
||||
Min: 0,
|
||||
MaxSet: true,
|
||||
Max: 1e+09,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: nil,
|
||||
Pattern: nil,
|
||||
}).Validate(float64(value)); err != nil {
|
||||
return errors.Wrap(err, "float")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "abs_tolerance",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := s.RelTolerance.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.Float{
|
||||
MinSet: true,
|
||||
Min: 0,
|
||||
MaxSet: true,
|
||||
Max: 1,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: nil,
|
||||
Pattern: nil,
|
||||
}).Validate(float64(value)); err != nil {
|
||||
return errors.Wrap(err, "float")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "rel_tolerance",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := s.Program.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := value.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "program",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
@@ -38,11 +112,61 @@ func (s CheckerKind) Validate() error {
|
||||
return nil
|
||||
case "tokens":
|
||||
return nil
|
||||
case "numbers":
|
||||
return nil
|
||||
case "custom":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CheckerProgram) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Language.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "language",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 65536,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(s.Source)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "source",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CompileResult) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
@@ -668,6 +792,8 @@ func (s RunLanguage) Validate() error {
|
||||
switch s {
|
||||
case "python3":
|
||||
return nil
|
||||
case "go":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
|
||||
@@ -64,7 +64,11 @@ func Run() error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("app.Run - prepare sandbox: %w", err)
|
||||
}
|
||||
evaluator := judge.New(executor, logger, judge.Python3(cfg.PythonPath))
|
||||
languages := Languages(cfg)
|
||||
if err := checkLanguageFiles(languages); err != nil {
|
||||
return err
|
||||
}
|
||||
evaluator := judge.New(executor, logger, languages...)
|
||||
manager, err := jobs.NewManager(jobs.Config{
|
||||
MaxConcurrent: cfg.MaxConcurrentRuns,
|
||||
ResultTTL: cfg.ResultTTL,
|
||||
@@ -128,6 +132,24 @@ func serve(httpServer *http.Server, cfg config.Config, logger *slog.Logger) erro
|
||||
return fmt.Errorf("app.serve - listen: %w", err)
|
||||
}
|
||||
|
||||
// Languages returns the languages of the runner for cfg.
|
||||
func Languages(cfg config.Config) []judge.Language {
|
||||
return []judge.Language{judge.Python3(cfg.PythonPath), judge.Go(cfg.GoToolDir)}
|
||||
}
|
||||
|
||||
// checkLanguageFiles fails startup when a toolchain file is missing, so a
|
||||
// broken image is not ready instead of failing every run.
|
||||
func checkLanguageFiles(languages []judge.Language) error {
|
||||
for _, language := range languages {
|
||||
for _, path := range language.Requires {
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
return fmt.Errorf("app.checkLanguageFiles - %s: %w", language.ID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SandboxConfig returns the sandbox settings of the runner for cfg.
|
||||
func SandboxConfig(cfg config.Config) sandbox.Config {
|
||||
return sandbox.Config{
|
||||
|
||||
@@ -10,7 +10,10 @@ package checker
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Kind names a comparison rule of the runner contract.
|
||||
@@ -23,11 +26,32 @@ const (
|
||||
// Tokens accepts texts with the same sequence of whitespace-separated
|
||||
// tokens.
|
||||
Tokens Kind = "tokens"
|
||||
// Numbers compares tokens like Tokens, but numeric tokens are equal
|
||||
// within an absolute or a relative tolerance.
|
||||
Numbers Kind = "numbers"
|
||||
// Custom runs a checker program of the task family in the sandbox.
|
||||
Custom Kind = "custom"
|
||||
)
|
||||
|
||||
// ErrNeedsSandbox reports a kind that the judge builds with its sandbox.
|
||||
var ErrNeedsSandbox = errors.New("checker.New - this checker kind runs in the sandbox")
|
||||
|
||||
// Spec selects and parameterizes a checker.
|
||||
type Spec struct {
|
||||
Kind Kind `json:"kind"`
|
||||
// AbsTolerance and RelTolerance parameterize Numbers.
|
||||
AbsTolerance float64 `json:"abs_tolerance,omitempty"`
|
||||
RelTolerance float64 `json:"rel_tolerance,omitempty"`
|
||||
// Program is the checker program of Custom.
|
||||
Program *Program `json:"program,omitempty"`
|
||||
}
|
||||
|
||||
// Program is the source of a custom checker. It reads the files input,
|
||||
// expected, and actual, whose paths are its arguments, and exits with 0 to
|
||||
// accept, 1 to reject, and any other status when it fails itself.
|
||||
type Program struct {
|
||||
Language string `json:"language"`
|
||||
Source string `json:"source"`
|
||||
}
|
||||
|
||||
// Input is everything a checker may look at for one test.
|
||||
@@ -51,6 +75,13 @@ func New(spec Spec) (Checker, error) {
|
||||
return exactChecker{}, nil
|
||||
case Tokens:
|
||||
return tokensChecker{}, nil
|
||||
case Numbers:
|
||||
if spec.AbsTolerance < 0 || spec.RelTolerance < 0 || spec.AbsTolerance == 0 && spec.RelTolerance == 0 {
|
||||
return nil, errors.New("checker.New - numbers needs a positive tolerance")
|
||||
}
|
||||
return numbersChecker{absolute: spec.AbsTolerance, relative: spec.RelTolerance}, nil
|
||||
case Custom:
|
||||
return nil, ErrNeedsSandbox
|
||||
default:
|
||||
return nil, fmt.Errorf("checker.New - unknown kind %q", spec.Kind)
|
||||
}
|
||||
@@ -78,6 +109,44 @@ func (tokensChecker) Check(_ context.Context, input Input) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
type numbersChecker struct {
|
||||
absolute float64
|
||||
relative float64
|
||||
}
|
||||
|
||||
func (c numbersChecker) Check(_ context.Context, input Input) (bool, error) {
|
||||
expected := bytes.Fields(input.Expected)
|
||||
actual := bytes.Fields(input.Actual)
|
||||
if len(expected) != len(actual) {
|
||||
return false, nil
|
||||
}
|
||||
for index := range expected {
|
||||
if !c.tokensMatch(expected[index], actual[index]) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// tokensMatch compares two finite numbers within the tolerance and any
|
||||
// other tokens exactly.
|
||||
func (c numbersChecker) tokensMatch(expected, actual []byte) bool {
|
||||
if bytes.Equal(expected, actual) {
|
||||
return true
|
||||
}
|
||||
want, wantErr := strconv.ParseFloat(string(expected), 64)
|
||||
got, gotErr := strconv.ParseFloat(string(actual), 64)
|
||||
if wantErr != nil || gotErr != nil || !finite(want) || !finite(got) {
|
||||
return false
|
||||
}
|
||||
difference := math.Abs(got - want)
|
||||
return difference <= c.absolute || difference <= c.relative*math.Abs(want)
|
||||
}
|
||||
|
||||
func finite(value float64) bool {
|
||||
return !math.IsNaN(value) && !math.IsInf(value, 0)
|
||||
}
|
||||
|
||||
// normalizeLines replaces CRLF with LF, removes spaces and tabs at the end of
|
||||
// every line, and removes trailing empty lines.
|
||||
func normalizeLines(text []byte) []byte {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package checker
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -26,6 +27,33 @@ func TestCheckersCompareOutput(t *testing.T) {
|
||||
{"tokens different token", Tokens, "1 2 3", "1 2 4", false},
|
||||
{"tokens are case sensitive", Tokens, "Yes", "yes", false},
|
||||
}
|
||||
numbers := Spec{Kind: Numbers, AbsTolerance: 1e-6}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
expected string
|
||||
actual string
|
||||
accepted bool
|
||||
}{
|
||||
{"numbers within the absolute tolerance", "3.3333333333", "3.3333334", true},
|
||||
{"numbers outside the tolerance", "3.3333333333", "3.33", false},
|
||||
{"numbers in another notation", "0.000001 2", "1e-6 2.0000000", true},
|
||||
{"numbers keep words exact", "YES 1.5", "yes 1.5", false},
|
||||
{"numbers reject NaN", "1", "NaN", false},
|
||||
{"numbers reject infinity", "1e308", "Inf", false},
|
||||
{"numbers count tokens", "1 2", "1 2 3", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
check, err := New(numbers)
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
accepted, err := check.Check(t.Context(), Input{Expected: []byte(tc.expected), Actual: []byte(tc.actual)})
|
||||
if err != nil || accepted != tc.accepted {
|
||||
t.Fatalf("Check(%q, %q) = %v, %v; want %v", tc.expected, tc.actual, accepted, err, tc.accepted)
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
@@ -50,4 +78,13 @@ func TestNewRejectsUnknownKind(t *testing.T) {
|
||||
if _, err := New(Spec{Kind: "float"}); err == nil {
|
||||
t.Fatal("New accepted an unknown checker kind")
|
||||
}
|
||||
if _, err := New(Spec{Kind: Numbers}); err == nil {
|
||||
t.Fatal("New accepted numbers without a tolerance")
|
||||
}
|
||||
if _, err := New(Spec{Kind: Numbers, AbsTolerance: -1}); err == nil {
|
||||
t.Fatal("New accepted a negative tolerance")
|
||||
}
|
||||
if _, err := New(Spec{Kind: Custom}); !errors.Is(err, ErrNeedsSandbox) {
|
||||
t.Fatalf("New(custom) = %v, want ErrNeedsSandbox", err)
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ const (
|
||||
DefaultCgroupRoot = "/sys/fs/cgroup"
|
||||
DefaultNsjailPath = "/usr/bin/nsjail"
|
||||
DefaultPythonPath = "/usr/local/bin/python3"
|
||||
DefaultGoToolDir = "/usr/local/lib/lincodex-runner/go"
|
||||
DefaultSandboxUID = 99999
|
||||
DefaultMaxProcesses = 16
|
||||
DefaultMemoryOverheadBytes = 4 << 20
|
||||
@@ -55,6 +56,7 @@ type Config struct {
|
||||
CgroupRoot string
|
||||
NsjailPath string
|
||||
PythonPath string
|
||||
GoToolDir string
|
||||
SandboxUID int
|
||||
MaxProcesses int
|
||||
MemoryOverheadBytes int64
|
||||
@@ -92,6 +94,7 @@ func parse(lookup lookupFunc, readFile readFileFunc) (Config, error) {
|
||||
CgroupRoot: r.text("RUNNER_CGROUP_ROOT", DefaultCgroupRoot),
|
||||
NsjailPath: r.text("RUNNER_NSJAIL_PATH", DefaultNsjailPath),
|
||||
PythonPath: r.text("RUNNER_PYTHON_PATH", DefaultPythonPath),
|
||||
GoToolDir: r.text("RUNNER_GO_TOOL_DIR", DefaultGoToolDir),
|
||||
SandboxUID: r.integer("RUNNER_SANDBOX_UID", DefaultSandboxUID),
|
||||
MaxProcesses: r.integer("RUNNER_SANDBOX_MAX_PROCESSES", DefaultMaxProcesses),
|
||||
MemoryOverheadBytes: r.int64("RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES", DefaultMemoryOverheadBytes),
|
||||
@@ -164,6 +167,7 @@ func (c Config) validatePaths() error {
|
||||
"RUNNER_CGROUP_ROOT": c.CgroupRoot,
|
||||
"RUNNER_NSJAIL_PATH": c.NsjailPath,
|
||||
"RUNNER_PYTHON_PATH": c.PythonPath,
|
||||
"RUNNER_GO_TOOL_DIR": c.GoToolDir,
|
||||
} {
|
||||
if !strings.HasPrefix(path, "/") {
|
||||
errs = append(errs, fmt.Errorf("config.validate - %s must be an absolute path", name))
|
||||
|
||||
@@ -89,7 +89,7 @@ func newRunner(t *testing.T) (*sandbox.Executor, *judge.Judge) {
|
||||
t.Fatalf("sandbox: %v", err)
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))
|
||||
return executor, judge.New(executor, logger, judge.Python3(cfg.PythonPath))
|
||||
return executor, judge.New(executor, logger, app.Languages(cfg)...)
|
||||
}
|
||||
|
||||
func TestHostileProgramsAreStoppedByTheRightLimit(t *testing.T) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// Package judgetest checks languages and checkers against reference
|
||||
// solutions in the real sandbox. Like isolationtest, it is built only with
|
||||
// the sandbox tag and runs in the dev-only test container
|
||||
// (make -C runner test-sandbox); its fixtures are under testdata/judge.
|
||||
package judgetest
|
||||
@@ -0,0 +1,192 @@
|
||||
//go:build sandbox && linux
|
||||
|
||||
package judgetest
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/runner/internal/app"
|
||||
"lincodex/runner/internal/checker"
|
||||
"lincodex/runner/internal/config"
|
||||
"lincodex/runner/internal/judge"
|
||||
"lincodex/runner/internal/sandbox"
|
||||
)
|
||||
|
||||
const (
|
||||
fixturesEnv = "RUNNER_JUDGE_FIXTURES"
|
||||
defaultFixtures = "../../testdata/judge"
|
||||
manifestSchema = "lincodex.runner-judge-fixtures/v1"
|
||||
)
|
||||
|
||||
type manifest struct {
|
||||
Schema string `json:"schema"`
|
||||
Limits struct {
|
||||
TimeLimitMs int64 `json:"time_limit_ms"`
|
||||
MemoryLimitMB int64 `json:"memory_limit_mb"`
|
||||
OutputLimitKB int64 `json:"output_limit_kb"`
|
||||
} `json:"limits"`
|
||||
Tasks []task `json:"tasks"`
|
||||
Solutions []solution `json:"solutions"`
|
||||
}
|
||||
|
||||
type task struct {
|
||||
Name string `json:"name"`
|
||||
Groups []struct {
|
||||
ID string `json:"id"`
|
||||
Visibility judge.Visibility `json:"visibility"`
|
||||
Checker struct {
|
||||
Kind checker.Kind `json:"kind"`
|
||||
AbsTolerance float64 `json:"abs_tolerance"`
|
||||
RelTolerance float64 `json:"rel_tolerance"`
|
||||
Program *struct {
|
||||
Language string `json:"language"`
|
||||
Source string `json:"source"`
|
||||
} `json:"program"`
|
||||
} `json:"checker"`
|
||||
Tests []judge.Test `json:"tests"`
|
||||
} `json:"groups"`
|
||||
}
|
||||
|
||||
type solution struct {
|
||||
Name string `json:"name"`
|
||||
Task string `json:"task"`
|
||||
Language string `json:"language"`
|
||||
Source string `json:"source"`
|
||||
Expect struct {
|
||||
Outcome judge.Outcome `json:"outcome"`
|
||||
Groups map[string]judge.Outcome `json:"groups"`
|
||||
} `json:"expect"`
|
||||
}
|
||||
|
||||
func fixturesDir() string {
|
||||
if dir := os.Getenv(fixturesEnv); dir != "" {
|
||||
return dir
|
||||
}
|
||||
return defaultFixtures
|
||||
}
|
||||
|
||||
func readFixture(t *testing.T, name string) string {
|
||||
t.Helper()
|
||||
content, err := os.ReadFile(filepath.Join(fixturesDir(), name))
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", name, err)
|
||||
}
|
||||
return string(content)
|
||||
}
|
||||
|
||||
func loadManifest(t *testing.T) manifest {
|
||||
t.Helper()
|
||||
var loaded manifest
|
||||
if err := json.Unmarshal([]byte(readFixture(t, "manifest.json")), &loaded); err != nil {
|
||||
t.Fatalf("decode manifest: %v", err)
|
||||
}
|
||||
if loaded.Schema != manifestSchema || len(loaded.Solutions) == 0 {
|
||||
t.Fatalf("unexpected manifest %q with %d solutions", loaded.Schema, len(loaded.Solutions))
|
||||
}
|
||||
return loaded
|
||||
}
|
||||
|
||||
func newJudge(t *testing.T) (*sandbox.Executor, *judge.Judge) {
|
||||
t.Helper()
|
||||
t.Setenv("RUNNER_API_TOKEN", strings.Repeat("t", config.MinTokenLength))
|
||||
t.Setenv("RUNNER_DEV_ALLOW_PLAINTEXT_HTTP", "true")
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatalf("config: %v", err)
|
||||
}
|
||||
executor, err := sandbox.New(app.SandboxConfig(cfg))
|
||||
if err != nil {
|
||||
t.Fatalf("sandbox: %v", err)
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))
|
||||
return executor, judge.New(executor, logger, app.Languages(cfg)...)
|
||||
}
|
||||
|
||||
func (m manifest) request(t *testing.T, candidate solution) judge.Request {
|
||||
t.Helper()
|
||||
var found *task
|
||||
for index := range m.Tasks {
|
||||
if m.Tasks[index].Name == candidate.Task {
|
||||
found = &m.Tasks[index]
|
||||
}
|
||||
}
|
||||
if found == nil {
|
||||
t.Fatalf("%s: unknown task %q", candidate.Name, candidate.Task)
|
||||
}
|
||||
request := judge.Request{
|
||||
Language: candidate.Language,
|
||||
Source: readFixture(t, candidate.Source),
|
||||
Limits: judge.Limits{
|
||||
TimeLimit: time.Duration(m.Limits.TimeLimitMs) * time.Millisecond,
|
||||
MemoryBytes: m.Limits.MemoryLimitMB << 20,
|
||||
OutputBytes: m.Limits.OutputLimitKB << 10,
|
||||
},
|
||||
}
|
||||
for _, group := range found.Groups {
|
||||
spec := checker.Spec{Kind: group.Checker.Kind, AbsTolerance: group.Checker.AbsTolerance, RelTolerance: group.Checker.RelTolerance}
|
||||
if group.Checker.Program != nil {
|
||||
spec.Program = &checker.Program{Language: group.Checker.Program.Language, Source: readFixture(t, group.Checker.Program.Source)}
|
||||
}
|
||||
request.Groups = append(request.Groups, judge.Group{ID: group.ID, Visibility: group.Visibility, Checker: spec, Tests: group.Tests})
|
||||
}
|
||||
return request
|
||||
}
|
||||
|
||||
func TestReferenceSolutionsGetTheExpectedGroupResults(t *testing.T) {
|
||||
loaded := loadManifest(t)
|
||||
executor, evaluator := newJudge(t)
|
||||
|
||||
for _, candidate := range loaded.Solutions {
|
||||
request := loaded.request(t, candidate)
|
||||
result := evaluator.Run(t.Context(), request)
|
||||
if result.Outcome != candidate.Expect.Outcome {
|
||||
t.Errorf("%s: outcome %s, want %s (%+v)", candidate.Name, result.Outcome, candidate.Expect.Outcome, result)
|
||||
continue
|
||||
}
|
||||
got := map[string]judge.Outcome{}
|
||||
for _, group := range result.Groups {
|
||||
got[group.ID] = group.Outcome
|
||||
assertGroupShape(t, candidate, group)
|
||||
}
|
||||
if fmt.Sprint(got) != fmt.Sprint(candidate.Expect.Groups) {
|
||||
t.Errorf("%s: groups %v, want %v", candidate.Name, got, candidate.Expect.Groups)
|
||||
}
|
||||
if result.Outcome == judge.CompileError && (result.Compile == nil || !strings.Contains(result.Compile.Diagnostic, "main.go:")) {
|
||||
t.Errorf("%s: compile error without a main.go diagnostic: %+v", candidate.Name, result.Compile)
|
||||
}
|
||||
t.Logf("%-28s %-14s %v duration=%v", candidate.Name, result.Outcome, got, result.Duration)
|
||||
}
|
||||
|
||||
boxes, cgroups, err := executor.Leftovers()
|
||||
if err != nil || len(boxes) != 0 || len(cgroups) != 0 {
|
||||
t.Fatalf("left boxes %q and cgroups %q: %v", boxes, cgroups, err)
|
||||
}
|
||||
}
|
||||
|
||||
// assertGroupShape checks what a group result may reveal: a compile error
|
||||
// runs no test, a group stops at its first failure, and hidden tests never
|
||||
// carry program output or diagnostics.
|
||||
func assertGroupShape(t *testing.T, candidate solution, group judge.GroupResult) {
|
||||
t.Helper()
|
||||
if group.Outcome == judge.CompileError && len(group.Tests) != 0 {
|
||||
t.Errorf("%s/%s: tests ran after a compile error", candidate.Name, group.ID)
|
||||
}
|
||||
for index, test := range group.Tests {
|
||||
if group.Visibility == judge.Hidden && test.Diagnostic != "" {
|
||||
t.Errorf("%s/%s/%s: hidden test carries a diagnostic", candidate.Name, group.ID, test.ID)
|
||||
}
|
||||
if test.Outcome != judge.Accepted && index != len(group.Tests)-1 {
|
||||
t.Errorf("%s/%s: group continued after a failed test", candidate.Name, group.ID)
|
||||
}
|
||||
if test.CPUTime <= 0 || test.MemoryKB <= 0 {
|
||||
t.Errorf("%s/%s/%s: usage not recorded", candidate.Name, group.ID, test.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -75,9 +75,10 @@ func validateConfig(cfg Config) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewBox creates the read-only file directory of a run.
|
||||
// NewBox creates the directory of one program; the sandbox user owns its
|
||||
// build output.
|
||||
func (e *Executor) NewBox(fileName string, content []byte) (*Box, error) {
|
||||
return CreateBox(e.cfg.WorkRoot, fileName, content)
|
||||
return CreateBox(e.cfg.WorkRoot, fileName, content, Owner{UID: e.cfg.SandboxUID, GID: e.cfg.SandboxGID})
|
||||
}
|
||||
|
||||
// Leftovers lists boxes and run cgroups that still exist. After every run
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"bytes"
|
||||
"math"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
@@ -34,7 +35,7 @@ func nsjailArgs(cfg Config, spec Spec, limits Limits, seccompPolicy string) []st
|
||||
"--mode", "o",
|
||||
"--log_fd", strconv.Itoa(nsjailLogFD),
|
||||
"--hostname", sandboxHostname,
|
||||
"--cwd", ScratchPath,
|
||||
"--cwd", workDir(spec),
|
||||
// Inside and outside the user namespace the program is the same
|
||||
// unprivileged ID, never root.
|
||||
"--user", idMapping(cfg.SandboxUID),
|
||||
@@ -42,7 +43,7 @@ func nsjailArgs(cfg Config, spec Spec, limits Limits, seccompPolicy string) []st
|
||||
"--time_limit", strconv.Itoa(ceilSeconds(limits.WallTime + nsjailTimeBackstop)),
|
||||
"--rlimit_as", strconv.Itoa(addressSpaceLimitMB),
|
||||
"--rlimit_cpu", strconv.Itoa(ceilSeconds(limits.CPUTime + cpuRlimitBackstop)),
|
||||
"--rlimit_fsize", strconv.Itoa(ceilMB(cfg.FileSizeBytes)),
|
||||
"--rlimit_fsize", strconv.Itoa(ceilMB(fileSizeLimit(cfg, limits))),
|
||||
"--rlimit_nofile", strconv.Itoa(cfg.OpenFiles),
|
||||
"--rlimit_core", "0",
|
||||
"--disable_proc",
|
||||
@@ -54,19 +55,39 @@ func nsjailArgs(cfg Config, spec Spec, limits Limits, seccompPolicy string) []st
|
||||
for _, mount := range cfg.ReadOnlyMounts {
|
||||
args = append(args, "--bindmount_ro", mount)
|
||||
}
|
||||
for _, mount := range spec.Mounts {
|
||||
flag := "--bindmount_ro"
|
||||
if mount.Writable {
|
||||
flag = "--bindmount"
|
||||
}
|
||||
args = append(args, flag, mount.Source+":"+mount.Target)
|
||||
}
|
||||
args = append(args,
|
||||
"--bindmount_ro", spec.BoxDir+":"+BoxPath,
|
||||
"--bindmount", "/dev/null",
|
||||
"--bindmount_ro", "/dev/urandom",
|
||||
"--mount", "none:"+ScratchPath+":tmpfs:size="+strconv.FormatInt(cfg.TmpfsBytes, 10),
|
||||
)
|
||||
for _, variable := range cfg.Env {
|
||||
for _, variable := range append(slices.Clone(cfg.Env), spec.Env...) {
|
||||
args = append(args, "--env", variable)
|
||||
}
|
||||
args = append(args, "--")
|
||||
return append(args, spec.Argv...)
|
||||
}
|
||||
|
||||
func workDir(spec Spec) string {
|
||||
if spec.WorkDir != "" {
|
||||
return spec.WorkDir
|
||||
}
|
||||
return ScratchPath
|
||||
}
|
||||
|
||||
func fileSizeLimit(cfg Config, limits Limits) int64 {
|
||||
if limits.FileSizeBytes > 0 {
|
||||
return limits.FileSizeBytes
|
||||
}
|
||||
return cfg.FileSizeBytes
|
||||
}
|
||||
|
||||
func idMapping(id int) string {
|
||||
value := strconv.Itoa(id)
|
||||
return value + ":" + value + ":1"
|
||||
|
||||
@@ -35,9 +35,14 @@ const (
|
||||
|
||||
// Jail paths seen by the jailed program.
|
||||
const (
|
||||
// BoxPath is the read-only directory with the files of a run.
|
||||
// BoxPath is the read-only directory with the source of a program.
|
||||
BoxPath = "/box"
|
||||
// ScratchPath is the writable tmpfs and the working directory.
|
||||
// OutPath holds build output: writable for compile steps, read-only
|
||||
// for test runs.
|
||||
OutPath = "/out"
|
||||
// CheckPath holds the files a custom checker compares, read-only.
|
||||
CheckPath = "/check"
|
||||
// ScratchPath is the writable tmpfs and the default working directory.
|
||||
ScratchPath = "/tmp"
|
||||
)
|
||||
|
||||
@@ -50,6 +55,16 @@ type Limits struct {
|
||||
WallTime time.Duration
|
||||
MemoryBytes int64
|
||||
OutputBytes int64
|
||||
// FileSizeBytes overrides Config.FileSizeBytes when positive, for
|
||||
// compile steps that write binaries.
|
||||
FileSizeBytes int64
|
||||
}
|
||||
|
||||
// Mount is a host directory bound into the jail.
|
||||
type Mount struct {
|
||||
Source string
|
||||
Target string
|
||||
Writable bool
|
||||
}
|
||||
|
||||
// Spec is one command to run in the jail.
|
||||
@@ -58,8 +73,12 @@ type Spec struct {
|
||||
Argv []string
|
||||
// Stdin is written to the standard input of the command.
|
||||
Stdin []byte
|
||||
// BoxDir is the host directory mounted read-only at BoxPath.
|
||||
BoxDir string
|
||||
// Mounts are the run's directories, for example a Box.
|
||||
Mounts []Mount
|
||||
// Env is added to Config.Env.
|
||||
Env []string
|
||||
// WorkDir is the working directory in the jail; empty means ScratchPath.
|
||||
WorkDir string
|
||||
}
|
||||
|
||||
// Result describes a finished run. It never contains host paths.
|
||||
|
||||
@@ -39,7 +39,11 @@ func flagValue(t *testing.T, args []string, flag string) string {
|
||||
func TestNsjailArgsKeepEveryIsolationSwitch(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
spec := Spec{Argv: []string{"/usr/local/bin/python3", "-I", "/box/main.py"}, BoxDir: "/work/run-1"}
|
||||
spec := Spec{
|
||||
Argv: []string{"/usr/local/bin/python3", "-I", "/box/main.py"},
|
||||
Mounts: []Mount{{Source: "/work/run-1/src", Target: BoxPath}, {Source: "/work/run-1/out", Target: OutPath}},
|
||||
Env: []string{"GOMAXPROCS=1"},
|
||||
}
|
||||
limits := Limits{CPUTime: 1500 * time.Millisecond, WallTime: 3500 * time.Millisecond, MemoryBytes: 64 << 20, OutputBytes: 1 << 16}
|
||||
args := nsjailArgs(testConfig(), spec, limits, "POLICY")
|
||||
|
||||
@@ -74,17 +78,32 @@ func TestNsjailArgsKeepEveryIsolationSwitch(t *testing.T) {
|
||||
t.Errorf("args miss %s", required)
|
||||
}
|
||||
}
|
||||
if !slices.Contains(args, "/work/run-1:/box") {
|
||||
t.Errorf("the box is not mounted at /box: %q", args)
|
||||
if !slices.Contains(args, "/work/run-1/src:/box") || !slices.Contains(args, "/work/run-1/out:/out") {
|
||||
t.Errorf("the box is not mounted read-only: %q", args)
|
||||
}
|
||||
if !slices.Contains(args, "GOMAXPROCS=1") || !slices.Contains(args, "LANG=C.UTF-8") {
|
||||
t.Errorf("args miss the environment: %q", args)
|
||||
}
|
||||
|
||||
compile := spec
|
||||
compile.WorkDir = BoxPath
|
||||
compile.Mounts = []Mount{{Source: "/work/run-1/out", Target: OutPath, Writable: true}}
|
||||
compileArgs := nsjailArgs(testConfig(), compile, Limits{CPUTime: time.Second, WallTime: time.Second, FileSizeBytes: 64 << 20}, "POLICY")
|
||||
if got := flagValue(t, compileArgs, "--cwd"); got != BoxPath {
|
||||
t.Errorf("compile --cwd = %q", got)
|
||||
}
|
||||
if got := flagValue(t, compileArgs, "--rlimit_fsize"); got != "64" {
|
||||
t.Errorf("compile --rlimit_fsize = %q", got)
|
||||
}
|
||||
if got := writableMounts(compileArgs); !slices.Equal(got, []string{"/work/run-1/out:/out", "/dev/null"}) {
|
||||
t.Errorf("compile writable mounts = %q", got)
|
||||
}
|
||||
separator := slices.Index(args, "--")
|
||||
if separator < 0 || !slices.Equal(args[separator+1:], spec.Argv) {
|
||||
t.Errorf("command after -- = %q, want %q", args[separator+1:], spec.Argv)
|
||||
}
|
||||
for _, writable := range writableMounts(args) {
|
||||
if writable != "/dev/null" {
|
||||
t.Errorf("unexpected writable bind mount %q", writable)
|
||||
}
|
||||
if got := writableMounts(args); !slices.Equal(got, []string{"/dev/null"}) {
|
||||
t.Errorf("unexpected writable bind mounts %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,13 +209,27 @@ func TestBoxIsReadOnlyAndRemovable(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
root := t.TempDir()
|
||||
box, err := CreateBox(root, "main.py", []byte("print(1)"))
|
||||
box, err := CreateBox(root, "main.py", []byte("print(1)"), Owner{UID: -1, GID: -1})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateBox: %v", err)
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(box.Dir(), "main.py"))
|
||||
info, err := os.Stat(filepath.Join(box.Dir(), "src", "main.py"))
|
||||
if err != nil || info.Mode().Perm() != boxFileMode {
|
||||
t.Fatalf("source file mode = %v, %v", info.Mode(), err)
|
||||
t.Fatalf("source file mode = %v, %v", info, err)
|
||||
}
|
||||
mounts := box.Mounts(false)
|
||||
if mounts[0].Target != BoxPath || mounts[0].Writable || mounts[1].Target != OutPath || mounts[1].Writable {
|
||||
t.Fatalf("mounts = %+v", mounts)
|
||||
}
|
||||
check, remove, err := box.AddCheckFiles(map[string][]byte{"actual": []byte("1")})
|
||||
if err != nil || check.Target != CheckPath || check.Writable {
|
||||
t.Fatalf("AddCheckFiles = %+v, %v", check, err)
|
||||
}
|
||||
if err := remove(); err != nil {
|
||||
t.Fatalf("remove check files: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(check.Source); !os.IsNotExist(err) {
|
||||
t.Fatalf("check files remain: %v", err)
|
||||
}
|
||||
if err := box.Remove(); err != nil {
|
||||
t.Fatalf("Remove: %v", err)
|
||||
@@ -205,7 +238,7 @@ func TestBoxIsReadOnlyAndRemovable(t *testing.T) {
|
||||
t.Fatalf("root after Remove = %v, %v", entries, err)
|
||||
}
|
||||
for _, name := range []string{"", "../main.py", ".hidden", "dir/main.py"} {
|
||||
if _, err := CreateBox(root, name, nil); err == nil {
|
||||
if _, err := CreateBox(root, name, nil, Owner{UID: -1, GID: -1}); err == nil {
|
||||
t.Errorf("CreateBox accepted file name %q", name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package sandbox
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -20,47 +21,143 @@ const (
|
||||
boxPrefix = "run-"
|
||||
)
|
||||
|
||||
// Box is the host directory with the files of one run. It is mounted
|
||||
// read-only into every jail of the run and removed with Remove.
|
||||
// Box is the host directory of one program: its source, mounted read-only
|
||||
// at BoxPath, and its build output, mounted at OutPath, writable only for
|
||||
// compile steps. Remove deletes it.
|
||||
type Box struct {
|
||||
dir string
|
||||
root string
|
||||
}
|
||||
|
||||
// Owner is the user that may write a box's build output. A negative ID
|
||||
// leaves the owner unchanged, which unit tests use.
|
||||
type Owner struct {
|
||||
UID int
|
||||
GID int
|
||||
}
|
||||
|
||||
const (
|
||||
boxSourceDir = "src"
|
||||
boxOutputDir = "out"
|
||||
checkPrefix = "check-"
|
||||
)
|
||||
|
||||
// Dir returns the host path of the box.
|
||||
func (b *Box) Dir() string {
|
||||
return b.dir
|
||||
return b.root
|
||||
}
|
||||
|
||||
// CreateBox creates a box under root with one file.
|
||||
func CreateBox(root, fileName string, content []byte) (*Box, error) {
|
||||
if fileName == "" || fileName != filepath.Base(fileName) || strings.HasPrefix(fileName, ".") {
|
||||
// CreateBox creates a box under root with one source file.
|
||||
func CreateBox(root, fileName string, content []byte, owner Owner) (*Box, error) {
|
||||
if !validFileName(fileName) {
|
||||
return nil, fmt.Errorf("sandbox.CreateBox - invalid file name %q", fileName)
|
||||
}
|
||||
dir, err := os.MkdirTemp(root, boxPrefix)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sandbox.CreateBox - create: %w", err)
|
||||
}
|
||||
box := &Box{dir: dir}
|
||||
if err := os.WriteFile(filepath.Join(dir, fileName), content, boxFileMode); err != nil {
|
||||
return nil, errors.Join(fmt.Errorf("sandbox.CreateBox - write: %w", err), box.Remove())
|
||||
}
|
||||
if err := os.Chmod(dir, boxDirMode); err != nil {
|
||||
return nil, errors.Join(fmt.Errorf("sandbox.CreateBox - chmod: %w", err), box.Remove())
|
||||
box := &Box{root: dir}
|
||||
if err := box.populate(fileName, content, owner); err != nil {
|
||||
return nil, errors.Join(err, box.Remove())
|
||||
}
|
||||
return box, nil
|
||||
}
|
||||
|
||||
// Remove deletes the box and its files.
|
||||
func (b *Box) Remove() error {
|
||||
if err := os.Chmod(b.dir, ownerOnlyMode); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("sandbox.Box.Remove - chmod: %w", err)
|
||||
func (b *Box) populate(fileName string, content []byte, owner Owner) error {
|
||||
source := filepath.Join(b.root, boxSourceDir)
|
||||
if err := writeReadOnlyDir(source, map[string][]byte{fileName: content}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.RemoveAll(b.dir); err != nil {
|
||||
return fmt.Errorf("sandbox.Box.Remove - remove: %w", err)
|
||||
output := filepath.Join(b.root, boxOutputDir)
|
||||
if err := os.Mkdir(output, ownerOnlyMode); err != nil {
|
||||
return fmt.Errorf("sandbox.Box.populate - create output: %w", err)
|
||||
}
|
||||
if err := os.Chown(output, owner.UID, owner.GID); err != nil {
|
||||
return fmt.Errorf("sandbox.Box.populate - chown output: %w", err)
|
||||
}
|
||||
if err := os.Chmod(b.root, workRootMode); err != nil {
|
||||
return fmt.Errorf("sandbox.Box.populate - chmod: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Mounts returns the source and output mounts of the box.
|
||||
func (b *Box) Mounts(outputWritable bool) []Mount {
|
||||
return []Mount{
|
||||
{Source: filepath.Join(b.root, boxSourceDir), Target: BoxPath},
|
||||
{Source: filepath.Join(b.root, boxOutputDir), Target: OutPath, Writable: outputWritable},
|
||||
}
|
||||
}
|
||||
|
||||
// AddCheckFiles writes read-only files for one custom checker call and
|
||||
// returns their mount at CheckPath and a function that deletes them.
|
||||
func (b *Box) AddCheckFiles(files map[string][]byte) (Mount, func() error, error) {
|
||||
for name := range files {
|
||||
if !validFileName(name) {
|
||||
return Mount{}, nil, fmt.Errorf("sandbox.Box.AddCheckFiles - invalid file name %q", name)
|
||||
}
|
||||
}
|
||||
dir, err := os.MkdirTemp(b.root, checkPrefix)
|
||||
if err != nil {
|
||||
return Mount{}, nil, fmt.Errorf("sandbox.Box.AddCheckFiles - create: %w", err)
|
||||
}
|
||||
remove := func() error { return removeTree(dir) }
|
||||
if err := fillReadOnlyDir(dir, files); err != nil {
|
||||
return Mount{}, nil, errors.Join(err, remove())
|
||||
}
|
||||
return Mount{Source: dir, Target: CheckPath}, remove, nil
|
||||
}
|
||||
|
||||
// Remove deletes the box and its files.
|
||||
func (b *Box) Remove() error {
|
||||
return removeTree(b.root)
|
||||
}
|
||||
|
||||
// writeReadOnlyDir creates dir with read-only files that the jailed user
|
||||
// can read but not change.
|
||||
func writeReadOnlyDir(dir string, files map[string][]byte) error {
|
||||
if err := os.Mkdir(dir, ownerOnlyMode); err != nil {
|
||||
return fmt.Errorf("sandbox.writeReadOnlyDir - create: %w", err)
|
||||
}
|
||||
return fillReadOnlyDir(dir, files)
|
||||
}
|
||||
|
||||
// fillReadOnlyDir writes files into an existing directory and makes both
|
||||
// read-only.
|
||||
func fillReadOnlyDir(dir string, files map[string][]byte) error {
|
||||
for name, content := range files {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), content, boxFileMode); err != nil {
|
||||
return fmt.Errorf("sandbox.fillReadOnlyDir - write: %w", err)
|
||||
}
|
||||
}
|
||||
if err := os.Chmod(dir, boxDirMode); err != nil {
|
||||
return fmt.Errorf("sandbox.fillReadOnlyDir - chmod: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// removeTree makes read-only directories writable again and removes path.
|
||||
// The sandbox user owns build output and may have left symlinks there, so
|
||||
// the walk goes through an os.Root, which never follows a link out of path.
|
||||
func removeTree(path string) error {
|
||||
if root, err := os.OpenRoot(path); err == nil {
|
||||
_ = fs.WalkDir(root.FS(), ".", func(name string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr == nil && entry.IsDir() {
|
||||
_ = root.Chmod(name, ownerOnlyMode) // RemoveAll reports what remains.
|
||||
}
|
||||
return nil
|
||||
})
|
||||
_ = root.Close() // Only the walk used it.
|
||||
}
|
||||
if err := os.RemoveAll(path); err != nil {
|
||||
return fmt.Errorf("sandbox.removeTree - remove: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validFileName(name string) bool {
|
||||
return name != "" && name == filepath.Base(name) && !strings.HasPrefix(name, ".")
|
||||
}
|
||||
|
||||
// emptyWorkRoot removes every entry of root, for example boxes of a process
|
||||
// that crashed, and creates root when it is missing.
|
||||
func emptyWorkRoot(root string) error {
|
||||
@@ -75,8 +172,7 @@ func emptyWorkRoot(root string) error {
|
||||
return fmt.Errorf("sandbox.emptyWorkRoot - list: %w", err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
box := &Box{dir: filepath.Join(root, entry.Name())}
|
||||
if err := box.Remove(); err != nil {
|
||||
if err := removeTree(filepath.Join(root, entry.Name())); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,10 +142,14 @@ func (h *Handler) toJudgeRequest(req *api.RunRequest) (judge.Request, []api.Prob
|
||||
fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, groupPointer+"/id"))
|
||||
}
|
||||
groupIDs[group.ID] = true
|
||||
spec, valid := h.toCheckerSpec(group.Checker)
|
||||
if !valid {
|
||||
fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, groupPointer+"/checker"))
|
||||
}
|
||||
converted := judge.Group{
|
||||
ID: string(group.ID),
|
||||
Visibility: judge.Visibility(group.Visibility),
|
||||
Checker: checker.Spec{Kind: checker.Kind(group.Checker.Kind)},
|
||||
Checker: spec,
|
||||
Tests: make([]judge.Test, 0, len(group.Tests)),
|
||||
}
|
||||
testIDs := make(map[api.TestKey]bool, len(group.Tests))
|
||||
@@ -165,6 +169,31 @@ func (h *Handler) toJudgeRequest(req *api.RunRequest) (judge.Request, []api.Prob
|
||||
return request, fieldErrors
|
||||
}
|
||||
|
||||
// toCheckerSpec converts a checker and reports whether its parameters fit
|
||||
// its kind: numbers needs a positive tolerance, custom needs a program in a
|
||||
// supported language, and other kinds take no parameter.
|
||||
func (h *Handler) toCheckerSpec(source api.Checker) (checker.Spec, bool) {
|
||||
spec := checker.Spec{
|
||||
Kind: checker.Kind(source.Kind),
|
||||
AbsTolerance: source.AbsTolerance.Or(0),
|
||||
RelTolerance: source.RelTolerance.Or(0),
|
||||
}
|
||||
hasTolerance := source.AbsTolerance.IsSet() || source.RelTolerance.IsSet()
|
||||
if program, ok := source.Program.Get(); ok {
|
||||
spec.Program = &checker.Program{Language: string(program.Language), Source: program.Source}
|
||||
}
|
||||
switch spec.Kind {
|
||||
case checker.Numbers:
|
||||
return spec, spec.Program == nil && spec.AbsTolerance+spec.RelTolerance > 0
|
||||
case checker.Custom:
|
||||
return spec, !hasTolerance && spec.Program != nil && h.supports(spec.Program.Language)
|
||||
case checker.Exact, checker.Tokens:
|
||||
return spec, !hasTolerance && spec.Program == nil
|
||||
default:
|
||||
return spec, false
|
||||
}
|
||||
}
|
||||
|
||||
func toRunStatus(snapshot jobs.Snapshot) api.RunStatus {
|
||||
status := api.RunStatus{RunID: snapshot.ID, State: api.RunStateRunning}
|
||||
if snapshot.State != jobs.Finished || snapshot.Result == nil {
|
||||
|
||||
@@ -82,7 +82,7 @@ func startServer(t *testing.T) *testServer {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager: %v", err)
|
||||
}
|
||||
supports := func(language string) bool { return language == "python3" }
|
||||
supports := func(language string) bool { return language == "python3" || language == "go" }
|
||||
handler := NewHandler(manager, supports, func() bool { return !manager.Draining() }, 3*time.Second, logger)
|
||||
httpHandler, err := New(handler, testToken, maxBody, logger)
|
||||
if err != nil {
|
||||
@@ -233,6 +233,29 @@ func TestSubmitRunIsIdempotentAndAnswersBusy(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmitRunAcceptsParameterizedCheckers(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
server := startServer(t)
|
||||
body := runBody(secretSource)
|
||||
groups := body["groups"].([]any)
|
||||
numbers := map[string]any{
|
||||
"id": "hidden-1", "visibility": "hidden", "checker": map[string]any{"kind": "numbers", "abs_tolerance": 1e-6},
|
||||
"tests": []any{map[string]any{"id": "t1", "input": "1", "expected_output": "0.5"}},
|
||||
}
|
||||
custom := map[string]any{
|
||||
"id": "hidden-2", "visibility": "hidden",
|
||||
"checker": map[string]any{"kind": "custom", "program": map[string]any{"language": "python3", "source": "raise SystemExit(0)"}},
|
||||
"tests": []any{map[string]any{"id": "t1", "input": "1", "expected_output": "1"}},
|
||||
}
|
||||
body["groups"] = append(groups, numbers, custom)
|
||||
body["language"] = "go"
|
||||
response, decoded := server.do(t, http.MethodPut, runPath(uuid.New()), testToken, body)
|
||||
if response.StatusCode != http.StatusAccepted {
|
||||
t.Fatalf("PUT = %d %v, want 202", response.StatusCode, decoded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmitRunValidatesTheRequest(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -267,6 +290,20 @@ func TestSubmitRunValidatesTheRequest(t *testing.T) {
|
||||
t.Fatalf("invalid run ID = %d %v, want 400", response.StatusCode, body)
|
||||
}
|
||||
|
||||
for name, checkerValue := range map[string]map[string]any{
|
||||
"numbers without tolerance": {"kind": "numbers"},
|
||||
"exact with tolerance": {"kind": "exact", "abs_tolerance": 0.1},
|
||||
"custom without program": {"kind": "custom"},
|
||||
"tokens with program": {"kind": "tokens", "program": map[string]any{"language": "python3", "source": "x"}},
|
||||
} {
|
||||
invalid := runBody(secretSource)
|
||||
invalid["groups"].([]any)[0].(map[string]any)["checker"] = checkerValue
|
||||
response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, invalid)
|
||||
if response.StatusCode != http.StatusBadRequest || body["errors"].([]any)[0].(map[string]any)["pointer"] != "/groups/0/checker" {
|
||||
t.Fatalf("%s = %d %v, want 400 at /groups/0/checker", name, response.StatusCode, body)
|
||||
}
|
||||
}
|
||||
|
||||
response, body = server.do(t, http.MethodGet, runPath(uuid.New()), testToken, nil)
|
||||
if response.StatusCode != http.StatusNotFound || body["code"] != "not_found" {
|
||||
t.Fatalf("unknown run = %d %v, want 404", response.StatusCode, body)
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
// Custom checker of the pair task in Go, with the same rules as
|
||||
// pair_checker.py.
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
input, err := os.ReadFile(os.Args[1])
|
||||
if err != nil {
|
||||
os.Exit(3)
|
||||
}
|
||||
actual, err := os.ReadFile(os.Args[3])
|
||||
if err != nil {
|
||||
os.Exit(3)
|
||||
}
|
||||
lines := strings.Split(string(input), "\n")
|
||||
target, _ := strconv.Atoi(strings.TrimSpace(lines[0]))
|
||||
var values []int
|
||||
for _, field := range strings.Fields(lines[1]) {
|
||||
value, _ := strconv.Atoi(field)
|
||||
values = append(values, value)
|
||||
}
|
||||
answer := strings.Fields(string(actual))
|
||||
if len(answer) != 2 {
|
||||
os.Exit(1)
|
||||
}
|
||||
first, errFirst := strconv.Atoi(answer[0])
|
||||
second, errSecond := strconv.Atoi(answer[1])
|
||||
valid := errFirst == nil && errSecond == nil && first != second &&
|
||||
first >= 1 && first <= len(values) && second >= 1 && second <= len(values)
|
||||
if valid && values[first-1]+values[second-1] == target {
|
||||
os.Exit(0)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
# Custom checker of the pair task: accepts any two distinct 1-based
|
||||
# positions whose values add up to the target. Exit 0 accepts, 1 rejects.
|
||||
import sys
|
||||
|
||||
with open(sys.argv[1]) as stream:
|
||||
lines = stream.read().split("\n")
|
||||
with open(sys.argv[3]) as stream:
|
||||
answer = stream.read().split()
|
||||
target = int(lines[0])
|
||||
values = [int(token) for token in lines[1].split()]
|
||||
try:
|
||||
first, second = (int(token) for token in answer)
|
||||
except ValueError:
|
||||
sys.exit(1)
|
||||
valid = 1 <= first <= len(values) and 1 <= second <= len(values) and first != second
|
||||
sys.exit(0 if valid and values[first - 1] + values[second - 1] == target else 1)
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package main
|
||||
|
||||
func main() {
|
||||
unused := 1
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
scanner.Split(bufio.ScanWords)
|
||||
var total, count float64
|
||||
for scanner.Scan() {
|
||||
value, err := strconv.ParseFloat(scanner.Text(), 64)
|
||||
if err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
total += value
|
||||
count++
|
||||
}
|
||||
fmt.Printf("%.9f\n", total/count)
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
var target int
|
||||
if _, err := fmt.Fscan(reader, &target); err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
seen := map[int]int{}
|
||||
scanner := bufio.NewScanner(reader)
|
||||
scanner.Split(bufio.ScanWords)
|
||||
for position := 1; scanner.Scan(); position++ {
|
||||
value, err := strconv.Atoi(scanner.Text())
|
||||
if err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
if first, ok := seen[target-value]; ok {
|
||||
fmt.Println(first, position)
|
||||
return
|
||||
}
|
||||
if _, ok := seen[value]; !ok {
|
||||
seen[value] = position
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
// Wrong: always answers the first two positions.
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
fmt.Println(1, 2)
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
scanner.Split(bufio.ScanWords)
|
||||
total := new(big.Int)
|
||||
for scanner.Scan() {
|
||||
value, ok := new(big.Int).SetString(scanner.Text(), 10)
|
||||
if !ok {
|
||||
os.Exit(2)
|
||||
}
|
||||
total.Add(total, value)
|
||||
}
|
||||
fmt.Println(total)
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
// Wrong: int64 overflows, so only the group with huge numbers fails.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
scanner.Split(bufio.ScanWords)
|
||||
var total int64
|
||||
for scanner.Scan() {
|
||||
value, err := strconv.ParseInt(scanner.Text(), 10, 64)
|
||||
if err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
total += value
|
||||
}
|
||||
fmt.Println(total)
|
||||
}
|
||||
Vendored
+73
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"schema": "lincodex.runner-judge-fixtures/v1",
|
||||
"description": "Reference solutions in Python and Go with their expected outcome per test group. Each task has one public and three hidden groups; checkers.program names a checker source under this directory.",
|
||||
"limits": {"time_limit_ms": 2000, "memory_limit_mb": 128, "output_limit_kb": 64},
|
||||
"tasks": [
|
||||
{
|
||||
"name": "sum",
|
||||
"groups": [
|
||||
{"id": "public", "visibility": "public", "checker": {"kind": "exact"}, "tests": [
|
||||
{"id": "t1", "input": "1 2 3\n", "expected_output": "6\n"}]},
|
||||
{"id": "hidden-1", "visibility": "hidden", "checker": {"kind": "exact"}, "tests": [
|
||||
{"id": "t1", "input": "5 5\n", "expected_output": "10\n"},
|
||||
{"id": "t2", "input": "100\n", "expected_output": "100\n"}]},
|
||||
{"id": "hidden-2", "visibility": "hidden", "checker": {"kind": "tokens"}, "tests": [
|
||||
{"id": "t1", "input": "-1 -2\n", "expected_output": "-3"},
|
||||
{"id": "t2", "input": "-5 5\n", "expected_output": "0"}]},
|
||||
{"id": "hidden-3", "visibility": "hidden", "checker": {"kind": "exact"}, "tests": [
|
||||
{"id": "t1", "input": "9000000000000000000 9000000000000000000\n", "expected_output": "18000000000000000000\n"}]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "mean",
|
||||
"groups": [
|
||||
{"id": "public", "visibility": "public", "checker": {"kind": "numbers", "abs_tolerance": 1e-6}, "tests": [
|
||||
{"id": "t1", "input": "1 2 7\n", "expected_output": "3.333333333\n"}]},
|
||||
{"id": "hidden-1", "visibility": "hidden", "checker": {"kind": "numbers", "abs_tolerance": 1e-6}, "tests": [
|
||||
{"id": "t1", "input": "1 2\n", "expected_output": "1.5\n"},
|
||||
{"id": "t2", "input": "4 6\n", "expected_output": "5\n"}]},
|
||||
{"id": "hidden-2", "visibility": "hidden", "checker": {"kind": "numbers", "rel_tolerance": 1e-9}, "tests": [
|
||||
{"id": "t1", "input": "10 20 31\n", "expected_output": "20.3333333333\n"}]},
|
||||
{"id": "hidden-3", "visibility": "hidden", "checker": {"kind": "numbers", "abs_tolerance": 1e-6}, "tests": [
|
||||
{"id": "t1", "input": "1\n", "expected_output": "1\n"}]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "pair",
|
||||
"groups": [
|
||||
{"id": "public", "visibility": "public", "checker": {"kind": "custom", "program": {"language": "python3", "source": "checkers/pair_checker.py"}}, "tests": [
|
||||
{"id": "t1", "input": "9\n2 7 11 15\n", "expected_output": "1 2\n"}]},
|
||||
{"id": "hidden-1", "visibility": "hidden", "checker": {"kind": "custom", "program": {"language": "python3", "source": "checkers/pair_checker.py"}}, "tests": [
|
||||
{"id": "t1", "input": "6\n3 2 4\n", "expected_output": "2 3\n"}]},
|
||||
{"id": "hidden-2", "visibility": "hidden", "checker": {"kind": "custom", "program": {"language": "go", "source": "checkers/pair_checker.go"}}, "tests": [
|
||||
{"id": "t1", "input": "10\n5 5 1\n", "expected_output": "1 2\n"}]},
|
||||
{"id": "hidden-3", "visibility": "hidden", "checker": {"kind": "custom", "program": {"language": "go", "source": "checkers/pair_checker.go"}}, "tests": [
|
||||
{"id": "t1", "input": "0\n-3 4 3 90\n", "expected_output": "1 3\n"}]}
|
||||
]
|
||||
}
|
||||
],
|
||||
"solutions": [
|
||||
{"name": "python_sum_correct", "task": "sum", "language": "python3", "source": "python/sum_correct.py",
|
||||
"expect": {"outcome": "accepted", "groups": {"public": "accepted", "hidden-1": "accepted", "hidden-2": "accepted", "hidden-3": "accepted"}}},
|
||||
{"name": "python_sum_drops_signs", "task": "sum", "language": "python3", "source": "python/sum_drops_signs.py",
|
||||
"expect": {"outcome": "wrong_answer", "groups": {"public": "accepted", "hidden-1": "accepted", "hidden-2": "wrong_answer", "hidden-3": "accepted"}}},
|
||||
{"name": "go_sum_correct", "task": "sum", "language": "go", "source": "go/sum_correct.go",
|
||||
"expect": {"outcome": "accepted", "groups": {"public": "accepted", "hidden-1": "accepted", "hidden-2": "accepted", "hidden-3": "accepted"}}},
|
||||
{"name": "go_sum_overflows", "task": "sum", "language": "go", "source": "go/sum_overflows.go",
|
||||
"expect": {"outcome": "wrong_answer", "groups": {"public": "accepted", "hidden-1": "accepted", "hidden-2": "accepted", "hidden-3": "wrong_answer"}}},
|
||||
{"name": "go_compile_error", "task": "sum", "language": "go", "source": "go/compile_error.go",
|
||||
"expect": {"outcome": "compile_error", "groups": {"public": "compile_error", "hidden-1": "compile_error", "hidden-2": "compile_error", "hidden-3": "compile_error"}}},
|
||||
{"name": "python_mean_full_precision", "task": "mean", "language": "python3", "source": "python/mean_full_precision.py",
|
||||
"expect": {"outcome": "accepted", "groups": {"public": "accepted", "hidden-1": "accepted", "hidden-2": "accepted", "hidden-3": "accepted"}}},
|
||||
{"name": "python_mean_two_decimals", "task": "mean", "language": "python3", "source": "python/mean_two_decimals.py",
|
||||
"expect": {"outcome": "wrong_answer", "groups": {"public": "wrong_answer", "hidden-1": "accepted", "hidden-2": "wrong_answer", "hidden-3": "accepted"}}},
|
||||
{"name": "go_mean_nine_decimals", "task": "mean", "language": "go", "source": "go/mean_nine_decimals.go",
|
||||
"expect": {"outcome": "accepted", "groups": {"public": "accepted", "hidden-1": "accepted", "hidden-2": "accepted", "hidden-3": "accepted"}}},
|
||||
{"name": "python_pair_correct", "task": "pair", "language": "python3", "source": "python/pair_correct.py",
|
||||
"expect": {"outcome": "accepted", "groups": {"public": "accepted", "hidden-1": "accepted", "hidden-2": "accepted", "hidden-3": "accepted"}}},
|
||||
{"name": "go_pair_correct", "task": "pair", "language": "go", "source": "go/pair_correct.go",
|
||||
"expect": {"outcome": "accepted", "groups": {"public": "accepted", "hidden-1": "accepted", "hidden-2": "accepted", "hidden-3": "accepted"}}},
|
||||
{"name": "go_pair_first_two", "task": "pair", "language": "go", "source": "go/pair_first_two.go",
|
||||
"expect": {"outcome": "wrong_answer", "groups": {"public": "accepted", "hidden-1": "wrong_answer", "hidden-2": "accepted", "hidden-3": "wrong_answer"}}}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import sys
|
||||
|
||||
values = [int(token) for token in sys.stdin.read().split()]
|
||||
print(sum(values) / len(values))
|
||||
@@ -0,0 +1,5 @@
|
||||
# Wrong: rounds to two decimals, so only exact means pass the tolerance.
|
||||
import sys
|
||||
|
||||
values = [int(token) for token in sys.stdin.read().split()]
|
||||
print(f"{sum(values) / len(values):.2f}")
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
# Prints any pair of 1-based positions whose values add up to the target.
|
||||
import sys
|
||||
|
||||
lines = sys.stdin.read().split("\n")
|
||||
target = int(lines[0])
|
||||
values = [int(token) for token in lines[1].split()]
|
||||
seen = {}
|
||||
for position, value in enumerate(values, start=1):
|
||||
if target - value in seen:
|
||||
print(seen[target - value], position)
|
||||
break
|
||||
seen.setdefault(value, position)
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import sys
|
||||
|
||||
print(sum(int(token) for token in sys.stdin.read().split()))
|
||||
@@ -0,0 +1,4 @@
|
||||
# Wrong: adds absolute values, so only groups with negative numbers fail.
|
||||
import sys
|
||||
|
||||
print(sum(abs(int(token)) for token in sys.stdin.read().split()))
|
||||
Reference in new issue
Block a user