feat(practice): add the code runner port and its TLS client

This commit is contained in:
shira committed 2026-10-11 09:48:44 +03:00
1 parent 53a125f2b5
commit facc1789b1
24 files changed
+3374 -6

No files matched your search

+17 -2
View File
@@ -573,7 +573,7 @@ backend/
usecase/files/ shared private file layer: policies, opaque keys, stream limits, checksums
usecase/notification/ mail requests and the consumer that stores them as deliveries, the quota gate, the service mail enqueue (`ServiceMailer`), the senders of service mail (`ServiceMailSender`) and of product notifications (`NewNotificationSender`), and their rights checks
usecase/notification/mailtemplate/ pure rendering of versioned service emails; the delivery consumer renders notifications with it
port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, organization and membership, policy, password hashing, and mail boundaries
port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, organization and membership, policy, password hashing, mail, and code runner boundaries
adapter/primary/http/
api/ generated ogen handler
middleware/ request log and request metrics by route template
@@ -588,7 +588,9 @@ backend/
mail/resend/ mail transport that sends one request to the Resend HTTP API per message
mail/resend/resendfixture/ local stand-in for the Resend API, for tests only; production never imports it
ml/api/ generated client from backend/codegen/ogen-ml.yml
code_runner/ client of the code runner: TLS 1.3 transport pinned to the configured CA, opaque idempotent run IDs, request and response validation
code_runner/api/ generated client from backend/codegen/ogen-code-runner.yml
code_runner/disabled/ code runner that runs nothing and reports itself unavailable
postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity, consent ledger, organization, membership, and policy repositories, health check
postgres/sqlc/ generated SQL adapter
redis/ cache adapter and Redis check
@@ -746,10 +748,23 @@ A checker is set per group: `exact`, `tokens`, `numbers` (numeric tokens are equ
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; running the A16 suite on the runner VM.
Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; the run queue and the practice usecases that call the backend port (the port and its client are implemented, see below); service metrics; running the A16 suite on the runner VM.
The A16 hostile-program suite (`make -C runner test-a16`, see [checks](TESTING.md#a16-hostile-program-suite)) is implemented and passes locally. Code practice is enabled only after the suite has passed on the runner VM with the verdict `pass`; any failed case blocks enabling it.
#### Backend port and client
Implemented: the outbound `CodeRunner` port (`backend/internal/port/outbound/code_runner.go`), its client over HTTPS (`backend/internal/adapter/secondary/code_runner/`, built on the generated client in `api/`), and the disabled runner (`code_runner/disabled/`). Bootstrap selects the runner from `CODE_RUNNER_URL` (`bootstrap/code_runner.go`): an unset URL selects the disabled runner, a set one the client, and an unusable setting stops startup instead of falling back. Nothing calls the port yet: the practice usecases, the run queue, and scoring are planned. The environment variables are in [DEPLOY.md](DEPLOY.md#code-runner-client).
- What leaves the backend. A request holds the language, the source, the technical limits, and the test groups with their checkers; the checker program of a task family is part of a group. It holds no account, attempt, task, or company identifier and no name or contact. `CodeRunRequest.Validate` checks the runner contract rules (ranges, unique IDs, checker parameters, the CPU budget of 300000 ms, the payload size) before anything is sent. A request prints as `[redacted code run request]` in every format and in logs, because the source is candidate work and the hidden tests are task secrets.
- Two calls, no hidden retries. `Submit` is idempotent by run key and reports `running`, `finished`, or `busy`; `Poll` reads the run without sending the payload again. Each makes one runner call and neither retries nor sleeps. `busy` is the runner's 503 `runner_busy`: the runner stored nothing, `RetryAfter` carries its `Retry-After`, and the caller keeps the queue and submits again with the same key. When the runner has lost a run (a restart or the retention time), `Poll` returns `ErrCodeRunNotFound` and the caller submits again.
- Opaque idempotent run ID. The run ID is HMAC-SHA256 over the attempt item ID, the submission ID, and a generation counter, keyed with `CODE_RUNNER_RUN_KEY` and domain-separated, formatted as a UUID. A retry of the same submission therefore reuses the run and the runner starts it once, while the runner cannot link an ID to an attempt or a submission and nobody can guess the ID of another submission. The key differs from the service token, which the runner knows. After a run the runner could not evaluate, the caller raises the generation: the runner keeps the stored failure under the old ID. The same key with another payload is refused (`ErrCodeRunKeyReused`).
- Infrastructure failure is never a verdict. `finished` always holds a validated result with the outcomes `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, and `runtime_error`, per group and test. Everything else is an error: `ErrCodeRunnerUnavailable` is the umbrella for a disabled runner, an unreachable one, a timeout, a failed TLS check, a rejected token (`ErrCodeRunnerUnauthorized`, HTTP 401), a server error, an answer outside the contract (`ErrCodeRunnerBadResponse`), and a run that finished with `infrastructure_failure` (`ErrCodeRunnerInfrastructureFailure`). With such an error the returned status is empty. A caller must report the practice as unavailable and keep the submission ungraded; it never scores, fails, or accepts it. A request the runner rejects as invalid (400, 413) is `ErrInvalidCodeRunRequest`, a bug of the task content, not of the candidate.
- Response validation. The generated client already checks the schema. The adapter adds the rules the schema cannot express: the run ID equals the one derived, a `running` run has no result, a 202 answer is `running`, the groups and tests of the result are the requested ones in order with the requested counts, a group stops at its first failed test, `passed_tests` equals the accepted tests, and the group, compile, and run outcomes agree with each other (the run outcome is `compile_error` or the outcome of the first failed group). A hidden test never passes on a diagnostic, even if a faulty runner sends one. A body above 4 MiB fails.
- Transport. TLS 1.3 only, the runner certificate is verified against the configured CA alone (the system roots are not trusted; there is no switch that skips verification), the optional `CODE_RUNNER_SERVER_NAME` changes only the name checked, redirects and environment proxies are not followed, one request is limited by `CODE_RUNNER_REQUEST_TIMEOUT`, and the token is sent only in the `Authorization` header and appears in no error or log. Error texts name the failure class, never the URL or the response body.
What the checks cover: the fixture tests run the client against a local TLS 1.3 stand-in that speaks the `api/runner` protocol (success, every outcome, compile error, runner timeout, busy, 401 and 5xx, malformed and contradictory answers, a stopped service, a foreign CA, TLS 1.2, idempotent retry). They do not prove sandbox isolation or behavior on the production runner VM. The run on a real runner is `make -C backend test-code-runner-live` (see DEPLOY) and has not been performed against the runner VM.
## Matching and explanations
Implemented as a deterministic search without ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. There is no new table, migration, or query file: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule.
+17 -2
View File
@@ -573,7 +573,7 @@ backend/
usecase/files/ общий закрытый файловый слой: политики, непрозрачные ключи, лимиты потока, контрольные суммы
usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки, шлюз квот, постановка служебной почты (`ServiceMailer`) и отправители служебной почты (`ServiceMailSender`) и продуктовых уведомлений (`NewNotificationSender`) с проверкой прав
usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем; обработчик доставки рендерит им уведомления
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, журнала согласий, организаций и членств, политики, хеширования паролей и почты
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, журнала согласий, организаций и членств, политики, хеширования паролей, почты и исполнителя кода
adapter/primary/http/
api/ generated ogen handler
middleware/ журнал и метрики запросов по шаблону маршрута
@@ -588,7 +588,9 @@ backend/
mail/resend/ почтовый транспорт, который отправляет одно письмо одним запросом к HTTP API Resend
mail/resend/resendfixture/ локальная замена API Resend только для тестов; production ее не импортирует
ml/api/ generated client из backend/codegen/ogen-ml.yml
code_runner/ клиент исполнителя кода: транспорт TLS 1.3 с привязкой к заданному CA, непрозрачные идемпотентные ID прогонов, проверка запроса и ответа
code_runner/api/ generated client из backend/codegen/ogen-code-runner.yml
code_runner/disabled/ исполнитель кода, который ничего не запускает и сообщает о недоступности
postgres/ pool, migrator, transactor, запись outbox и хранилище relay, хранилище обработчиков событий, репозитории identity, журнала согласий, организаций, членств и политики, health check
postgres/sqlc/ generated SQL adapter
redis/ адаптер кеша и проверка Redis
@@ -746,10 +748,23 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи
Исходы различают `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 на VM исполнителя.
Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; очередь прогонов и usecase практики, которые вызывают порт backend (порт и его клиент реализованы, см. ниже); метрики сервиса; прогон набора A16 на VM исполнителя.
Набор враждебных программ A16 (`make -C runner test-a16`, см. [проверки](TESTING.md#набор-враждебных-программ-a16)) реализован и проходит локально. Практика с кодом включается только после того, как набор прошел на VM исполнителя с вердиктом `pass`; любой проваленный случай блокирует включение.
#### Порт и клиент в backend
Реализовано: исходящий порт `CodeRunner` (`backend/internal/port/outbound/code_runner.go`), его клиент по HTTPS (`backend/internal/adapter/secondary/code_runner/` поверх generated client в `api/`) и отключенный исполнитель (`code_runner/disabled/`). Bootstrap выбирает исполнителя по `CODE_RUNNER_URL` (`bootstrap/code_runner.go`): незаданный URL выбирает отключенного исполнителя, заданный - клиент, а непригодная настройка останавливает запуск и не откатывается к другому варианту. Порт пока никто не вызывает: usecase практики, очередь прогонов и подсчет баллов запланированы. Переменные окружения описаны в [DEPLOY.md](DEPLOY.md#клиент-исполнителя-кода).
- Что уходит из backend. Запрос содержит язык, исходный код, технические лимиты и группы тестов с их checker; программа checker семейства задач входит в группу. В нем нет идентификатора аккаунта, попытки, задачи или компании, имени и контактов. `CodeRunRequest.Validate` проверяет правила контракта исполнителя (диапазоны, уникальные ID, параметры checker, CPU-бюджет 300000 мс, размер запроса) до отправки. Запрос печатается как `[redacted code run request]` в любом формате и в логах, потому что исходный код - работа кандидата, а скрытые тесты - секрет задачи.
- Два вызова без скрытых повторов. `Submit` идемпотентен по ключу прогона и сообщает `running`, `finished` или `busy`; `Poll` читает прогон, не отправляя данные снова. Каждый делает один вызов исполнителя и не повторяет и не ждет. `busy` - это 503 `runner_busy` исполнителя: он ничего не сохранил, `RetryAfter` несет его `Retry-After`, а очередь ведет вызывающий и отправляет снова с тем же ключом. Если исполнитель потерял прогон (перезапуск или истекшее хранение), `Poll` возвращает `ErrCodeRunNotFound`, и вызывающий отправляет прогон заново.
- Непрозрачный идемпотентный ID прогона. ID - это HMAC-SHA256 от ID элемента попытки, ID отправки и счетчика поколения с ключом `CODE_RUNNER_RUN_KEY` и разделением доменов, оформленный как UUID. Повтор той же отправки поэтому использует тот же прогон, и исполнитель запускает его один раз, но исполнитель не может связать ID с попыткой или отправкой, и никто не угадает ID чужой отправки. Ключ отличается от сервисного токена, который знает исполнитель. После прогона, который исполнитель не смог оценить, вызывающий повышает поколение: исполнитель хранит сбой под старым ID. Тот же ключ с другими данными отклоняется (`ErrCodeRunKeyReused`).
- Сбой инфраструктуры никогда не вердикт. `finished` всегда содержит проверенный результат с исходами `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded` и `runtime_error` по группам и тестам. Все остальное - ошибка: `ErrCodeRunnerUnavailable` объединяет отключенного исполнителя, недоступного, таймаут, неудачную проверку TLS, отклоненный токен (`ErrCodeRunnerUnauthorized`, HTTP 401), ошибку сервера, ответ вне контракта (`ErrCodeRunnerBadResponse`) и прогон, завершенный с `infrastructure_failure` (`ErrCodeRunnerInfrastructureFailure`). При такой ошибке возвращаемый статус пуст. Вызывающий должен сообщить, что практика недоступна, и оставить отправку неоцененной; он никогда не начисляет баллы, не проваливает и не принимает ее. Запрос, который исполнитель отклонил как неверный (400, 413), - это `ErrInvalidCodeRunRequest`, ошибка содержимого задачи, а не кандидата.
- Проверка ответа. Generated client уже проверяет схему. Адаптер добавляет правила, которые схема выразить не может: ID прогона равен выведенному, у `running` нет результата, ответ 202 - это `running`, группы и тесты результата - запрошенные, в том же порядке и с теми же числами, группа останавливается на первом проваленном тесте, `passed_tests` равен числу принятых тестов, а исходы группы, компиляции и прогона согласованы (исход прогона - `compile_error` или исход первой проваленной группы). Диагностика скрытого теста не передается дальше, даже если ее прислал неисправный исполнитель. Тело больше 4 МиБ отклоняется.
- Транспорт. Только TLS 1.3; сертификат исполнителя проверяется только по заданному CA (системные корни не доверенные, переключателя, который отключает проверку, нет); необязательный `CODE_RUNNER_SERVER_NAME` меняет только проверяемое имя; редиректы и прокси из окружения не используются; один запрос ограничен `CODE_RUNNER_REQUEST_TIMEOUT`; токен отправляется только в заголовке `Authorization` и не попадает ни в ошибки, ни в логи. Тексты ошибок называют класс сбоя, но не URL и не тело ответа.
Что покрывают проверки: тесты с fixture запускают клиент против локальной замены с TLS 1.3, которая говорит по протоколу `api/runner` (успех, каждый исход, ошибка компиляции, таймаут исполнителя, занятость, 401 и 5xx, искаженные и противоречивые ответы, остановленный сервис, чужой CA, TLS 1.2, идемпотентный повтор). Они не доказывают изоляцию песочницы и поведение на производственной VM исполнителя. Прогон на настоящем исполнителе - `make -C backend test-code-runner-live` (см. DEPLOY); против VM исполнителя он не выполнялся.
## Подбор и объяснение
Реализован как детерминированный поиск без ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.md](../../api/README.md#подбор)). Код: usecase `backend/internal/usecase/matching/` (`search.go` - порядок работы, `filter.go` - фильтры, `score.go` - целочисленный расчет, `explain.go` - объяснение), список карточек `candidateview.Service.ListVisibleCards`, раздел политики `domain.MatchingPolicy` (`policy_matching.go`), связи навыков `domain.RelateEvidenceSkill` (`evidence_relation.go`), обработчик `adapter/primary/http/v1/matches.go` и сборка `bootstrap/matches.go`. Новых таблиц, миграций и файлов запросов нет: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре.