feat(runner): compile Go and check answers per test group

This commit is contained in:
shira committed 2026-10-11 08:59:29 +03:00
1 parent e95c681165
commit afee564bf4
61 files changed
+2592 -143

No files matched your search

+6 -2
View File
@@ -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
+3 -2
View File
@@ -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 |
+4 -2
View File
@@ -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.
+6 -2
View File
@@ -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/`.
## Подбор и объяснение
+3 -2
View File
@@ -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 сверх лимита задания |
+4 -2
View File
@@ -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.