diff --git a/api/README.en.md b/api/README.en.md index d2075e3..101e7b7 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -109,7 +109,8 @@ The ML service answers its errors with the same `Problem` schema. Its `ProblemCo - Data. `RunRequest` carries only the language, the source code, the limits, and the test groups; each group has a label, a visibility (`public` or `hidden`), a checker kind, and tests with an input and an expected output. It has no candidate, account, attempt, task, or company field; `scripts/test_runner_contract.py` checks this for every request schema, together with `additionalProperties: false` on every request object. - Idempotency. `PUT /v1/runs/{run_id}` (`SubmitRun`) takes a random UUID from the backend. A new ID with a free slot starts the run and answers 202, the same ID with the same body returns the current state with 200 without running again, and the same ID with a different body answers 422 `idempotency_key_reused`. Bodies are compared by a SHA-256 fingerprint of the decoded request. When every slot is busy or the process is stopping, the answer is 503 `runner_busy` with `Retry-After`; nothing is stored, and the backend keeps the queue. - Result. `GetRun` returns `state` (`running` or `finished`) and, per group, the outcome `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error`, or `infrastructure_failure`, the number of passed tests, the CPU time, and the peak memory. `limit` names the limit that stopped a test (`cpu_time`, `wall_time`, `memory`, `output`, `processes`). Only public tests carry a stderr diagnostic; hidden tests never carry program output. -- Checker. The current kinds are `exact` (comparison after normalizing CRLF, trailing spaces of lines, and trailing empty lines) and `tokens` (token sequences split on ASCII whitespace). The `Checker` object grows with new `kind` values and optional parameters, such as a float tolerance. +- Languages: `python3` and `go`. Go is compiled in a separate phase with its own limits; a compile error gives `compile_error` and no test runs. +- A checker is set per group: `exact` (comparison after normalizing CRLF, trailing spaces of lines, and trailing empty lines), `tokens` (token sequences split on ASCII whitespace), `numbers` (like `tokens`, but numbers are equal within `abs_tolerance` or `rel_tolerance`), and `custom` (`program` with the language and source of the task family checker; it runs in nsjail, reads the files input, expected, and actual, and answers with exit status 0 or 1). The server rejects parameters that do not fit the checker kind. - Errors use the api/core `Problem` shape with a runner-specific `ProblemCode` enum: `validation_failed`, `unauthenticated`, `not_found`, `method_not_allowed`, `payload_too_large`, `unsupported_media_type`, `idempotency_key_reused`, `internal`, and `runner_busy`. `scripts/test_runner_contract.py` checks that the shape matches api/core. ### Identity: sessions, cookie, and CSRF diff --git a/api/README.md b/api/README.md index 97ef724..d1b352b 100644 --- a/api/README.md +++ b/api/README.md @@ -109,7 +109,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Данные. `RunRequest` содержит только язык, исходный код, лимиты и группы тестов; у каждой группы есть метка, видимость (`public` или `hidden`), вид checker и тесты с входом и ожидаемым выводом. Полей кандидата, аккаунта, попытки, задания или компании нет; `scripts/test_runner_contract.py` проверяет это для всех схем запросов, а также `additionalProperties: false` у каждого объекта запроса. - Идемпотентность. `PUT /v1/runs/{run_id}` (`SubmitRun`) принимает случайный UUID от backend. Новый ID при свободном слоте запускает прогон и отвечает 202, тот же ID с тем же телом возвращает текущее состояние с 200 без повторного запуска, тот же ID с другим телом дает 422 `idempotency_key_reused`. Тела сравниваются по SHA-256 отпечатку разобранного запроса. Когда все слоты заняты или процесс останавливается, ответ - 503 `runner_busy` с `Retry-After`; ничего не сохраняется, очередь держит backend. - Результат. `GetRun` возвращает `state` (`running` или `finished`) и итог по каждой группе: `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` или `infrastructure_failure`, число пройденных тестов, время CPU и пиковую память. `limit` называет сработавший лимит (`cpu_time`, `wall_time`, `memory`, `output`, `processes`). Диагностика stderr есть только у публичных тестов; у скрытых тестов нет вывода программы. -- Checker. Сейчас есть `exact` (сравнение после нормализации CRLF, хвостовых пробелов строк и пустых строк в конце) и `tokens` (последовательности токенов по ASCII-пробелам). Объект `Checker` расширяется новыми `kind` и необязательными параметрами, например допуском для чисел. +- Языки: `python3` и `go`. Go компилируется отдельной фазой со своими лимитами; ошибка компиляции дает `compile_error` без запуска тестов. +- Checker задается для группы: `exact` (сравнение после нормализации CRLF, хвостовых пробелов строк и пустых строк в конце), `tokens` (последовательности токенов по ASCII-пробелам), `numbers` (как `tokens`, но числа равны в пределах `abs_tolerance` или `rel_tolerance`) и `custom` (`program` с языком и исходником checker семейства заданий; он работает в nsjail, читает файлы input, expected и actual и отвечает кодом выхода 0 или 1). Сервер отклоняет параметры, не подходящие виду checker. - Ошибки используют форму `Problem` из api/core; перечисление `ProblemCode` свое: `validation_failed`, `unauthenticated`, `not_found`, `method_not_allowed`, `payload_too_large`, `unsupported_media_type`, `idempotency_key_reused`, `internal` и `runner_busy`. Совпадение формы с api/core проверяет `scripts/test_runner_contract.py`. ### Identity: сессии, cookie и CSRF diff --git a/api/runner/components/schemas.yml b/api/runner/components/schemas.yml index 5814c64..d4fb009 100644 --- a/api/runner/components/schemas.yml +++ b/api/runner/components/schemas.yml @@ -168,9 +168,10 @@ RunRequest: $ref: '#/TestGroup' RunLanguage: type: string - description: 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. + description: 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. `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. enum: - python3 + - go RunLimits: type: object description: Limits applied to every test of the run. @@ -234,21 +235,55 @@ TestVisibility: - hidden Checker: type: object - description: 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. + description: 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. additionalProperties: false required: - kind properties: kind: $ref: '#/CheckerKind' + abs_tolerance: + type: number + format: double + minimum: 0 + maximum: 1000000000 + description: Largest accepted absolute difference of two numeric tokens. + rel_tolerance: + type: number + format: double + minimum: 0 + maximum: 1 + description: Largest accepted difference of two numeric tokens relative to the expected value. + program: + $ref: '#/CheckerProgram' +CheckerProgram: + type: object + description: '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.' + additionalProperties: false + required: + - language + - source + properties: + language: + $ref: '#/RunLanguage' + source: + type: string + minLength: 1 + maxLength: 65536 CheckerKind: type: string description: '- 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.' + - 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.' enum: - exact - tokens + - numbers + - custom TestCase: type: object additionalProperties: false diff --git a/api/runner/components/schemas/run_schemas.yml b/api/runner/components/schemas/run_schemas.yml index 562af70..4c7ba73 100644 --- a/api/runner/components/schemas/run_schemas.yml +++ b/api/runner/components/schemas/run_schemas.yml @@ -37,9 +37,14 @@ schemas: description: >- 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. + 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. enum: - python3 + - go RunLimits: type: object description: Limits applied to every test of the run. @@ -120,22 +125,64 @@ schemas: type: object description: >- 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. + `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. additionalProperties: false required: - kind properties: kind: $ref: "#/schemas/CheckerKind" + abs_tolerance: + type: number + format: double + minimum: 0 + maximum: 1000000000 + description: Largest accepted absolute difference of two numeric tokens. + rel_tolerance: + type: number + format: double + minimum: 0 + maximum: 1 + description: >- + Largest accepted difference of two numeric tokens relative to the + expected value. + program: + $ref: "#/schemas/CheckerProgram" + CheckerProgram: + type: object + description: >- + 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. + additionalProperties: false + required: + - language + - source + properties: + language: + $ref: "#/schemas/RunLanguage" + source: + type: string + minLength: 1 + maxLength: 65536 CheckerKind: type: string description: |- - 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. enum: - exact - tokens + - numbers + - custom TestCase: type: object additionalProperties: false diff --git a/api/runner/openapi.bundle.yml b/api/runner/openapi.bundle.yml index f77ed50..9f6653f 100644 --- a/api/runner/openapi.bundle.yml +++ b/api/runner/openapi.bundle.yml @@ -93,8 +93,10 @@ paths: 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. + 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. tags: - runs requestBody: @@ -518,9 +520,10 @@ components: $ref: '#/components/schemas/RunResult' RunLanguage: type: string - description: 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. + description: 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. `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. enum: - python3 + - go RunLimits: type: object description: Limits applied to every test of the run. @@ -553,18 +556,50 @@ components: description: |- - 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. enum: - exact - tokens + - numbers + - custom + CheckerProgram: + type: object + description: '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.' + additionalProperties: false + required: + - language + - source + properties: + language: + $ref: '#/components/schemas/RunLanguage' + source: + type: string + minLength: 1 + maxLength: 65536 Checker: type: object - description: 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. + description: 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. additionalProperties: false required: - kind properties: kind: $ref: '#/components/schemas/CheckerKind' + abs_tolerance: + type: number + format: double + minimum: 0 + maximum: 1000000000 + description: Largest accepted absolute difference of two numeric tokens. + rel_tolerance: + type: number + format: double + minimum: 0 + maximum: 1 + description: Largest accepted difference of two numeric tokens relative to the expected value. + program: + $ref: '#/components/schemas/CheckerProgram' TestCase: type: object additionalProperties: false diff --git a/api/runner/routes/runs.yml b/api/runner/routes/runs.yml index 6249553..ba28cda 100644 --- a/api/runner/routes/runs.yml +++ b/api/runner/routes/runs.yml @@ -26,8 +26,10 @@ put: 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. + 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. tags: - runs requestBody: diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_client_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_client_gen.go index dffd69f..b88566e 100644 --- a/backend/internal/adapter/secondary/code_runner/api/oas_client_gen.go +++ b/backend/internal/adapter/secondary/code_runner/api/oas_client_gen.go @@ -65,8 +65,9 @@ type Invoker 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, request *RunRequest, params SubmitRunParams) (SubmitRunRes, error) @@ -422,8 +423,9 @@ func (c *Client) sendGetRunnerReadyz(ctx context.Context) (res GetRunnerReadyzRe // 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 (c *Client) SubmitRun(ctx context.Context, request *RunRequest, params SubmitRunParams) (SubmitRunRes, error) { diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_json_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_json_gen.go index 1c39f15..247d8df 100644 --- a/backend/internal/adapter/secondary/code_runner/api/oas_json_gen.go +++ b/backend/internal/adapter/secondary/code_runner/api/oas_json_gen.go @@ -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) } diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_schemas_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_schemas_gen.go index f4c89f0..cb6f9b8 100644 --- a/backend/internal/adapter/secondary/code_runner/api/oas_schemas_gen.go +++ b/backend/internal/adapter/secondary/code_runner/api/oas_schemas_gen.go @@ -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) } diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_validators_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_validators_gen.go index a84d549..cb8cf57 100644 --- a/backend/internal/adapter/secondary/code_runner/api/oas_validators_gen.go +++ b/backend/internal/adapter/secondary/code_runner/api/oas_validators_gen.go @@ -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) } diff --git a/deploy/docker/docker-compose.runner.dev.yml b/deploy/docker/docker-compose.runner.dev.yml index e52cf91..4701169 100644 --- a/deploy/docker/docker-compose.runner.dev.yml +++ b/deploy/docker/docker-compose.runner.dev.yml @@ -31,7 +31,8 @@ services: secrets: - runner_api_token tmpfs: - - /var/lib/lincodex-runner/work:size=64m,mode=0711 + # exec: compiled Go solutions run from their box; nosuid and nodev stay. + - /var/lib/lincodex-runner/work:size=128m,mode=0711,exec ports: - "127.0.0.1:${RUNNER_DEV_HTTP_PORT:-8070}:8080" healthcheck: diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index cdf8776..b0af775 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -740,9 +740,13 @@ Isolation layers of one run (implemented): The service bounds concurrent runs (1 by default) and answers 503 `runner_busy` when no slot is free; the backend keeps the queue. The contract and the configuration bound the request body, the source, the inputs, and the output. Logs carry only the method, operation, status, duration, run ID, language, group and test counts, and outcome; the source, test data, program output, and token never reach a log. Runs live only in memory and are forgotten after their TTL; the backend resubmits a run lost in a restart. -Outcomes distinguish `accepted`, `wrong_answer`, `compile_error` (for Python, a syntax check with `compile()` before the tests), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (including the process limit), and `infrastructure_failure`. Test time is the CPU time of every process of the test, including interpreter startup; memory is the cgroup peak of the test, including nsjail and file cache charged to the test. +Languages. Python 3 runs on the image's interpreter in isolated mode after a syntax check with `compile()`. Go is compiled in a separate phase with its own limits (20 s CPU, 768 MiB, files up to 64 MiB): `go tool compile` and `go tool link` run in separate jails and read a standard library prebuilt into the image through an importcfg, so they need no build cache, modules, cgo, or network, and only the standard library can be imported. A run directory consists of the source (`/box`, read-only) and the build output (`/out`): only compile steps write it, and tests see it read-only. A compile or link error is `compile_error` with the compiler message, and no test runs. -Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; Go (compile and run); a float tolerance checker and custom checkers; calls from the backend and the run queue; service metrics; the full A16 isolation suite built on `runner/testdata/hostile/`. +A checker is set per group: `exact`, `tokens`, `numbers` (numeric tokens are equal within an absolute or relative tolerance), and `custom`. A custom checker is a task family program in Python or Go; it is built once per run and runs in nsjail with the same isolation as the solution and limits of its own (5 s CPU, 256 MiB). It receives the input, the expected output, and the actual output as read-only files in `/check` and answers with its exit status: 0 accepts, 1 rejects, and anything else is a checker failure, that is, `infrastructure_failure`. Its output is discarded. The result is returned per group; hidden test content, program output, and hidden test diagnostics never reach the response. + +Outcomes distinguish `accepted`, `wrong_answer`, `compile_error` (for Python, a syntax check with `compile()` before the tests; for Go, compile and link), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (including the process limit), and `infrastructure_failure`. Test time is the CPU time of every process of the test, including interpreter startup; memory is the cgroup peak of the test, including nsjail and file cache charged to the test. + +Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; calls from the backend and the run queue; service metrics; the full A16 isolation suite built on `runner/testdata/hostile/`. ## Matching and explanations diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 4de2e1a..cebb79f 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -737,7 +737,7 @@ Cleanup before the rollout removed only the Docker build cache (`docker builder ## Code runner -The `runner/Dockerfile` image holds the Go supervisor, nsjail, and Python from `python:alpine`; pip and ensurepip are removed. The base images are the `GO_IMAGE` and `RUNTIME_IMAGE` arguments, so a release build can pin their digests. The supervisor runs as root inside its own host or VM because it needs namespaces, user mapping, and writes to its delegated cgroup. Candidate programs run as uid 99999 without capabilities. +The `runner/Dockerfile` image holds the Go supervisor, nsjail, Python from `python:alpine`, and, for Go solutions, the `compile` and `link` tools with a standard library prebuilt from `GO_IMAGE`; pip and ensurepip are removed. The base images are the `GO_IMAGE` and `RUNTIME_IMAGE` arguments, so a release build can pin their digests. The supervisor runs as root inside its own host or VM because it needs namespaces, user mapping, and writes to its delegated cgroup. Candidate programs run as uid 99999 without capabilities. ### Local (development only) @@ -764,9 +764,10 @@ The runner runs only in the `lincodex-runner` VM on the `lxdbr-runner` bridge (s | `RUNNER_MAX_REQUEST_BYTES` | `8388608` | Request body limit | | `RUNNER_RESULT_TTL`, `RUNNER_MAX_RETAINED_RUNS` | `15m`, `256` | In-memory result retention | | `RUNNER_RETRY_AFTER`, `RUNNER_SHUTDOWN_TIMEOUT` | `2s`, `30s` | Retry-After when busy and the wait for runs at shutdown | -| `RUNNER_WORK_DIR` | `/var/lib/lincodex-runner/work` | Run directories; emptied at startup, tmpfs recommended | +| `RUNNER_WORK_DIR` | `/var/lib/lincodex-runner/work` | Run directories; emptied at startup; a tmpfs with `exec` (built Go solutions run from it), `nosuid`, and `nodev` | | `RUNNER_CGROUP_ROOT` | `/sys/fs/cgroup` | The service's delegated cgroup v2 | | `RUNNER_NSJAIL_PATH`, `RUNNER_PYTHON_PATH` | `/usr/bin/nsjail`, `/usr/local/bin/python3` | Paths in the image | +| `RUNNER_GO_TOOL_DIR` | `/usr/local/lib/lincodex-runner/go` | `compile`, `link`, `importcfg`, and the prebuilt Go standard library in the image | | `RUNNER_SANDBOX_UID` | `99999` | Program user, never root | | `RUNNER_SANDBOX_MAX_PROCESSES` | `16` | Processes and threads of a run | | `RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES` | `4194304` | Memory allowance for nsjail above the task limit | diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 4fc3d72..fdb2fc7 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -588,10 +588,12 @@ The tests do not run the Make targets against a real stack. A manual check on a | make -C runner test | Unit tests with the race detector: checkers, configuration, judge outcomes on a scripted sandbox, idempotency and busy handling of the run manager, the HTTP API (token, 202/200/422/503, 400, 413, 404), and that logs carry no source, input, or token | | make -C runner lint | golangci-lint for Linux, including the isolation tests | | make -C runner check-generated | The generated ogen server matches the bundle | -| make -C runner test-sandbox | Isolation tests in a privileged dev container with real nsjail and cgroup v2 | +| make -C runner test-sandbox | Reference solutions and isolation tests in a privileged dev container with real nsjail and cgroup v2 | | make -C deploy check-runner-dev | Dev switches stay out of production files | -`test-sandbox` runs every case of `runner/testdata/hostile/manifest.json` twice: a correct solution is accepted with its time and memory recorded; a syntax error gives `compile_error`; the CPU limit stops an infinite loop, the wall-clock limit a sleep, the cgroup memory limit a memory leak, the output limit endless output, and the process limit a fork bomb (`runtime_error`); network, file system, and privilege probes confirm that there is no network, the root and the source are read-only, runner files are not visible, and the program is not root. After every case and after the series the test checks that the run directory is empty, the run cgroups are gone, and no uid 99999 process is left. It runs without a separate init, so it also confirms that nsjail reaps every stopped process. +First, `test-sandbox` runs the reference solutions of `runner/testdata/judge/manifest.json` on three tasks with one public and three hidden groups: correct and incorrect Python and Go solutions get the expected outcome of every group (`exact` and `tokens`; `numbers` on fractional answers with an absolute and a relative tolerance; `custom` with a Python and a Go checker in nsjail); Go code with a compile error gives `compile_error` with a `main.go:` message and no test runs. The test also checks that a group stops at its first failed test, hidden tests carry no diagnostic, and the run directories and cgroups are removed. + +Then `test-sandbox` runs every case of `runner/testdata/hostile/manifest.json` twice: a correct solution is accepted with its time and memory recorded; a syntax error gives `compile_error`; the CPU limit stops an infinite loop, the wall-clock limit a sleep, the cgroup memory limit a memory leak, the output limit endless output, and the process limit a fork bomb (`runtime_error`); network, file system, and privilege probes confirm that there is no network, the root and the source are read-only, runner files are not visible, and the program is not root. After every case and after the series the test checks that the run directory is empty, the run cgroups are gone, and no uid 99999 process is left. It runs without a separate init, so it also confirms that nsjail reaps every stopped process. What the tests do not prove: isolation in the production VM (they have not run there yet), protection against kernel, nsjail, or cgroup vulnerabilities, the absence of side channels, or behavior under load. The full A16 isolation suite is planned separately and will extend the same fixtures. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index d4a5d20..3ddbb97 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -740,9 +740,13 @@ contact_grant относится к паре кандидат-компания Сервис ограничивает число параллельных прогонов (по умолчанию 1) и отвечает 503 `runner_busy` при занятом слоте; очередь держит backend. Размер тела запроса, исходника, входа и вывода ограничен контрактом и конфигурацией. Логи содержат только метод, операцию, статус, длительность, run ID, язык, число групп и тестов и исход; исходник, тестовые данные, вывод программы и токен в логи не попадают. Прогоны хранятся только в памяти и забываются после TTL; потерянный при рестарте прогон backend отправляет снова. -Исходы различают `accepted`, `wrong_answer`, `compile_error` (для Python - проверка синтаксиса через `compile()` до тестов), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (включая лимит процессов) и `infrastructure_failure`. Время теста - CPU всех процессов теста вместе с запуском интерпретатора; память - пик cgroup теста, включая nsjail и файловый кеш, отнесенный к тесту. +Языки. Python 3 запускается интерпретатором образа в изолированном режиме после проверки синтаксиса через `compile()`. Go компилируется отдельной фазой со своими лимитами (20 с CPU, 768 MiB, файлы до 64 MiB): `go tool compile` и `go tool link` в отдельных jail читают заранее собранную стандартную библиотеку из образа по importcfg, поэтому не нужны build cache, модули, cgo и сеть, а импортировать можно только стандартную библиотеку. Каталог прогона состоит из исходника (`/box`, только чтение) и результата сборки (`/out`): его пишут только шаги компиляции, тесты видят его только для чтения. Ошибка компиляции или линковки - `compile_error` с сообщением компилятора, тесты не запускаются. -Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; Go (компиляция и запуск); checker с допуском для чисел и собственный checker; вызов исполнителя из backend и очередь прогонов; метрики сервиса; полный набор проверок изоляции A16 на базе `runner/testdata/hostile/`. +Checker задается для группы: `exact`, `tokens`, `numbers` (числовые токены равны в пределах абсолютного или относительного допуска) и `custom`. Custom checker - программа семейства заданий на Python или Go; она собирается один раз за прогон и запускается в nsjail с той же изоляцией, что и решение, и с собственными лимитами (5 с CPU, 256 MiB). Вход, ожидаемый и фактический вывод она получает файлами только для чтения в `/check` и отвечает кодом выхода: 0 - принять, 1 - отклонить, иначе - сбой checker, то есть `infrastructure_failure`. Вывод checker отбрасывается. Результат возвращается по группам; содержимое скрытых тестов, вывод программы и диагностика скрытых тестов в ответ не попадают. + +Исходы различают `accepted`, `wrong_answer`, `compile_error` (для Python - проверка синтаксиса через `compile()` до тестов, для Go - компиляция и линковка), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (включая лимит процессов) и `infrastructure_failure`. Время теста - CPU всех процессов теста вместе с запуском интерпретатора; память - пик cgroup теста, включая nsjail и файловый кеш, отнесенный к тесту. + +Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; вызов исполнителя из backend и очередь прогонов; метрики сервиса; полный набор проверок изоляции A16 на базе `runner/testdata/hostile/`. ## Подбор и объяснение diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 6f246b3..14739b5 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -739,7 +739,7 @@ lxd init --preseed < deploy/labs/lxd-preseed.yaml ## Исполнитель кода -Образ `runner/Dockerfile` содержит Go-супервизор, nsjail и Python из `python:alpine`; pip и ensurepip удалены. Базовые образы - аргументы `GO_IMAGE` и `RUNTIME_IMAGE`, поэтому сборка выпуска может закрепить их digest. Супервизор работает root внутри своего хоста или VM: ему нужны namespaces, отображение пользователя и запись в делегированную cgroup. Программы кандидата работают как uid 99999 без capabilities. +Образ `runner/Dockerfile` содержит Go-супервизор, nsjail, Python из `python:alpine` и для решений на Go инструменты `compile` и `link` с заранее собранной стандартной библиотекой из `GO_IMAGE`; pip и ensurepip удалены. Базовые образы - аргументы `GO_IMAGE` и `RUNTIME_IMAGE`, поэтому сборка выпуска может закрепить их digest. Супервизор работает root внутри своего хоста или VM: ему нужны namespaces, отображение пользователя и запись в делегированную cgroup. Программы кандидата работают как uid 99999 без capabilities. ### Локально (только разработка) @@ -766,9 +766,10 @@ lxd init --preseed < deploy/labs/lxd-preseed.yaml | `RUNNER_MAX_REQUEST_BYTES` | `8388608` | Лимит тела запроса | | `RUNNER_RESULT_TTL`, `RUNNER_MAX_RETAINED_RUNS` | `15m`, `256` | Хранение результатов в памяти | | `RUNNER_RETRY_AFTER`, `RUNNER_SHUTDOWN_TIMEOUT` | `2s`, `30s` | Retry-After при занятости и ожидание прогонов при остановке | -| `RUNNER_WORK_DIR` | `/var/lib/lincodex-runner/work` | Каталоги прогонов; очищается при старте, рекомендуется tmpfs | +| `RUNNER_WORK_DIR` | `/var/lib/lincodex-runner/work` | Каталоги прогонов; очищается при старте; tmpfs с `exec` (собранные Go-решения запускаются оттуда), `nosuid` и `nodev` | | `RUNNER_CGROUP_ROOT` | `/sys/fs/cgroup` | Делегированная cgroup v2 сервиса | | `RUNNER_NSJAIL_PATH`, `RUNNER_PYTHON_PATH` | `/usr/bin/nsjail`, `/usr/local/bin/python3` | Пути в образе | +| `RUNNER_GO_TOOL_DIR` | `/usr/local/lib/lincodex-runner/go` | `compile`, `link`, `importcfg` и собранная стандартная библиотека Go в образе | | `RUNNER_SANDBOX_UID` | `99999` | Пользователь программ, не root | | `RUNNER_SANDBOX_MAX_PROCESSES` | `16` | Процессы и потоки прогона | | `RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES` | `4194304` | Запас памяти на nsjail сверх лимита задания | diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index eeba231..1b4bb64 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -588,10 +588,12 @@ Vitest работает в Node без DOM, поэтому ограничени | make -C runner test | Unit-тесты с race detector: checker, конфигурация, исходы judge на сценарном sandbox, идемпотентность и занятость менеджера прогонов, HTTP API (токен, 202/200/422/503, 400, 413, 404) и отсутствие исходника, входа и токена в логах | | make -C runner lint | golangci-lint для Linux, включая тесты изоляции | | make -C runner check-generated | Сгенерированный ogen-сервер совпадает с bundle | -| make -C runner test-sandbox | Тесты изоляции в привилегированном dev-контейнере с настоящими nsjail и cgroup v2 | +| make -C runner test-sandbox | Эталонные решения и тесты изоляции в привилегированном dev-контейнере с настоящими nsjail и cgroup v2 | | make -C deploy check-runner-dev | Dev-переключатели не попадают в production-файлы | -`test-sandbox` прогоняет дважды все случаи `runner/testdata/hostile/manifest.json`: верное решение принимается с записанными временем и памятью; синтаксическая ошибка дает `compile_error`; бесконечный цикл останавливает лимит CPU, сон - лимит стены, утечка памяти - лимит памяти cgroup, бесконечный вывод - лимит вывода, fork bomb - лимит процессов (`runtime_error`); пробы сети, файловой системы и привилегий подтверждают, что сети нет, корень и исходник только для чтения, файлы runner не видны, а программа не root. После каждого случая и после серии проверяется, что каталог прогонов пуст, cgroup прогонов удалены и не осталось процессов uid 99999. Тест запускается без отдельного init, поэтому подтверждает, что nsjail забирает каждый остановленный процесс. +Сначала `test-sandbox` прогоняет эталонные решения `runner/testdata/judge/manifest.json` на трех задачах с одной публичной и тремя скрытыми группами: верные и неверные решения на Python и Go получают ожидаемый исход каждой группы (`exact` и `tokens`; `numbers` на дробных ответах с абсолютным и относительным допуском; `custom` с checker на Python и на Go в nsjail); Go-код с ошибкой компиляции дает `compile_error` с сообщением `main.go:` и ни одного запущенного теста. Тест также проверяет, что группа останавливается на первом проваленном тесте, у скрытых тестов нет диагностики, а каталоги и cgroup прогонов удалены. + +Затем `test-sandbox` прогоняет дважды все случаи `runner/testdata/hostile/manifest.json`: верное решение принимается с записанными временем и памятью; синтаксическая ошибка дает `compile_error`; бесконечный цикл останавливает лимит CPU, сон - лимит стены, утечка памяти - лимит памяти cgroup, бесконечный вывод - лимит вывода, fork bomb - лимит процессов (`runtime_error`); пробы сети, файловой системы и привилегий подтверждают, что сети нет, корень и исходник только для чтения, файлы runner не видны, а программа не root. После каждого случая и после серии проверяется, что каталог прогонов пуст, cgroup прогонов удалены и не осталось процессов uid 99999. Тест запускается без отдельного init, поэтому подтверждает, что nsjail забирает каждый остановленный процесс. Что тесты не доказывают: изоляцию в production VM (там они еще не запускались), защиту от уязвимостей ядра, nsjail или cgroup, отсутствие побочных каналов и устойчивость под нагрузкой. Полный набор проверок A16 запланирован отдельно и расширит те же fixtures. diff --git a/runner/Dockerfile b/runner/Dockerfile index ae38304..5491ec3 100644 --- a/runner/Dockerfile +++ b/runner/Dockerfile @@ -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 diff --git a/runner/Dockerfile.sandbox-test b/runner/Dockerfile.sandbox-test index ab147e4..78a1132 100644 --- a/runner/Dockerfile.sandbox-test +++ b/runner/Dockerfile.sandbox-test @@ -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"] diff --git a/runner/Makefile b/runner/Makefile index 03c845c..a9ff70e 100644 --- a/runner/Makefile +++ b/runner/Makefile @@ -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 diff --git a/runner/README.en.md b/runner/README.en.md index b77b01b..69417b3 100644 --- a/runner/README.en.md +++ b/runner/README.en.md @@ -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. diff --git a/runner/README.md b/runner/README.md index dd998cd..f3adee6 100644 --- a/runner/README.md +++ b/runner/README.md @@ -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/` - тесты изоляции и общие враждебные программы. diff --git a/runner/internal/api/oas_handlers_gen.go b/runner/internal/api/oas_handlers_gen.go index d37cc60..c8b8176 100644 --- a/runner/internal/api/oas_handlers_gen.go +++ b/runner/internal/api/oas_handlers_gen.go @@ -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) { diff --git a/runner/internal/api/oas_json_gen.go b/runner/internal/api/oas_json_gen.go index 1c39f15..247d8df 100644 --- a/runner/internal/api/oas_json_gen.go +++ b/runner/internal/api/oas_json_gen.go @@ -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) } diff --git a/runner/internal/api/oas_schemas_gen.go b/runner/internal/api/oas_schemas_gen.go index f4c89f0..cb6f9b8 100644 --- a/runner/internal/api/oas_schemas_gen.go +++ b/runner/internal/api/oas_schemas_gen.go @@ -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) } diff --git a/runner/internal/api/oas_server_gen.go b/runner/internal/api/oas_server_gen.go index 87d0791..e45447b 100644 --- a/runner/internal/api/oas_server_gen.go +++ b/runner/internal/api/oas_server_gen.go @@ -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) diff --git a/runner/internal/api/oas_unimplemented_gen.go b/runner/internal/api/oas_unimplemented_gen.go index 7946562..eaa08cf 100644 --- a/runner/internal/api/oas_unimplemented_gen.go +++ b/runner/internal/api/oas_unimplemented_gen.go @@ -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) { diff --git a/runner/internal/api/oas_validators_gen.go b/runner/internal/api/oas_validators_gen.go index a84d549..cb8cf57 100644 --- a/runner/internal/api/oas_validators_gen.go +++ b/runner/internal/api/oas_validators_gen.go @@ -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) } diff --git a/runner/internal/app/app.go b/runner/internal/app/app.go index 3f710ab..1052cc6 100644 --- a/runner/internal/app/app.go +++ b/runner/internal/app/app.go @@ -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{ diff --git a/runner/internal/checker/checker.go b/runner/internal/checker/checker.go index 3c71f90..e7bac72 100644 --- a/runner/internal/checker/checker.go +++ b/runner/internal/checker/checker.go @@ -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 { diff --git a/runner/internal/checker/checker_test.go b/runner/internal/checker/checker_test.go index 45bae4c..607db46 100644 --- a/runner/internal/checker/checker_test.go +++ b/runner/internal/checker/checker_test.go @@ -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) + } } diff --git a/runner/internal/config/config.go b/runner/internal/config/config.go index 2f0b13a..c5bd6e6 100644 --- a/runner/internal/config/config.go +++ b/runner/internal/config/config.go @@ -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)) diff --git a/runner/internal/isolationtest/isolation_test.go b/runner/internal/isolationtest/isolation_test.go index 5ea1c16..3d2be5b 100644 --- a/runner/internal/isolationtest/isolation_test.go +++ b/runner/internal/isolationtest/isolation_test.go @@ -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) { diff --git a/runner/internal/judge/custom.go b/runner/internal/judge/custom.go new file mode 100644 index 0000000..cbb3036 --- /dev/null +++ b/runner/internal/judge/custom.go @@ -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) +} diff --git a/runner/internal/judge/judge.go b/runner/internal/judge/judge.go index f601018..2605a2e 100644 --- a/runner/internal/judge/judge.go +++ b/runner/internal/judge/judge.go @@ -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), diff --git a/runner/internal/judge/judge_test.go b/runner/internal/judge/judge_test.go index bccdb7e..e8ad1a4 100644 --- a/runner/internal/judge/judge_test.go +++ b/runner/internal/judge/judge_test.go @@ -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) +} diff --git a/runner/internal/judge/language.go b/runner/internal/judge/language.go index 9c30234..7b40e13 100644 --- a/runner/internal/judge/language.go +++ b/runner/internal/judge/language.go @@ -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}, } } diff --git a/runner/internal/judgetest/doc.go b/runner/internal/judgetest/doc.go new file mode 100644 index 0000000..27fba66 --- /dev/null +++ b/runner/internal/judgetest/doc.go @@ -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 diff --git a/runner/internal/judgetest/judge_test.go b/runner/internal/judgetest/judge_test.go new file mode 100644 index 0000000..917aa44 --- /dev/null +++ b/runner/internal/judgetest/judge_test.go @@ -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) + } + } +} diff --git a/runner/internal/sandbox/executor.go b/runner/internal/sandbox/executor.go index 5c17b4e..8ec6c2c 100644 --- a/runner/internal/sandbox/executor.go +++ b/runner/internal/sandbox/executor.go @@ -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 diff --git a/runner/internal/sandbox/nsjail.go b/runner/internal/sandbox/nsjail.go index 0faba83..aed3e1c 100644 --- a/runner/internal/sandbox/nsjail.go +++ b/runner/internal/sandbox/nsjail.go @@ -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" diff --git a/runner/internal/sandbox/sandbox.go b/runner/internal/sandbox/sandbox.go index ac4e50d..0612160 100644 --- a/runner/internal/sandbox/sandbox.go +++ b/runner/internal/sandbox/sandbox.go @@ -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. diff --git a/runner/internal/sandbox/sandbox_test.go b/runner/internal/sandbox/sandbox_test.go index 13bb197..86d9c98 100644 --- a/runner/internal/sandbox/sandbox_test.go +++ b/runner/internal/sandbox/sandbox_test.go @@ -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) } } diff --git a/runner/internal/sandbox/workdir.go b/runner/internal/sandbox/workdir.go index 0c91d1c..3948549 100644 --- a/runner/internal/sandbox/workdir.go +++ b/runner/internal/sandbox/workdir.go @@ -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 } } diff --git a/runner/internal/server/handler.go b/runner/internal/server/handler.go index e353447..953a2eb 100644 --- a/runner/internal/server/handler.go +++ b/runner/internal/server/handler.go @@ -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 { diff --git a/runner/internal/server/server_test.go b/runner/internal/server/server_test.go index d581e7d..cc3a9da 100644 --- a/runner/internal/server/server_test.go +++ b/runner/internal/server/server_test.go @@ -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) diff --git a/runner/testdata/judge/checkers/pair_checker.go b/runner/testdata/judge/checkers/pair_checker.go new file mode 100644 index 0000000..545499d --- /dev/null +++ b/runner/testdata/judge/checkers/pair_checker.go @@ -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) +} diff --git a/runner/testdata/judge/checkers/pair_checker.py b/runner/testdata/judge/checkers/pair_checker.py new file mode 100644 index 0000000..7594b84 --- /dev/null +++ b/runner/testdata/judge/checkers/pair_checker.py @@ -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) diff --git a/runner/testdata/judge/go/compile_error.go b/runner/testdata/judge/go/compile_error.go new file mode 100644 index 0000000..006024b --- /dev/null +++ b/runner/testdata/judge/go/compile_error.go @@ -0,0 +1,5 @@ +package main + +func main() { + unused := 1 +} diff --git a/runner/testdata/judge/go/mean_nine_decimals.go b/runner/testdata/judge/go/mean_nine_decimals.go new file mode 100644 index 0000000..bb2c924 --- /dev/null +++ b/runner/testdata/judge/go/mean_nine_decimals.go @@ -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) +} diff --git a/runner/testdata/judge/go/pair_correct.go b/runner/testdata/judge/go/pair_correct.go new file mode 100644 index 0000000..72ebab4 --- /dev/null +++ b/runner/testdata/judge/go/pair_correct.go @@ -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 + } + } +} diff --git a/runner/testdata/judge/go/pair_first_two.go b/runner/testdata/judge/go/pair_first_two.go new file mode 100644 index 0000000..adcb0a6 --- /dev/null +++ b/runner/testdata/judge/go/pair_first_two.go @@ -0,0 +1,8 @@ +// Wrong: always answers the first two positions. +package main + +import "fmt" + +func main() { + fmt.Println(1, 2) +} diff --git a/runner/testdata/judge/go/sum_correct.go b/runner/testdata/judge/go/sum_correct.go new file mode 100644 index 0000000..bc696fd --- /dev/null +++ b/runner/testdata/judge/go/sum_correct.go @@ -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) +} diff --git a/runner/testdata/judge/go/sum_overflows.go b/runner/testdata/judge/go/sum_overflows.go new file mode 100644 index 0000000..a015625 --- /dev/null +++ b/runner/testdata/judge/go/sum_overflows.go @@ -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) +} diff --git a/runner/testdata/judge/manifest.json b/runner/testdata/judge/manifest.json new file mode 100644 index 0000000..9ef0215 --- /dev/null +++ b/runner/testdata/judge/manifest.json @@ -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"}}} + ] +} diff --git a/runner/testdata/judge/python/mean_full_precision.py b/runner/testdata/judge/python/mean_full_precision.py new file mode 100644 index 0000000..04773c3 --- /dev/null +++ b/runner/testdata/judge/python/mean_full_precision.py @@ -0,0 +1,4 @@ +import sys + +values = [int(token) for token in sys.stdin.read().split()] +print(sum(values) / len(values)) diff --git a/runner/testdata/judge/python/mean_two_decimals.py b/runner/testdata/judge/python/mean_two_decimals.py new file mode 100644 index 0000000..3cf8bec --- /dev/null +++ b/runner/testdata/judge/python/mean_two_decimals.py @@ -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}") diff --git a/runner/testdata/judge/python/pair_correct.py b/runner/testdata/judge/python/pair_correct.py new file mode 100644 index 0000000..fbf82fa --- /dev/null +++ b/runner/testdata/judge/python/pair_correct.py @@ -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) diff --git a/runner/testdata/judge/python/sum_correct.py b/runner/testdata/judge/python/sum_correct.py new file mode 100644 index 0000000..52463f0 --- /dev/null +++ b/runner/testdata/judge/python/sum_correct.py @@ -0,0 +1,3 @@ +import sys + +print(sum(int(token) for token in sys.stdin.read().split())) diff --git a/runner/testdata/judge/python/sum_drops_signs.py b/runner/testdata/judge/python/sum_drops_signs.py new file mode 100644 index 0000000..52d2b0e --- /dev/null +++ b/runner/testdata/judge/python/sum_drops_signs.py @@ -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())) diff --git a/scripts/test_runner_contract.py b/scripts/test_runner_contract.py index ef98f5e..ee6ba8c 100644 --- a/scripts/test_runner_contract.py +++ b/scripts/test_runner_contract.py @@ -209,6 +209,21 @@ class RunnerContractTest(unittest.TestCase): def test_outcomes_distinguish_every_required_result(self) -> None: self.assertEqual(set(self.schemas["RunOutcome"]["enum"]), REQUIRED_OUTCOMES) + def test_languages_and_checkers_are_declared(self) -> None: + self.assertEqual(set(self.schemas["RunLanguage"]["enum"]), {"python3", "go"}) + self.assertEqual(set(self.schemas["CheckerKind"]["enum"]), {"exact", "tokens", "numbers", "custom"}) + checker = self.schemas["Checker"]["properties"] + self.assertEqual(set(checker), {"kind", "abs_tolerance", "rel_tolerance", "program"}) + self.assertEqual(self.schemas["CheckerProgram"]["required"], ["language", "source"]) + + def test_results_never_carry_test_content(self) -> None: + # Results describe outcomes and usage; inputs, expected outputs, and + # program output have no field there. + for name in ("RunStatus", "RunResult", "CompileResult", "GroupResult", "TestResult"): + with self.subTest(schema=name): + properties = set(self.schemas[name].get("properties", {})) + self.assertFalse(properties & {"input", "expected_output", "stdout", "output", "actual_output"}) + def test_submit_run_is_idempotent_by_run_id(self) -> None: item = self.document["paths"]["/v1/runs/{run_id}"] (parameter,) = item["parameters"]