feat(runner): add the own code runner contract, client and nsjail service

This commit is contained in:
shira committed 2026-10-11 08:23:42 +03:00
1 parent 5e1db37746
commit cdf6bcbb91
109 files changed
+24084 -28

No files matched your search

+7 -3
View File
@@ -16,23 +16,27 @@ install: ## Install pinned OpenAPI tooling
npm ci --prefix "$(API_DIR)" --ignore-scripts --no-audit --no-fund
.PHONY: bundle
bundle: ## Merge split schemas and create public and ML bundles
bundle: ## Merge split schemas and create public, ML, and code runner bundles
"$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/core"
"$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/ml"
"$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/runner"
"$(REDOCLY)" bundle "$(API_DIR)/core/openapi.yml" --output "$(API_DIR)/core/openapi.bundle.yml"
"$(REDOCLY)" bundle "$(API_DIR)/ml/openapi.yml" --output "$(API_DIR)/ml/openapi.bundle.yml"
"$(REDOCLY)" bundle "$(API_DIR)/runner/openapi.yml" --output "$(API_DIR)/runner/openapi.bundle.yml"
.PHONY: lint
lint: bundle ## Lint both bundled contracts
lint: bundle ## Lint every bundled contract
"$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/core/openapi.bundle.yml"
"$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/ml/openapi.bundle.yml"
"$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/runner/openapi.bundle.yml"
.PHONY: check
check: lint ## Build and lint both contract bundles
check: lint ## Build and lint every contract bundle and run the contract tests
PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_merge_schemas.py'
PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_contract_copies.py'
PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_assessment_contract.py'
PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_match_contract.py'
PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_runner_contract.py'
.PHONY: check-compat
check-compat: bundle ## Compare the public contract with API_BASE_REF
+13 -1
View File
@@ -6,9 +6,10 @@ Shared OpenAPI contracts for Go, the frontend, and ML. Contract changes come fir
- `core/` defines the main backend's public API.
- `ml/` defines the ML service's internal HTTP API.
- `runner/` defines the internal HTTP API of the own code runner.
- `testdata/` contains a specification for checking tool compatibility with OpenAPI 3.2.0.
Routes live in `routes/` and schemas in `components/`. The `openapi.bundle.yml` files are built automatically. Generator configuration lives in `backend/codegen/`, `frontend/codegen/`, and `ml/codegen/`.
Routes live in `routes/` and schemas in `components/`. The `openapi.bundle.yml` files are built automatically. Generator configuration lives in `backend/codegen/`, `frontend/codegen/`, and `ml/codegen/`; the code runner server code is generated from `runner/codegen/`.
From the repository root, `make -C api check` checks contracts and `make generate` updates all generated code.
@@ -100,6 +101,17 @@ Timestamps use the `Timestamp` schema: `string`, `format: date-time`, UTC with t
The ML service answers its errors with the same `Problem` schema. Its `ProblemCode` enum keeps the public identity codes so both contracts share one shape, but the service never returns them. FastAPI request validation answers 400 `validation_failed`. An HTTP exception raised inside the service maps by status: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, and 501 to their codes, 422 to 400 `validation_failed`, any other 4xx to 400 `validation_failed`, and any other 5xx to 500 `internal`. An unhandled exception answers 500 `internal` inside the application, so Starlette does not re-raise it to uvicorn; only its type is logged. The service also routes the uvicorn loggers through its JSON log format, which keeps only the exception type of a record and never its text or traceback.
### Code runner contract
`runner/openapi.yml` describes the internal API of the code runner, which only the Go backend calls. ogen generates the Go client from `backend/codegen/ogen-code-runner.yml` into `backend/internal/adapter/secondary/code_runner/api/`; no use case calls it yet.
- Transport and sign-in. The runner listens on a private interface of its host over HTTPS (TLS 1.3). Every operation except `/healthz` and `/readyz` requires `Authorization: Bearer <token>`; the token is a shared random secret of at least 32 characters from the deployment secret store. A wrong or missing token answers 401 `unauthenticated`. Plain HTTP is allowed only by an explicit switch of the local dev Compose file.
- 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.
- 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
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. The session boundary authenticates every operation protected by the contract; its principal comes from a verified account and an active PostgreSQL session. Except for identity and the consent operations below, protected business operations currently pass the security boundary and answer 501 `not_implemented` after request validation. Frontend registration and confirmation screens remain placeholders.
+13 -1
View File
@@ -6,9 +6,10 @@
- `core/` - публичный API основного backend.
- `ml/` - внутренний HTTP API ML-сервиса.
- `runner/` - внутренний HTTP API собственного исполнителя кода.
- `testdata/` - спецификация для проверки совместимости инструментов с OpenAPI 3.2.0.
Маршруты лежат в `routes/`, схемы - в `components/`. Файлы `openapi.bundle.yml` собираются автоматически. Конфигурации генераторов находятся в `backend/codegen/`, `frontend/codegen/` и `ml/codegen/`.
Маршруты лежат в `routes/`, схемы - в `components/`. Файлы `openapi.bundle.yml` собираются автоматически. Конфигурации генераторов находятся в `backend/codegen/`, `frontend/codegen/` и `ml/codegen/`; серверный код исполнителя генерируется по `runner/codegen/`.
Из корня: `make -C api check` проверяет контракты, `make generate` обновляет весь сгенерированный код.
@@ -100,6 +101,17 @@
ML-сервис отвечает на ошибки той же схемой `Problem`. Его перечисление `ProblemCode` сохраняет публичные коды identity, чтобы оба контракта имели одну форму, но сервис их никогда не возвращает. Валидация запроса FastAPI дает 400 `validation_failed`. HTTP-исключение внутри сервиса преобразуется по статусу: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429 и 501 - в свои коды, 422 - в 400 `validation_failed`, любой другой 4xx - в 400 `validation_failed`, любой другой 5xx - в 500 `internal`. Необработанное исключение дает 500 `internal` внутри приложения, поэтому Starlette не пробрасывает его в uvicorn; в лог попадает только тип. Сервис также направляет логгеры uvicorn через свой JSON-формат, который сохраняет только тип исключения записи, но не текст и не traceback.
### Контракт исполнителя кода
`runner/openapi.yml` описывает внутренний API исполнителя кода, который вызывает только Go backend. Go-клиент генерируется ogen по `backend/codegen/ogen-code-runner.yml` в `backend/internal/adapter/secondary/code_runner/api/`; его пока не вызывает ни один usecase.
- Транспорт и вход. Исполнитель слушает частный интерфейс своего хоста по HTTPS (TLS 1.3). Все операции, кроме `/healthz` и `/readyz`, требуют `Authorization: Bearer <token>`; токен - общий случайный секрет не короче 32 символов из хранилища секретов развертывания. Неверный или отсутствующий токен дает 401 `unauthenticated`. Простой HTTP разрешен только явным переключателем локального dev Compose.
- Данные. `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` и необязательными параметрами, например допуском для чисел.
- Ошибки используют форму `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
Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session boundary аутентифицирует все операции, защищенные контрактом; principal создается только из действующей PostgreSQL-сессии подтвержденного аккаунта. Помимо identity и перечисленных ниже операций согласий, защищенные бизнес-операции пока проходят security boundary и отвечают 501 `not_implemented` после проверки запроса. Экраны регистрации и подтверждения во frontend остаются заглушками.
+57
View File
@@ -0,0 +1,57 @@
Problem:
description: >-
Any error response. The body is a Problem whose `status` equals the HTTP
status and whose `code` is one of ProblemCode.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
validation_failed:
summary: Request fields do not match the contract
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
errors:
- in: body
pointer: /groups/1/id
code: invalid
message: The value does not match the contract.
idempotency_key_reused:
summary: The run ID was used with a different payload
value:
type: urn:lincodex:problem:idempotency_key_reused
title: Run ID reused with a different payload
status: 422
code: idempotency_key_reused
detail: A run with this ID exists with a different payload.
RunnerBusy:
description: >-
Every sandbox slot is busy or the runner is draining; code runner_busy.
Nothing was stored. Retry with the same run ID after Retry-After.
headers:
Retry-After:
description: Number of seconds to wait before retrying the request.
required: true
schema:
type: integer
format: int32
minimum: 0
maximum: 3600
example: 2
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
runner_busy:
summary: No free sandbox slot
value:
type: urn:lincodex:problem:runner_busy
title: Runner busy
status: 503
code: runner_busy
detail: Every sandbox slot is busy. Retry later with the same run ID.
+452
View File
@@ -0,0 +1,452 @@
RunnerHealthResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ok
RunnerReadinessResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ready
- not_ready
Problem:
type: object
description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the runner copy of the public api/core Problem schema; keep both copies identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.
title:
type: string
minLength: 1
maxLength: 200
description: Short, fixed English summary of the problem type. It does not change between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: '#/ProblemCode'
detail:
type: string
maxLength: 1000
description: Safe English explanation of this occurrence. It never contains internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: ^[A-Za-z0-9._-]+$
description: Request identifier of the call when the caller propagated one; it is not a secret.
errors:
type: array
maxItems: 100
description: Field-level reasons for validation_failed. Other codes omit it.
items:
$ref: '#/ProblemFieldError'
ProblemCode:
type: string
description: 'Stable error code of the runner API. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.
- validation_failed (400): parameters or body do not match the contract or a semantic rule of SubmitRun; `errors` points at the fields.
- unauthenticated (401): the bearer token is missing or wrong.
- not_found (404): the route or the run does not exist.
- method_not_allowed (405): the route does not support the method.
- payload_too_large (413): the request body exceeds the limit.
- unsupported_media_type (415): the request Content-Type is not accepted.
- idempotency_key_reused (422): the run ID was already used with a different payload.
- internal (500): unexpected server error.
- runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After.
The Problem shape is the api/core shape; only this enum is specific to the runner.'
enum:
- validation_failed
- unauthenticated
- not_found
- method_not_allowed
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- internal
- runner_busy
ProblemFieldError:
type: object
description: One reason why a request field or parameter is invalid.
additionalProperties: false
required:
- in
- pointer
- code
- message
properties:
in:
$ref: '#/ProblemFieldLocation'
pointer:
type: string
maxLength: 1024
pattern: ^(/([^~/]|~[01])*)*$
description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/limits/time_limit_ms`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/run_id`.
code:
type: string
minLength: 1
maxLength: 64
pattern: ^[a-z][a-z0-9_]*$
description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.
message:
type: string
minLength: 1
maxLength: 500
description: Fixed English message that never echoes the submitted value.
ProblemFieldLocation:
type: string
description: Part of the request that contains the invalid field.
enum:
- body
- query
- path
- header
- cookie
RunRequest:
type: object
description: One source and its test groups. The request has no field for a candidate, account, attempt, task, or company; the backend maps a run ID to its own records.
additionalProperties: false
required:
- language
- source
- limits
- groups
properties:
language:
$ref: '#/RunLanguage'
source:
type: string
minLength: 1
maxLength: 65536
description: Complete program text in UTF-8. The runner writes it to a read-only file inside the sandbox and never logs it.
limits:
$ref: '#/RunLimits'
groups:
type: array
minItems: 1
maxItems: 4
description: Test groups in evaluation order, for example one public group and three hidden groups. Group IDs are unique in a run.
items:
$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.
enum:
- python3
RunLimits:
type: object
description: Limits applied to every test of the run.
additionalProperties: false
required:
- time_limit_ms
- memory_limit_mb
- output_limit_kb
properties:
time_limit_ms:
type: integer
format: int32
minimum: 100
maximum: 10000
description: CPU time per test, including interpreter startup, summed over every process of the test. The wall-clock limit is twice this value plus a fixed startup allowance.
memory_limit_mb:
type: integer
format: int32
minimum: 32
maximum: 512
description: Memory of the test's processes in MiB, enforced by a cgroup v2 memory limit without swap. The limit also leaves a small fixed allowance for the sandbox supervisor process.
output_limit_kb:
type: integer
format: int32
minimum: 1
maximum: 1024
description: Standard output per test in KiB. The test is stopped as soon as it writes more.
TestGroup:
type: object
additionalProperties: false
required:
- id
- visibility
- checker
- tests
properties:
id:
$ref: '#/TestKey'
visibility:
$ref: '#/TestVisibility'
checker:
$ref: '#/Checker'
tests:
type: array
minItems: 1
maxItems: 50
description: Tests in evaluation order. Test IDs are unique in a group. A group stops at its first failed test.
items:
$ref: '#/TestCase'
TestKey:
type: string
minLength: 1
maxLength: 32
pattern: ^[a-z0-9][a-z0-9_-]{0,31}$
description: Opaque label chosen by the backend, for example `public` or `hidden-1`. It is not a database identifier.
TestVisibility:
type: string
description: '`public` tests may be shown to the person who wrote the source; their results may carry a diagnostic excerpt. `hidden` results never carry program output or diagnostics.'
enum:
- public
- 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.
additionalProperties: false
required:
- kind
properties:
kind:
$ref: '#/CheckerKind'
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.'
enum:
- exact
- tokens
TestCase:
type: object
additionalProperties: false
required:
- id
- input
- expected_output
properties:
id:
$ref: '#/TestKey'
input:
type: string
maxLength: 262144
description: UTF-8 text written to the standard input of the program.
expected_output:
type: string
maxLength: 262144
description: UTF-8 text the checker compares with the standard output.
RunState:
type: string
description: '`running` until every group was evaluated or the run failed; `finished` when `result` is final.'
enum:
- running
- finished
RunStatus:
type: object
additionalProperties: false
required:
- run_id
- state
properties:
run_id:
type: string
format: uuid
state:
$ref: '#/RunState'
result:
$ref: '#/RunResult'
RunOutcome:
type: string
description: 'Outcome of a test, a group, a compile step, or a whole run.
- accepted: the program exited with status 0 within every limit and the checker accepted the output.
- wrong_answer: the program exited with status 0 within every limit, but the checker rejected the output.
- compile_error: the source was rejected before any test ran (for Python, a syntax error).
- time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program.
- memory_limit_exceeded: the cgroup memory limit stopped the program.
- output_limit_exceeded: the program wrote more standard output than the limit.
- runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the process limit.
- infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about the program, and the caller may retry with a new run ID.
A run''s outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome of the first failed test in request order, otherwise accepted. A group''s outcome is the outcome of its first failed test, otherwise accepted.'
enum:
- accepted
- wrong_answer
- compile_error
- time_limit_exceeded
- memory_limit_exceeded
- output_limit_exceeded
- runtime_error
- infrastructure_failure
TerminationLimit:
type: string
description: 'The limit that stopped a test: CPU time, wall-clock time, memory, standard output, or the number of processes and threads.'
enum:
- cpu_time
- wall_time
- memory
- output
- processes
RunResult:
type: object
additionalProperties: false
required:
- outcome
- groups
- duration_ms
properties:
outcome:
$ref: '#/RunOutcome'
compile:
$ref: '#/CompileResult'
groups:
type: array
maxItems: 4
description: One result per requested group in request order. After compile_error or infrastructure_failure every group has that outcome and no tests.
items:
$ref: '#/GroupResult'
duration_ms:
type: integer
format: int64
minimum: 0
description: Wall-clock time of the whole run in the runner.
CompileResult:
type: object
additionalProperties: false
required:
- outcome
properties:
outcome:
$ref: '#/RunOutcome'
diagnostic:
type: string
maxLength: 4096
description: Compiler or syntax checker message for compile_error, truncated to the limit. It can quote the source, never test data.
GroupResult:
type: object
additionalProperties: false
required:
- id
- visibility
- outcome
- passed_tests
- total_tests
- tests
properties:
id:
$ref: '#/TestKey'
visibility:
$ref: '#/TestVisibility'
outcome:
$ref: '#/RunOutcome'
passed_tests:
type: integer
format: int32
minimum: 0
maximum: 50
total_tests:
type: integer
format: int32
minimum: 0
maximum: 50
max_time_ms:
type: integer
format: int64
minimum: 0
description: Largest CPU time of an evaluated test of the group.
max_memory_kb:
type: integer
format: int64
minimum: 0
description: Largest peak memory of an evaluated test of the group.
tests:
type: array
maxItems: 50
description: Results of the evaluated tests in order. Tests after the first failed one are not run and not listed.
items:
$ref: '#/TestResult'
TestResult:
type: object
additionalProperties: false
required:
- id
- outcome
- time_ms
- wall_time_ms
- memory_kb
properties:
id:
$ref: '#/TestKey'
outcome:
$ref: '#/RunOutcome'
time_ms:
type: integer
format: int64
minimum: 0
description: CPU time of every process of the test.
wall_time_ms:
type: integer
format: int64
minimum: 0
memory_kb:
type: integer
format: int64
minimum: 0
description: 'Peak memory of the test in KiB: the cgroup high-water mark of every process of the test, including the sandbox supervisor process and file cache charged to the test.'
exit_code:
type: integer
format: int32
description: Exit status when the program exited normally.
signal:
type: integer
format: int32
minimum: 1
maximum: 64
description: Signal number when the program was killed by a signal.
limit:
$ref: '#/TerminationLimit'
diagnostic:
type: string
maxLength: 2048
description: Truncated standard error of a failed public test. Hidden tests never carry it.
@@ -0,0 +1,22 @@
schemas:
RunnerHealthResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ok
RunnerReadinessResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ready
- not_ready
@@ -0,0 +1,138 @@
schemas:
Problem:
type: object
description: >-
Problem details (RFC 9457) returned with the application/problem+json
media type for every error response. This is the runner copy of the
public api/core Problem schema; keep both copies identical except for
descriptions and the ProblemCode enum. `code` is the stable,
machine-readable reason; clients branch on it rather than on `title`,
`detail`, or the HTTP status alone. The body never contains internal
error text, stack traces, SQL, file paths, credentials, contact data, or
echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: >-
URI that identifies the problem type. It has the form
`urn:lincodex:problem:<code>` and is an identifier, not a link to
dereference.
title:
type: string
minLength: 1
maxLength: 200
description: >-
Short, fixed English summary of the problem type. It does not change
between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: "#/schemas/ProblemCode"
detail:
type: string
maxLength: 1000
description: >-
Safe English explanation of this occurrence. It never contains
internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: "^[A-Za-z0-9._-]+$"
description: >-
Request identifier of the call when the caller propagated one; it is
not a secret.
errors:
type: array
maxItems: 100
description: >-
Field-level reasons for validation_failed. Other codes omit it.
items:
$ref: "#/schemas/ProblemFieldError"
ProblemCode:
type: string
description: |-
Stable error code of the runner API. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.
- validation_failed (400): parameters or body do not match the contract or a semantic rule of SubmitRun; `errors` points at the fields.
- unauthenticated (401): the bearer token is missing or wrong.
- not_found (404): the route or the run does not exist.
- method_not_allowed (405): the route does not support the method.
- payload_too_large (413): the request body exceeds the limit.
- unsupported_media_type (415): the request Content-Type is not accepted.
- idempotency_key_reused (422): the run ID was already used with a different payload.
- internal (500): unexpected server error.
- runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After.
The Problem shape is the api/core shape; only this enum is specific to the runner.
enum:
- validation_failed
- unauthenticated
- not_found
- method_not_allowed
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- internal
- runner_busy
ProblemFieldError:
type: object
description: One reason why a request field or parameter is invalid.
additionalProperties: false
required:
- in
- pointer
- code
- message
properties:
in:
$ref: "#/schemas/ProblemFieldLocation"
pointer:
type: string
maxLength: 1024
pattern: "^(/([^~/]|~[01])*)*$"
description: >-
JSON Pointer (RFC 6901). For `body` it points into the request body
document, for example `/limits/time_limit_ms`; an empty string means the whole
body. For a parameter it is `/` followed by the parameter name, for
example `/run_id`.
code:
type: string
minLength: 1
maxLength: 64
pattern: "^[a-z][a-z0-9_]*$"
description: >-
Stable field reason. Current values are `required` (missing value)
and `invalid` (malformed value or a value outside the schema).
Clients must tolerate new values.
message:
type: string
minLength: 1
maxLength: 500
description: Fixed English message that never echoes the submitted value.
ProblemFieldLocation:
type: string
description: Part of the request that contains the invalid field.
enum:
- body
- query
- path
- header
- cookie
@@ -0,0 +1,347 @@
schemas:
RunRequest:
type: object
description: >-
One source and its test groups. The request has no field for a
candidate, account, attempt, task, or company; the backend maps a run ID
to its own records.
additionalProperties: false
required:
- language
- source
- limits
- groups
properties:
language:
$ref: "#/schemas/RunLanguage"
source:
type: string
minLength: 1
maxLength: 65536
description: >-
Complete program text in UTF-8. The runner writes it to a read-only
file inside the sandbox and never logs it.
limits:
$ref: "#/schemas/RunLimits"
groups:
type: array
minItems: 1
maxItems: 4
description: >-
Test groups in evaluation order, for example one public group and
three hidden groups. Group IDs are unique in a run.
items:
$ref: "#/schemas/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.
enum:
- python3
RunLimits:
type: object
description: Limits applied to every test of the run.
additionalProperties: false
required:
- time_limit_ms
- memory_limit_mb
- output_limit_kb
properties:
time_limit_ms:
type: integer
format: int32
minimum: 100
maximum: 10000
description: >-
CPU time per test, including interpreter startup, summed over every
process of the test. The wall-clock limit is twice this value plus
a fixed startup allowance.
memory_limit_mb:
type: integer
format: int32
minimum: 32
maximum: 512
description: >-
Memory of the test's processes in MiB, enforced by a cgroup v2
memory limit without swap. The limit also leaves a small fixed
allowance for the sandbox supervisor process.
output_limit_kb:
type: integer
format: int32
minimum: 1
maximum: 1024
description: >-
Standard output per test in KiB. The test is stopped as soon as it
writes more.
TestGroup:
type: object
additionalProperties: false
required:
- id
- visibility
- checker
- tests
properties:
id:
$ref: "#/schemas/TestKey"
visibility:
$ref: "#/schemas/TestVisibility"
checker:
$ref: "#/schemas/Checker"
tests:
type: array
minItems: 1
maxItems: 50
description: >-
Tests in evaluation order. Test IDs are unique in a group. A group
stops at its first failed test.
items:
$ref: "#/schemas/TestCase"
TestKey:
type: string
minLength: 1
maxLength: 32
pattern: "^[a-z0-9][a-z0-9_-]{0,31}$"
description: >-
Opaque label chosen by the backend, for example `public` or `hidden-1`.
It is not a database identifier.
TestVisibility:
type: string
description: >-
`public` tests may be shown to the person who wrote the source; their
results may carry a diagnostic excerpt. `hidden` results never carry
program output or diagnostics.
enum:
- public
- 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.
additionalProperties: false
required:
- kind
properties:
kind:
$ref: "#/schemas/CheckerKind"
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.
enum:
- exact
- tokens
TestCase:
type: object
additionalProperties: false
required:
- id
- input
- expected_output
properties:
id:
$ref: "#/schemas/TestKey"
input:
type: string
maxLength: 262144
description: UTF-8 text written to the standard input of the program.
expected_output:
type: string
maxLength: 262144
description: UTF-8 text the checker compares with the standard output.
RunState:
type: string
description: >-
`running` until every group was evaluated or the run failed;
`finished` when `result` is final.
enum:
- running
- finished
RunStatus:
type: object
additionalProperties: false
required:
- run_id
- state
properties:
run_id:
type: string
format: uuid
state:
$ref: "#/schemas/RunState"
result:
$ref: "#/schemas/RunResult"
RunOutcome:
type: string
description: |-
Outcome of a test, a group, a compile step, or a whole run.
- accepted: the program exited with status 0 within every limit and the checker accepted the output.
- wrong_answer: the program exited with status 0 within every limit, but the checker rejected the output.
- compile_error: the source was rejected before any test ran (for Python, a syntax error).
- time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program.
- memory_limit_exceeded: the cgroup memory limit stopped the program.
- output_limit_exceeded: the program wrote more standard output than the limit.
- runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the process limit.
- infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about the program, and the caller may retry with a new run ID.
A run's outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome of the first failed test in request order, otherwise accepted. A group's outcome is the outcome of its first failed test, otherwise accepted.
enum:
- accepted
- wrong_answer
- compile_error
- time_limit_exceeded
- memory_limit_exceeded
- output_limit_exceeded
- runtime_error
- infrastructure_failure
TerminationLimit:
type: string
description: >-
The limit that stopped a test: CPU time, wall-clock time, memory,
standard output, or the number of processes and threads.
enum:
- cpu_time
- wall_time
- memory
- output
- processes
RunResult:
type: object
additionalProperties: false
required:
- outcome
- groups
- duration_ms
properties:
outcome:
$ref: "#/schemas/RunOutcome"
compile:
$ref: "#/schemas/CompileResult"
groups:
type: array
maxItems: 4
description: >-
One result per requested group in request order. After
compile_error or infrastructure_failure every group has that
outcome and no tests.
items:
$ref: "#/schemas/GroupResult"
duration_ms:
type: integer
format: int64
minimum: 0
description: Wall-clock time of the whole run in the runner.
CompileResult:
type: object
additionalProperties: false
required:
- outcome
properties:
outcome:
$ref: "#/schemas/RunOutcome"
diagnostic:
type: string
maxLength: 4096
description: >-
Compiler or syntax checker message for compile_error, truncated to
the limit. It can quote the source, never test data.
GroupResult:
type: object
additionalProperties: false
required:
- id
- visibility
- outcome
- passed_tests
- total_tests
- tests
properties:
id:
$ref: "#/schemas/TestKey"
visibility:
$ref: "#/schemas/TestVisibility"
outcome:
$ref: "#/schemas/RunOutcome"
passed_tests:
type: integer
format: int32
minimum: 0
maximum: 50
total_tests:
type: integer
format: int32
minimum: 0
maximum: 50
max_time_ms:
type: integer
format: int64
minimum: 0
description: Largest CPU time of an evaluated test of the group.
max_memory_kb:
type: integer
format: int64
minimum: 0
description: Largest peak memory of an evaluated test of the group.
tests:
type: array
maxItems: 50
description: >-
Results of the evaluated tests in order. Tests after the first
failed one are not run and not listed.
items:
$ref: "#/schemas/TestResult"
TestResult:
type: object
additionalProperties: false
required:
- id
- outcome
- time_ms
- wall_time_ms
- memory_kb
properties:
id:
$ref: "#/schemas/TestKey"
outcome:
$ref: "#/schemas/RunOutcome"
time_ms:
type: integer
format: int64
minimum: 0
description: CPU time of every process of the test.
wall_time_ms:
type: integer
format: int64
minimum: 0
memory_kb:
type: integer
format: int64
minimum: 0
description: >-
Peak memory of the test in KiB: the cgroup high-water mark of every
process of the test, including the sandbox supervisor process and
file cache charged to the test.
exit_code:
type: integer
format: int32
description: Exit status when the program exited normally.
signal:
type: integer
format: int32
minimum: 1
maximum: 64
description: Signal number when the program was killed by a signal.
limit:
$ref: "#/schemas/TerminationLimit"
diagnostic:
type: string
maxLength: 2048
description: >-
Truncated standard error of a failed public test. Hidden tests
never carry it.
+633
View File
@@ -0,0 +1,633 @@
openapi: 3.2.0
info:
title: Lincodex Code Runner API
version: 0.1.0
description: |-
Internal API of the own code runner. Only the Go backend calls it; it is
never exposed to browsers or to the public network.
Transport and authentication: the runner listens on a private network
interface of its dedicated host and serves HTTPS (TLS 1.3). Every
operation except the health routes requires `Authorization: Bearer
<token>`; the token is a shared random secret of at least 32 characters
that comes from the deployment secret store, never from this repository.
A missing or wrong token answers 401 `unauthenticated`. Plain HTTP exists
only behind an explicit development switch of the local Compose file.
Data minimization: a run carries only the language, the source code, the
limits, and the test groups. It has no candidate, account, attempt, or
task identifiers, names, or contacts. The run ID is a random UUID chosen
by the backend for idempotency; the runner keeps it only in memory.
Runs are asynchronous. SubmitRun accepts a run when a sandbox slot is free
and answers immediately; the caller polls GetRun until `state` is
`finished`. The runner does not queue runs: when every slot is busy it
answers 503 `runner_busy`, and the backend keeps the queue.
servers:
- url: /
security:
- bearerAuth: []
paths:
/healthz:
get:
operationId: GetRunnerHealthz
summary: Check whether the runner process is responding.
security: []
tags:
- health
responses:
'200':
description: The runner process is responding.
content:
application/json:
schema:
$ref: '#/components/schemas/RunnerHealthResponse'
default:
$ref: '#/components/responses/Problem'
/readyz:
get:
operationId: GetRunnerReadyz
summary: Check whether the sandbox is prepared to accept runs.
description: Ready means that the cgroup hierarchy, the work directory, and the sandbox binary were prepared at startup and the process is not draining. A busy runner is still ready; busy is reported by SubmitRun.
security: []
tags:
- health
responses:
'200':
description: The sandbox is prepared.
content:
application/json:
schema:
$ref: '#/components/schemas/RunnerReadinessResponse'
'503':
description: The sandbox is not prepared or the process is draining.
content:
application/json:
schema:
$ref: '#/components/schemas/RunnerReadinessResponse'
default:
$ref: '#/components/responses/Problem'
/v1/runs/{run_id}:
parameters:
- name: run_id
in: path
required: true
description: Random UUID chosen by the backend for one logical run. It is the idempotency key of SubmitRun and must not encode a candidate, attempt, or task identifier.
schema:
type: string
format: uuid
put:
operationId: SubmitRun
summary: Start a sandboxed run of one source against its test groups.
description: |-
Idempotent by `run_id`:
- a new ID with a free sandbox slot starts the run and answers 202 with `state: running`;
- the same ID with the same payload answers 200 with the current state of that run, including the finished result, without running it again;
- the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing;
- a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_busy` with Retry-After; nothing is stored, so the caller retries with the same ID.
Payloads are compared by a SHA-256 fingerprint of the decoded request.
The runner keeps runs only in 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.
tags:
- runs
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/RunRequest'
responses:
'200':
description: A run with this ID and the same payload already exists.
content:
application/json:
schema:
$ref: '#/components/schemas/RunStatus'
'202':
description: The run was accepted and started.
content:
application/json:
schema:
$ref: '#/components/schemas/RunStatus'
'503':
$ref: '#/components/responses/RunnerBusy'
default:
$ref: '#/components/responses/Problem'
get:
operationId: GetRun
summary: Read the state and, when finished, the per-group result of a run.
description: Answers 404 `not_found` for an ID the runner does not hold, including a run forgotten after its retention time or lost in a restart.
tags:
- runs
responses:
'200':
description: The current state of the run.
content:
application/json:
schema:
$ref: '#/components/schemas/RunStatus'
default:
$ref: '#/components/responses/Problem'
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
description: 'Shared random service token sent as `Authorization: Bearer <token>` over TLS. The runner compares it in constant time and never logs it. Rotation replaces the secret on both sides; there are no per-user tokens.'
responses:
Problem:
description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
validation_failed:
summary: Request fields do not match the contract
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
errors:
- in: body
pointer: /groups/1/id
code: invalid
message: The value does not match the contract.
idempotency_key_reused:
summary: The run ID was used with a different payload
value:
type: urn:lincodex:problem:idempotency_key_reused
title: Run ID reused with a different payload
status: 422
code: idempotency_key_reused
detail: A run with this ID exists with a different payload.
RunnerBusy:
description: Every sandbox slot is busy or the runner is draining; code runner_busy. Nothing was stored. Retry with the same run ID after Retry-After.
headers:
Retry-After:
description: Number of seconds to wait before retrying the request.
required: true
schema:
type: integer
format: int32
minimum: 0
maximum: 3600
example: 2
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
runner_busy:
summary: No free sandbox slot
value:
type: urn:lincodex:problem:runner_busy
title: Runner busy
status: 503
code: runner_busy
detail: Every sandbox slot is busy. Retry later with the same run ID.
schemas:
ProblemCode:
type: string
description: |-
Stable error code of the runner API. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.
- validation_failed (400): parameters or body do not match the contract or a semantic rule of SubmitRun; `errors` points at the fields.
- unauthenticated (401): the bearer token is missing or wrong.
- not_found (404): the route or the run does not exist.
- method_not_allowed (405): the route does not support the method.
- payload_too_large (413): the request body exceeds the limit.
- unsupported_media_type (415): the request Content-Type is not accepted.
- idempotency_key_reused (422): the run ID was already used with a different payload.
- internal (500): unexpected server error.
- runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After.
The Problem shape is the api/core shape; only this enum is specific to the runner.
enum:
- validation_failed
- unauthenticated
- not_found
- method_not_allowed
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- internal
- runner_busy
ProblemFieldLocation:
type: string
description: Part of the request that contains the invalid field.
enum:
- body
- query
- path
- header
- cookie
ProblemFieldError:
type: object
description: One reason why a request field or parameter is invalid.
additionalProperties: false
required:
- in
- pointer
- code
- message
properties:
in:
$ref: '#/components/schemas/ProblemFieldLocation'
pointer:
type: string
maxLength: 1024
pattern: ^(/([^~/]|~[01])*)*$
description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/limits/time_limit_ms`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/run_id`.
code:
type: string
minLength: 1
maxLength: 64
pattern: ^[a-z][a-z0-9_]*$
description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.
message:
type: string
minLength: 1
maxLength: 500
description: Fixed English message that never echoes the submitted value.
Problem:
type: object
description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the runner copy of the public api/core Problem schema; keep both copies identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.
title:
type: string
minLength: 1
maxLength: 200
description: Short, fixed English summary of the problem type. It does not change between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: '#/components/schemas/ProblemCode'
detail:
type: string
maxLength: 1000
description: Safe English explanation of this occurrence. It never contains internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: ^[A-Za-z0-9._-]+$
description: Request identifier of the call when the caller propagated one; it is not a secret.
errors:
type: array
maxItems: 100
description: Field-level reasons for validation_failed. Other codes omit it.
items:
$ref: '#/components/schemas/ProblemFieldError'
RunnerHealthResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ok
RunnerReadinessResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ready
- not_ready
RunState:
type: string
description: '`running` until every group was evaluated or the run failed; `finished` when `result` is final.'
enum:
- running
- finished
RunOutcome:
type: string
description: |-
Outcome of a test, a group, a compile step, or a whole run.
- accepted: the program exited with status 0 within every limit and the checker accepted the output.
- wrong_answer: the program exited with status 0 within every limit, but the checker rejected the output.
- compile_error: the source was rejected before any test ran (for Python, a syntax error).
- time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program.
- memory_limit_exceeded: the cgroup memory limit stopped the program.
- output_limit_exceeded: the program wrote more standard output than the limit.
- runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the process limit.
- infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about the program, and the caller may retry with a new run ID.
A run's outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome of the first failed test in request order, otherwise accepted. A group's outcome is the outcome of its first failed test, otherwise accepted.
enum:
- accepted
- wrong_answer
- compile_error
- time_limit_exceeded
- memory_limit_exceeded
- output_limit_exceeded
- runtime_error
- infrastructure_failure
CompileResult:
type: object
additionalProperties: false
required:
- outcome
properties:
outcome:
$ref: '#/components/schemas/RunOutcome'
diagnostic:
type: string
maxLength: 4096
description: Compiler or syntax checker message for compile_error, truncated to the limit. It can quote the source, never test data.
TestKey:
type: string
minLength: 1
maxLength: 32
pattern: ^[a-z0-9][a-z0-9_-]{0,31}$
description: Opaque label chosen by the backend, for example `public` or `hidden-1`. It is not a database identifier.
TestVisibility:
type: string
description: '`public` tests may be shown to the person who wrote the source; their results may carry a diagnostic excerpt. `hidden` results never carry program output or diagnostics.'
enum:
- public
- hidden
TerminationLimit:
type: string
description: 'The limit that stopped a test: CPU time, wall-clock time, memory, standard output, or the number of processes and threads.'
enum:
- cpu_time
- wall_time
- memory
- output
- processes
TestResult:
type: object
additionalProperties: false
required:
- id
- outcome
- time_ms
- wall_time_ms
- memory_kb
properties:
id:
$ref: '#/components/schemas/TestKey'
outcome:
$ref: '#/components/schemas/RunOutcome'
time_ms:
type: integer
format: int64
minimum: 0
description: CPU time of every process of the test.
wall_time_ms:
type: integer
format: int64
minimum: 0
memory_kb:
type: integer
format: int64
minimum: 0
description: 'Peak memory of the test in KiB: the cgroup high-water mark of every process of the test, including the sandbox supervisor process and file cache charged to the test.'
exit_code:
type: integer
format: int32
description: Exit status when the program exited normally.
signal:
type: integer
format: int32
minimum: 1
maximum: 64
description: Signal number when the program was killed by a signal.
limit:
$ref: '#/components/schemas/TerminationLimit'
diagnostic:
type: string
maxLength: 2048
description: Truncated standard error of a failed public test. Hidden tests never carry it.
GroupResult:
type: object
additionalProperties: false
required:
- id
- visibility
- outcome
- passed_tests
- total_tests
- tests
properties:
id:
$ref: '#/components/schemas/TestKey'
visibility:
$ref: '#/components/schemas/TestVisibility'
outcome:
$ref: '#/components/schemas/RunOutcome'
passed_tests:
type: integer
format: int32
minimum: 0
maximum: 50
total_tests:
type: integer
format: int32
minimum: 0
maximum: 50
max_time_ms:
type: integer
format: int64
minimum: 0
description: Largest CPU time of an evaluated test of the group.
max_memory_kb:
type: integer
format: int64
minimum: 0
description: Largest peak memory of an evaluated test of the group.
tests:
type: array
maxItems: 50
description: Results of the evaluated tests in order. Tests after the first failed one are not run and not listed.
items:
$ref: '#/components/schemas/TestResult'
RunResult:
type: object
additionalProperties: false
required:
- outcome
- groups
- duration_ms
properties:
outcome:
$ref: '#/components/schemas/RunOutcome'
compile:
$ref: '#/components/schemas/CompileResult'
groups:
type: array
maxItems: 4
description: One result per requested group in request order. After compile_error or infrastructure_failure every group has that outcome and no tests.
items:
$ref: '#/components/schemas/GroupResult'
duration_ms:
type: integer
format: int64
minimum: 0
description: Wall-clock time of the whole run in the runner.
RunStatus:
type: object
additionalProperties: false
required:
- run_id
- state
properties:
run_id:
type: string
format: uuid
state:
$ref: '#/components/schemas/RunState'
result:
$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.
enum:
- python3
RunLimits:
type: object
description: Limits applied to every test of the run.
additionalProperties: false
required:
- time_limit_ms
- memory_limit_mb
- output_limit_kb
properties:
time_limit_ms:
type: integer
format: int32
minimum: 100
maximum: 10000
description: CPU time per test, including interpreter startup, summed over every process of the test. The wall-clock limit is twice this value plus a fixed startup allowance.
memory_limit_mb:
type: integer
format: int32
minimum: 32
maximum: 512
description: Memory of the test's processes in MiB, enforced by a cgroup v2 memory limit without swap. The limit also leaves a small fixed allowance for the sandbox supervisor process.
output_limit_kb:
type: integer
format: int32
minimum: 1
maximum: 1024
description: Standard output per test in KiB. The test is stopped as soon as it writes more.
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.
enum:
- exact
- tokens
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.
additionalProperties: false
required:
- kind
properties:
kind:
$ref: '#/components/schemas/CheckerKind'
TestCase:
type: object
additionalProperties: false
required:
- id
- input
- expected_output
properties:
id:
$ref: '#/components/schemas/TestKey'
input:
type: string
maxLength: 262144
description: UTF-8 text written to the standard input of the program.
expected_output:
type: string
maxLength: 262144
description: UTF-8 text the checker compares with the standard output.
TestGroup:
type: object
additionalProperties: false
required:
- id
- visibility
- checker
- tests
properties:
id:
$ref: '#/components/schemas/TestKey'
visibility:
$ref: '#/components/schemas/TestVisibility'
checker:
$ref: '#/components/schemas/Checker'
tests:
type: array
minItems: 1
maxItems: 50
description: Tests in evaluation order. Test IDs are unique in a group. A group stops at its first failed test.
items:
$ref: '#/components/schemas/TestCase'
RunRequest:
type: object
description: One source and its test groups. The request has no field for a candidate, account, attempt, task, or company; the backend maps a run ID to its own records.
additionalProperties: false
required:
- language
- source
- limits
- groups
properties:
language:
$ref: '#/components/schemas/RunLanguage'
source:
type: string
minLength: 1
maxLength: 65536
description: Complete program text in UTF-8. The runner writes it to a read-only file inside the sandbox and never logs it.
limits:
$ref: '#/components/schemas/RunLimits'
groups:
type: array
minItems: 1
maxItems: 4
description: Test groups in evaluation order, for example one public group and three hidden groups. Group IDs are unique in a run.
items:
$ref: '#/components/schemas/TestGroup'
+49
View File
@@ -0,0 +1,49 @@
openapi: 3.2.0
info:
title: Lincodex Code Runner API
version: 0.1.0
description: |-
Internal API of the own code runner. Only the Go backend calls it; it is
never exposed to browsers or to the public network.
Transport and authentication: the runner listens on a private network
interface of its dedicated host and serves HTTPS (TLS 1.3). Every
operation except the health routes requires `Authorization: Bearer
<token>`; the token is a shared random secret of at least 32 characters
that comes from the deployment secret store, never from this repository.
A missing or wrong token answers 401 `unauthenticated`. Plain HTTP exists
only behind an explicit development switch of the local Compose file.
Data minimization: a run carries only the language, the source code, the
limits, and the test groups. It has no candidate, account, attempt, or
task identifiers, names, or contacts. The run ID is a random UUID chosen
by the backend for idempotency; the runner keeps it only in memory.
Runs are asynchronous. SubmitRun accepts a run when a sandbox slot is free
and answers immediately; the caller polls GetRun until `state` is
`finished`. The runner does not queue runs: when every slot is busy it
answers 503 `runner_busy`, and the backend keeps the queue.
servers:
- url: /
security:
- bearerAuth: []
paths:
/healthz:
$ref: ./routes/healthz.yml
/readyz:
$ref: ./routes/readyz.yml
/v1/runs/{run_id}:
$ref: ./routes/runs.yml
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
description: >-
Shared random service token sent as `Authorization: Bearer <token>`
over TLS. The runner compares it in constant time and never logs it.
Rotation replaces the secret on both sides; there are no per-user
tokens.
responses:
Problem:
$ref: ./components/responses.yml#/Problem
+15
View File
@@ -0,0 +1,15 @@
get:
operationId: GetRunnerHealthz
summary: Check whether the runner process is responding.
security: []
tags:
- health
responses:
"200":
description: The runner process is responding.
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunnerHealthResponse
default:
$ref: ../components/responses.yml#/Problem
+25
View File
@@ -0,0 +1,25 @@
get:
operationId: GetRunnerReadyz
summary: Check whether the sandbox is prepared to accept runs.
description: >-
Ready means that the cgroup hierarchy, the work directory, and the sandbox
binary were prepared at startup and the process is not draining. A busy
runner is still ready; busy is reported by SubmitRun.
security: []
tags:
- health
responses:
"200":
description: The sandbox is prepared.
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunnerReadinessResponse
"503":
description: The sandbox is not prepared or the process is draining.
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunnerReadinessResponse
default:
$ref: ../components/responses.yml#/Problem
+72
View File
@@ -0,0 +1,72 @@
parameters:
- name: run_id
in: path
required: true
description: >-
Random UUID chosen by the backend for one logical run. It is the
idempotency key of SubmitRun and must not encode a candidate, attempt,
or task identifier.
schema:
type: string
format: uuid
put:
operationId: SubmitRun
summary: Start a sandboxed run of one source against its test groups.
description: |-
Idempotent by `run_id`:
- a new ID with a free sandbox slot starts the run and answers 202 with `state: running`;
- the same ID with the same payload answers 200 with the current state of that run, including the finished result, without running it again;
- the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing;
- a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_busy` with Retry-After; nothing is stored, so the caller retries with the same ID.
Payloads are compared by a SHA-256 fingerprint of the decoded request.
The runner keeps runs only in 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.
tags:
- runs
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunRequest
responses:
"200":
description: A run with this ID and the same payload already exists.
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunStatus
"202":
description: The run was accepted and started.
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunStatus
"503":
$ref: ../components/responses.yml#/RunnerBusy
default:
$ref: ../components/responses.yml#/Problem
get:
operationId: GetRun
summary: Read the state and, when finished, the per-group result of a run.
description: >-
Answers 404 `not_found` for an ID the runner does not hold, including a
run forgotten after its retention time or lost in a restart.
tags:
- runs
responses:
"200":
description: The current state of the run.
content:
application/json:
schema:
$ref: ../components/schemas.yml#/RunStatus
default:
$ref: ../components/responses.yml#/Problem