feat(practice): store code submissions and practice states apart from attempts

This commit is contained in:
shira committed 2026-10-11 14:58:04 +03:00
1 parent d5e169e71b
commit 51770eea6c
61 files changed
+8584 -135

No files matched your search

+15 -2
View File
@@ -786,13 +786,13 @@ 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; 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.
Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; the worker of the run queue that calls the backend port, and scoring (the port, its client, and the stored submissions 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).
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 submissions it will run are stored (see [Practice submissions](#practice-submissions)), and the worker of 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.
@@ -803,6 +803,19 @@ Implemented: the outbound `CodeRunner` port (`backend/internal/port/outbound/cod
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.
#### Practice submissions
Implemented: the storage of practice items, their submissions, and the execution jobs, separate from the attempt snapshot and the result. Code: migration `00052_create_assessment_practice_submissions.sql`, the domain `backend/internal/domain/assessment_practice.go`, the port `outbound.AssessmentPracticeRepository` (`port/outbound/assessment_practice.go`), the repository `adapter/secondary/postgres/assessment_practice.go`, the usecase `backend/internal/usecase/practice/`, the handler `adapter/primary/http/v1/practice.go`, and the wiring `bootstrap/practice.go`.
- Three tables. `assessment_practices` holds one practice item of an attempt, `main` or `additional` (one of each per attempt), with its private task content in `task` (languages, the source length bound, limits, the checker, the public examples, and exactly three hidden groups) and its state: `not_started`, `pending`, `finished`, or `failed` with `sandbox_busy` or `sandbox_error`. Its ID is the item ID the candidate sees and the attempt item of the run key. `assessment_practice_submissions` holds every submission: the mode `public` (a debug run) or `final` (the graded solution), the language, the source with its SHA-256, the candidate's own tests of a debug run, the idempotency scope, and the result, written once. `assessment_practice_jobs` holds the execution job of every submission. Triggers keep the identity and the task of a practice and the request part of a submission immutable: the database refuses to replace the source or the language of a stored submission, to write a second result, and to delete a submission other than by the cascade of its account, attempt, or practice.
- Transactional queue. A submission and its job (`queued`) are inserted in one transaction, so a job exists exactly when its submission committed, and a worker picks it later. The job table is the outbox of the runner: nothing outside PostgreSQL has to learn about a submission before it runs, so no Kafka event is written.
- Debug runs. `CreateMyAssessmentPracticeRun` (`POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs`) stores a `public` submission and answers 202 with the queued run; `GetMyAssessmentPracticeRun` reads it. A debug run carries the public examples and up to ten tests of the candidate and never a hidden group: the request built for the runner has none, and the response maps only the public groups of a stored result. The task content, the hidden tests, and the source never reach a response. A debug run changes neither the practice state nor the attempt version.
- Final solutions. `practice.Service.SubmitFinal` stores a `final` submission with its job and marks the practice `pending`. The stored solution sent again (the same language and source) stores nothing; another solution is refused while the practice is `pending` or `finished`, so the source of a graded solution never changes; a practice that failed in the sandbox accepts a solution again. No HTTP operation calls it yet: `SubmitMyAssessmentAnswer` will, once the attempt flow serves practice items, and then the attempt version advances in the same transaction.
- Gates. A practice accepts commands only while it is the current item: its attempt is in `practice_pending` (main) or `additional_practice_pending` (additional) and before its deadline, read under a share lock of the attempt. The account must be a verified candidate. Every read is scoped by the owner, so an attempt, practice, or run of another candidate reads as not found. Without `CODE_RUNNER_URL` the operations answer 503 and store nothing.
- Idempotency. A command reserves the generic idempotency record of its scope (a keyed digest of the operation, the key, and the account) in its transaction. A repeat with the same body within 24 hours returns the stored run or the current practice state, and another body answers `idempotency_key_reused`. Refusals are not stored and are evaluated again.
The attempt flow does not serve practice items yet, so no practice exists in production; the assignment (`AssessmentPracticeRepository.Create`) is called by tests only. Retention of stored sources is not defined yet.
## Matching and explanations
Implemented as a deterministic search that never calls ML and reads precomputed vectors (see [Semantic layer and explanations](#semantic-layer-and-explanations)): `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`. Visibility has no new query: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule.
+12
View File
@@ -642,6 +642,18 @@ On the runner host the suite runs from a bundle: `make -C runner a16-bundle` (`A
What the tests do not prove: isolation in the production VM until the suite has passed there; protection against kernel, nsjail, or cgroup vulnerabilities; the absence of side channels (timing, CPU caches); or behavior under load.
## Code practice tests
`TestAssessmentPracticeSubmissionStorage` in `backend/integration_test/assessment_practice_http_test.go` uses `bootstrap(t, postgresService, redisService)`, an isolated migrated database, the real router, the practice usecase, and the PostgreSQL repository. No flow serves practice items yet, so the test moves a real attempt to `practice_pending` and creates its main and additional practices directly; the synthetic task marks every hidden test text. The sequential cases are:
- A debug run answers 202 with `Cache-Control: no-store`, is stored with exactly one queued job, and a repeat with the same key and body returns the same run without a new row; the same key with another body answers 422. Another candidate, another attempt, and an unknown run read as 404.
- Refusals store nothing: a practice of another candidate (404), the additional practice while the attempt is at the main one (409), and a source over the bound of the task (400).
- A stored result that also holds a hidden group is shown with the public tests only; the response has only the contract fields and no hidden text, source, or test text.
- A final solution marks the practice `pending` and is stored with one job; a replay returns it, the same solution under a new key stores nothing, another solution conflicts, and a reused key with another body is refused. The database refuses to replace the source or the language of the stored solution, to delete it, and to write a second result. After a sandbox failure the practice accepts another solution, and the first one stays as it was.
- With the runner disabled a run is refused as unavailable and nothing is stored. At the end every stored submission has exactly one job.
`backend/internal/usecase/practice/request_test.go` checks that the runner request of a debug run holds only the public examples and the candidate's tests, and that of a final solution exactly the three hidden groups. The tests do not run code: the worker of the run queue is planned.
## Semantic matching tests
- ML service (`make -C ml test`, no model, no network): `tests/test_embeddings.py` checks the `POST /v1/embeddings` contract on the deterministic hash encoder: response order, normalization, equal vectors for two equal requests, micro-batches by length, 503 `service_unavailable` before readiness and ready only after the warm-up, 400 for too many texts, a length, and unknown fields, 413 for a body over the limit (with Content-Length and streamed), and no request text in the logs; `tests/test_model_files.py` checks the lock file (only safetensors and configs, a full revision, no code or pickle) and the size and SHA-256 verification.
+15 -2
View File
@@ -786,13 +786,13 @@ 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 и мониторингом; очередь прогонов и usecase практики, которые вызывают порт backend (порт и его клиент реализованы, см. ниже); метрики сервиса; прогон набора A16 на VM исполнителя.
Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; обработчик очереди прогонов, который вызывает порт 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#клиент-исполнителя-кода).
Реализовано: исходящий порт `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 выбирает отключенного исполнителя, заданный - клиент, а непригодная настройка останавливает запуск и не откатывается к другому варианту. Порт пока никто не вызывает: отправки, которые он будет запускать, хранятся (см. [Отправки практики](#отправки-практики)), а обработчик очереди прогонов и подсчет баллов запланированы. Переменные окружения описаны в [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`, и вызывающий отправляет прогон заново.
@@ -803,6 +803,19 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи
Что покрывают проверки: тесты с fixture запускают клиент против локальной замены с TLS 1.3, которая говорит по протоколу `api/runner` (успех, каждый исход, ошибка компиляции, таймаут исполнителя, занятость, 401 и 5xx, искаженные и противоречивые ответы, остановленный сервис, чужой CA, TLS 1.2, идемпотентный повтор). Они не доказывают изоляцию песочницы и поведение на производственной VM исполнителя. Прогон на настоящем исполнителе - `make -C backend test-code-runner-live` (см. DEPLOY); против VM исполнителя он не выполнялся.
#### Отправки практики
Реализовано: хранение элементов практики, их отправок и заданий на выполнение отдельно от снимка попытки и результата. Код: миграция `00052_create_assessment_practice_submissions.sql`, домен `backend/internal/domain/assessment_practice.go`, порт `outbound.AssessmentPracticeRepository` (`port/outbound/assessment_practice.go`), репозиторий `adapter/secondary/postgres/assessment_practice.go`, usecase `backend/internal/usecase/practice/`, обработчик `adapter/primary/http/v1/practice.go` и сборка `bootstrap/practice.go`.
- Три таблицы. `assessment_practices` хранит один элемент практики попытки, `main` или `additional` (не больше одного каждого вида на попытку), с закрытым содержимым задачи в `task` (языки, предел длины кода, лимиты, checker, публичные примеры и ровно три скрытые группы) и его состояние: `not_started`, `pending`, `finished` или `failed` с `sandbox_busy` или `sandbox_error`. Его ID - это ID элемента, который видит кандидат, и элемент попытки в ключе прогона. `assessment_practice_submissions` хранит каждую отправку: режим `public` (отладочный прогон) или `final` (оцениваемое решение), язык, исходный код с его SHA-256, собственные тесты кандидата для отладочного прогона, область идемпотентности и результат, который записывается один раз. `assessment_practice_jobs` хранит задание на выполнение каждой отправки. Триггеры делают неизменяемыми идентичность и задачу практики и запросную часть отправки: база отказывает в замене исходного кода или языка сохраненной отправки, во второй записи результата и в удалении отправки иначе как каскадом от ее аккаунта, попытки или практики.
- Транзакционная очередь. Отправка и ее задание (`queued`) вставляются в одной транзакции, поэтому задание существует ровно тогда, когда зафиксирована его отправка, а обработчик берет его позже. Таблица заданий служит outbox для исполнителя: никому вне PostgreSQL не нужно узнавать об отправке до ее запуска, поэтому событие в Kafka не пишется.
- Отладочные прогоны. `CreateMyAssessmentPracticeRun` (`POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs`) сохраняет отправку `public` и отвечает 202 с прогоном в очереди; `GetMyAssessmentPracticeRun` читает его. Отладочный прогон несет публичные примеры и до десяти тестов кандидата и никогда не несет скрытую группу: в запросе к исполнителю ее нет, а ответ показывает только публичные группы сохраненного результата. Содержимое задачи, скрытые тесты и исходный код никогда не попадают в ответ. Отладочный прогон не меняет ни состояние практики, ни версию попытки.
- Финальные решения. `practice.Service.SubmitFinal` сохраняет отправку `final` с ее заданием и переводит практику в `pending`. Повтор сохраненного решения (тот же язык и код) ничего не сохраняет; другое решение отклоняется, пока практика в `pending` или `finished`, поэтому код оцениваемого решения никогда не меняется; практика, на которой сломалась песочница, снова принимает решение. HTTP-операция пока его не вызывает: это будет делать `SubmitMyAssessmentAnswer`, когда поток попытки начнет выдавать элементы практики, и тогда версия попытки будет расти в той же транзакции.
- Условия. Практика принимает команды, только пока она текущий элемент: ее попытка в `practice_pending` (main) или `additional_practice_pending` (additional) и срок не прошел; это читается под разделяемой блокировкой попытки. Аккаунт должен быть подтвержденным кандидатом. Каждое чтение ограничено владельцем, поэтому попытка, практика или прогон другого кандидата читаются как отсутствующие. Без `CODE_RUNNER_URL` операции отвечают 503 и ничего не сохраняют.
- Идемпотентность. Команда резервирует общую запись идемпотентности своей области (ключевой дайджест операции, ключа и аккаунта) в своей транзакции. Повтор с тем же телом в течение 24 часов возвращает сохраненный прогон или текущее состояние практики, а другое тело получает `idempotency_key_reused`. Отказы не сохраняются и вычисляются заново.
Поток попытки пока не выдает элементы практики, поэтому в production практик нет; назначение (`AssessmentPracticeRepository.Create`) вызывают только тесты. Срок хранения исходного кода еще не определен.
## Подбор и объяснение
Реализован как детерминированный поиск, который не вызывает 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`. Видимость не получила новых запросов: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре.
+12
View File
@@ -642,6 +642,18 @@ Vitest работает в Node без DOM, поэтому ограничени
Что тесты не доказывают: изоляцию в production VM, пока набор там не прошел; защиту от уязвимостей ядра, nsjail или cgroup; отсутствие побочных каналов (время, кеш процессора) и устойчивость под нагрузкой.
## Тесты практики с кодом
`TestAssessmentPracticeSubmissionStorage` в `backend/integration_test/assessment_practice_http_test.go` использует `bootstrap(t, postgresService, redisService)`, изолированную базу с миграциями, настоящий роутер, usecase практики и репозиторий PostgreSQL. Поток попытки пока не выдает элементы практики, поэтому тест сам переводит настоящую попытку в `practice_pending` и создает ее основную и дополнительную практики; синтетическая задача помечает текст каждого скрытого теста. Последовательные случаи:
- Отладочный прогон отвечает 202 с `Cache-Control: no-store` и сохраняется ровно с одним заданием в очереди, а повтор с тем же ключом и телом возвращает тот же прогон без новой строки; тот же ключ с другим телом получает 422. Другой кандидат, другая попытка и неизвестный прогон читаются как 404.
- Отказы ничего не сохраняют: практика другого кандидата (404), дополнительная практика, пока попытка на основной (409), и код длиннее предела задачи (400).
- Сохраненный результат, в котором есть и скрытая группа, показывается только с публичными тестами; в ответе только поля контракта и нет скрытого текста, исходного кода и текстов тестов.
- Финальное решение переводит практику в `pending` и сохраняется с одним заданием; повтор возвращает его, то же решение под новым ключом ничего не сохраняет, другое решение дает конфликт, а ключ с другим телом отклоняется. База отказывает в замене исходного кода или языка сохраненного решения, в его удалении и во второй записи результата. После сбоя песочницы практика принимает другое решение, а первое остается неизменным.
- С отключенным исполнителем прогон отклоняется как недоступный, и ничего не сохраняется. В конце у каждой сохраненной отправки ровно одно задание.
`backend/internal/usecase/practice/request_test.go` проверяет, что запрос к исполнителю для отладочного прогона содержит только публичные примеры и тесты кандидата, а для финального решения - ровно три скрытые группы. Тесты не запускают код: обработчик очереди прогонов запланирован.
## Тесты семантического подбора
- ML-сервис (`make -C ml test`, без модели и сети): `tests/test_embeddings.py` проверяет контракт `POST /v1/embeddings` на детерминированном хеш-кодировщике: порядок ответа, нормировку, одинаковые векторы двух одинаковых запросов, микропакеты по длине, 503 `service_unavailable` до готовности и ready только после прогрева, 400 на лишние тексты, длину и неизвестные поля, 413 на тело больше лимита (с Content-Length и потоком), отсутствие текстов запроса в логах; `tests/test_model_files.py` проверяет lock-файл (только safetensors и конфиги, полная ревизия, без кода и pickle) и сверку размера и SHA-256.