feat(practice): run practice jobs on the code runner with one stored result per run

This commit is contained in:
shira committed 2026-10-11 19:31:08 +03:00
1 parent 9385b2ddd4
commit 9344228e84
17 files changed
+1010 -35

No files matched your search

+5 -2
View File
@@ -818,11 +818,14 @@ The attempt flow does not serve practice items yet, so no practice exists in pro
#### Practice queue
Implemented: a durable queue with one running and ten queued jobs. Code: migration `00053_create_assessment_practice_queue.sql`, the port `outbound.PracticeJobStore` (`port/outbound/assessment_practice_queue.go`), the store `adapter/secondary/postgres/assessment_practice_queue.go`, the executor `usecase/practice/execute.go`, the worker `backend/internal/worker/practicequeue/`, and the wiring `bootstrap/practice.go`. It is not the scheduled job runtime: a scheduled job runs its handler inside the transaction that completes it, while a practice try waits seconds or minutes for an external run, and no transaction may stay open that long.
Implemented: a durable queue with one running and ten queued jobs. Code: migrations `00053_create_assessment_practice_queue.sql` and `00054_add_practice_job_runner_run.sql`, the port `outbound.PracticeJobStore` (`port/outbound/assessment_practice_queue.go`), the store `adapter/secondary/postgres/assessment_practice_queue.go`, the executor `usecase/practice/execute.go`, the worker `backend/internal/worker/practicequeue/`, and the wiring `bootstrap/practice.go`. It is not the scheduled job runtime: a scheduled job runs its handler inside the transaction that completes it, while a practice try waits seconds or minutes for an external run, and no transaction may stay open that long.
- States. A job is `queued`, `running` (under a lease of one worker), `finished` (its result is stored), or `failed` (the infrastructure gave up; never a verdict). It records the generation of its run key, the counted attempts, when it may be claimed (`available_at`), the lease, the start of the running try, and the class of the last failure.
- Atomic limits. Admission and the claim take the same transaction-scoped advisory lock and count the unfinished jobs. A command is admitted only while fewer than eleven jobs (one running and ten queued) are unfinished; the claim runs a job only while no other running job holds a live lease, so at most one job runs across all backend instances. A debug run beyond the limit answers 503 with `Retry-After` and stores nothing. A final solution beyond it stores nothing either: the practice becomes `failed` with `sandbox_busy`, which consumes nothing and accepts the solution again. The claim prefers a running job whose lease expired, then final solutions before debug runs, and skips rows that another transaction locks, so it never waits for a row lock while it holds the queue lock.
- One try. The executor builds the runner request from the stored task and submission, submits it, and polls the run every `PRACTICE_POLL_INTERVAL`, renewing the lease each time. A finished run stores the result once (`result IS NULL` guard), finishes the job, and, for the latest final submission of a pending practice, finishes the practice, in one transaction guarded by the lease owner and the start of the try. A busy runner puts the job back for the time it asked for (1 s to 1 min) without counting an attempt. A runner that is unreachable, refuses the token, or answers outside its contract is retried with the same run key after a backoff (2 s doubling to 1 min); a run the runner could not evaluate, or a key it holds with another payload, is retried with the next generation, so the next try is a new run; a lost run is submitted again. After `PRACTICE_JOB_MAX_ATTEMPTS` counted attempts, or for a task that cannot form a valid request, the job fails and a final practice becomes `failed` with `sandbox_error`; nothing is graded. A run that stays unfinished for 10 minutes counts as a failed try.
- One try. The executor builds the runner request from the stored task and submission, submits it, and polls the run every `PRACTICE_POLL_INTERVAL`, renewing the lease each time. A finished run stores the result once (`result IS NULL` guard), finishes the job with the opaque run ID of the runner run (`runner_run_id`, unique, set only on a finished job), and, for the latest final submission of a pending practice, finishes the practice, in one transaction guarded by the lease owner and the start of the try. A busy runner puts the job back for the time it asked for (1 s to 1 min) without counting an attempt. A runner that is unreachable, refuses the token, or answers outside its contract is retried with the same run key after a backoff (2 s doubling to 1 min); a run the runner could not evaluate, or a key it holds with another payload, is retried with the next generation, so the next try is a new run; a lost run is submitted again. After `PRACTICE_JOB_MAX_ATTEMPTS` counted attempts, or for a task that cannot form a valid request, the job fails and a final practice becomes `failed` with `sandbox_error`; nothing is graded. A run that stays unfinished for 10 minutes counts as a failed try.
- Runner isolation. The runner request carries the language, the source, the limits, and the test groups, nothing else: a debug run has the public examples and the candidate's own tests, a final solution the hidden groups only. The attempt item, the submission, and the generation reach the runner only as the opaque run ID, an HMAC under `CODE_RUNNER_RUN_KEY`, so the runner cannot link a run to a candidate. The stored `runner_run_id` is that ID: it lets an operator match a stored result to the runner's own log line without the runner learning who the candidate is.
- Repeats. A response lost or cut after the runner accepted the run, a request timeout, and a restart of the worker all end in a retry with the same run key, so the runner returns the run it already holds (200 instead of 202) and starts none. The result is written under the lease of the try and the `result IS NULL` guard, and the database refuses a second result, so a run has at most one result and one `runner_run_id`.
- Infrastructure failure. A runner that is stopped, unreachable, or answers outside its contract never produces a verdict. While tries remain, a debug run reads as `queued`, which tells the client to read it again; after the last try it reads as `failed` with `sandbox_error` and no result, a final practice becomes `failed` with `sandbox_error`, and neither changes the attempt, its result, or the confirmed category of the candidate. A new debug run or final solution is accepted at once.
- Restart. A worker that stops gives its job back at once without counting. A worker that dies leaves the lease to expire; the next claim takes the job over with the same generation and counts one attempt, the runner returns the run it already has, and the result is stored once. A late completion by the dead worker changes nothing, because the job no longer belongs to its try.
- Debug run limits. Besides the queue, a candidate gets at most `PRACTICE_RUNS_PER_MINUTE` and `PRACTICE_RUNS_PER_HOUR` new debug runs (the Redis limiter, keyed by a keyed digest of the account) and one unfinished run per practice; both answer 429 with `Retry-After`. A limiter failure refuses the run as unavailable.
- Off without a runner. Without `CODE_RUNNER_URL` the worker does not start, and the operations answer 503 and store nothing. Several backend instances may run the worker; the claim keeps one job running among them.
+11 -1
View File
@@ -662,7 +662,17 @@ What the tests do not prove: isolation in the production VM until the suite has
- A worker is killed mid-job (its pool closed, so it cannot give the job back): another worker claims nothing while the lease lives, takes the job over after it expires, and finishes it on the same run key, with one run on the runner, one counted takeover, and one result; a late completion by the killed worker is refused and leaves the result unchanged.
- A second debug run while the first is unfinished, and a third within a minute, answer 429 `rate_limited` with `Retry-After` and store nothing.
Unit tests: `usecase/practice/execute_test.go` checks with fakes that an unreachable runner keeps the run key, an infrastructure failure and a reused key raise the generation, an invalid request and the last attempt fail without a stored result, a lost run is submitted again, and a shutdown gives the job back uncounted. `config/practice_test.go` checks the defaults and refused values of the practice settings. The tests do not run code in a sandbox and do not prove the timing of a real runner.
`TestAssessmentPracticeRunnerProtocol` in `backend/integration_test/assessment_practice_runner_test.go` uses the same harness with the real queue worker and the real TLS 1.3 client of the code runner (`adapter/secondary/code_runner`), against a local fixture of the runner protocol (`practice_runner_fixture_test.go`: an `httptest` TLS server with the bearer token, PUT and GET of `/v1/runs/{id}`, one run per run ID, and 422 for another payload). The fixture does not run code: it recognizes one Python and one Go program that print the sum of two integers and compares their output with the expected output of each test, and a failed public test carries the program output as its diagnostic. The production runner VM is not called. Sequential cases:
- A Python and a Go debug run of two candidates finish through the API. Each candidate's own test expects a wrong sum, so the diagnostic shows what that program printed: `got 42` for the Python submission and `got 123` for the Go one, never the other's. The job keeps the `runner_run_id` of the run, and the fixture started that run from the source of that submission. The wire request has the fields `groups`, `language`, `limits`, and `source` only, the groups `public` and `custom` and no hidden group, headers limited to transport and the service token, a version 8 run ID that is none of the user, attempt, practice, or submission IDs, and none of those IDs, the email, or the session cookie in the path, headers, or body. Another candidate reads the run as 404.
- A final solution whose response is cut after the runner accepted the run (the connection is dropped) is retried after the backoff on the same run key: the runner holds one run, the job is `finished` with one counted attempt and generation 0, exactly one final result is stored, and its `runner_run_id` is that run. The wire request of a final solution has the groups `hidden-1` to `hidden-3` only.
- A debug run whose answer outlasts the request timeout ends the try as a retry, the run reads as `queued`, and the repeat joins the run the runner already holds.
- A worker that died mid-run (its pool is closed) is replaced by a worker with a new client built from the same settings after the lease expires. The new client derives the same run ID, so the runner still holds one run, one takeover is counted, and one result and one `runner_run_id` are stored.
- With the runner stopped, a debug run stays `queued` while tries remain, then reads as `failed` with `sandbox_error`, no result, no `runner_run_id`, and a finished time. The attempt state and version, the result count, and the confirmed categories of the candidate are the same before and after, and the practice is still `not_started`. A new debug run on the same practice is accepted and finishes once a working runner is back. A final solution with the stopped runner makes the practice `failed` with `sandbox_error` and no result, leaves the candidate state unchanged, and is accepted again and finished by a working runner. In the end no `runner_run_id` belongs to two jobs.
The fixture proves the protocol path and the storage and retry rules; it does not prove that a real sandbox compiles or runs Python and Go or the timing of a real runner.
Unit tests: `usecase/practice/execute_test.go` checks with fakes that an unreachable runner keeps the run key, an infrastructure failure and a reused key raise the generation, an invalid request and the last attempt fail without a stored result, a lost run is submitted again, a shutdown gives the job back uncounted, and a finished run without a valid run ID is retried and stores no result while a valid one is stored with the result. `config/practice_test.go` checks the defaults and refused values of the practice settings. The tests do not run code in a sandbox and do not prove the timing of a real runner.
## Semantic matching tests
+5 -2
View File
@@ -818,11 +818,14 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи
#### Очередь практики
Реализовано: долговечная очередь с одним выполняемым и десятью ожидающими заданиями. Код: миграция `00053_create_assessment_practice_queue.sql`, порт `outbound.PracticeJobStore` (`port/outbound/assessment_practice_queue.go`), хранилище `adapter/secondary/postgres/assessment_practice_queue.go`, исполнитель `usecase/practice/execute.go`, обработчик `backend/internal/worker/practicequeue/` и сборка `bootstrap/practice.go`. Это не среда заданий по сроку: задание по сроку выполняет обработчик внутри транзакции, которая его завершает, а попытка практики секунды или минуты ждет внешний прогон, и держать транзакцию открытой так долго нельзя.
Реализовано: долговечная очередь с одним выполняемым и десятью ожидающими заданиями. Код: миграции `00053_create_assessment_practice_queue.sql` и `00054_add_practice_job_runner_run.sql`, порт `outbound.PracticeJobStore` (`port/outbound/assessment_practice_queue.go`), хранилище `adapter/secondary/postgres/assessment_practice_queue.go`, исполнитель `usecase/practice/execute.go`, обработчик `backend/internal/worker/practicequeue/` и сборка `bootstrap/practice.go`. Это не среда заданий по сроку: задание по сроку выполняет обработчик внутри транзакции, которая его завершает, а попытка практики секунды или минуты ждет внешний прогон, и держать транзакцию открытой так долго нельзя.
- Состояния. Задание бывает `queued`, `running` (под арендой одного обработчика), `finished` (результат сохранен) или `failed` (инфраструктура отказалась от задания; это никогда не вердикт). Оно хранит поколение ключа прогона, учтенные попытки, момент, когда его можно взять (`available_at`), аренду, начало текущей попытки и класс последнего сбоя.
- Атомарные лимиты. Допуск и захват берут одну транзакционную advisory-блокировку и считают незавершенные задания. Команда допускается, только пока незавершенных заданий меньше одиннадцати (одно выполняется и десять ждут); захват запускает задание, только пока ни одно другое выполняемое задание не держит живую аренду, поэтому на всех экземплярах backend выполняется не больше одного задания. Отладочный прогон сверх лимита получает 503 с `Retry-After` и ничего не сохраняет. Финальное решение сверх лимита тоже ничего не сохраняет: практика становится `failed` с `sandbox_busy`, что ничего не расходует и снова принимает решение. Захват сначала берет выполняемое задание с истекшей арендой, затем финальные решения раньше отладочных прогонов и пропускает строки, заблокированные другой транзакцией, поэтому никогда не ждет блокировку строки, удерживая блокировку очереди.
- Одна попытка. Исполнитель строит запрос к исполнителю кода из сохраненной задачи и отправки, отправляет его и опрашивает прогон каждые `PRACTICE_POLL_INTERVAL`, каждый раз продлевая аренду. Завершенный прогон сохраняет результат один раз (условие `result IS NULL`), завершает задание и, для последнего финального решения практики в `pending`, завершает практику; все это в одной транзакции под условием владельца аренды и начала попытки. Занятый исполнитель возвращает задание в очередь на запрошенное им время (от 1 с до 1 мин) без учета попытки. Недоступный исполнитель, отказ в токене или ответ вне контракта повторяются с тем же ключом прогона после паузы (2 с, удваиваясь до 1 мин); прогон, который исполнитель не смог оценить, или ключ, под которым он хранит другие данные, повторяются со следующим поколением, то есть новым прогоном; потерянный прогон отправляется снова. После `PRACTICE_JOB_MAX_ATTEMPTS` учтенных попыток или для задачи, из которой не строится корректный запрос, задание завершается с `failed`, а финальная практика становится `failed` с `sandbox_error`; ничего не оценивается. Прогон, который не завершился за 10 минут, считается неудачной попыткой.
- Одна попытка. Исполнитель строит запрос к исполнителю кода из сохраненной задачи и отправки, отправляет его и опрашивает прогон каждые `PRACTICE_POLL_INTERVAL`, каждый раз продлевая аренду. Завершенный прогон сохраняет результат один раз (условие `result IS NULL`), завершает задание с непрозрачным ID прогона исполнителя (`runner_run_id`, уникален, задается только у завершенного задания) и, для последнего финального решения практики в `pending`, завершает практику; все это в одной транзакции под условием владельца аренды и начала попытки. Занятый исполнитель возвращает задание в очередь на запрошенное им время (от 1 с до 1 мин) без учета попытки. Недоступный исполнитель, отказ в токене или ответ вне контракта повторяются с тем же ключом прогона после паузы (2 с, удваиваясь до 1 мин); прогон, который исполнитель не смог оценить, или ключ, под которым он хранит другие данные, повторяются со следующим поколением, то есть новым прогоном; потерянный прогон отправляется снова. После `PRACTICE_JOB_MAX_ATTEMPTS` учтенных попыток или для задачи, из которой не строится корректный запрос, задание завершается с `failed`, а финальная практика становится `failed` с `sandbox_error`; ничего не оценивается. Прогон, который не завершился за 10 минут, считается неудачной попыткой.
- Изоляция исполнителя. Запрос к исполнителю содержит язык, исходный код, лимиты и группы тестов, и ничего больше: отладочный прогон несет публичные примеры и тесты кандидата, финальное решение только скрытые группы. Элемент попытки, отправка и поколение попадают к исполнителю только как непрозрачный ID прогона, HMAC под `CODE_RUNNER_RUN_KEY`, поэтому исполнитель не может связать прогон с кандидатом. Сохраненный `runner_run_id` и есть этот ID: по нему оператор сопоставляет сохраненный результат со строкой журнала самого исполнителя, а исполнитель не узнает, кто кандидат.
- Повторы. Потерянный или оборванный после приема прогона ответ, тайм-аут запроса и перезапуск обработчика заканчиваются повтором с тем же ключом прогона, поэтому исполнитель возвращает уже существующий прогон (200 вместо 202) и новый не запускает. Результат пишется под арендой попытки и условием `result IS NULL`, а база отказывает во втором результате, поэтому у прогона не больше одного результата и одного `runner_run_id`.
- Сбой инфраструктуры. Остановленный, недостижимый или отвечающий вне контракта исполнитель никогда не дает вердикта. Пока остаются попытки, отладочный прогон читается как `queued`, то есть клиенту нужно прочитать его снова; после последней попытки он читается как `failed` с `sandbox_error` без результата, финальная практика становится `failed` с `sandbox_error`, и ничто из этого не меняет попытку, ее результат и подтвержденную категорию кандидата. Новый отладочный прогон или финальное решение принимается сразу.
- Перезапуск. Остановленный обработчик сразу возвращает задание без учета попытки. Упавший обработчик оставляет аренду истекать; следующий захват забирает задание с тем же поколением и учитывает одну попытку, исполнитель возвращает уже существующий прогон, а результат сохраняется один раз. Позднее завершение от упавшего обработчика ничего не меняет, потому что задание больше не принадлежит его попытке.
- Лимиты отладочных прогонов. Кроме очереди, кандидат получает не больше `PRACTICE_RUNS_PER_MINUTE` и `PRACTICE_RUNS_PER_HOUR` новых отладочных прогонов (ограничитель в Redis по ключевому дайджесту аккаунта) и один незавершенный прогон на практику; оба лимита отвечают 429 с `Retry-After`. Сбой ограничителя отклоняет прогон как недоступный.
- Без исполнителя выключено. Без `CODE_RUNNER_URL` обработчик не запускается, а операции отвечают 503 и ничего не сохраняют. Обработчик может работать на нескольких экземплярах backend; захват оставляет среди них одно выполняемое задание.
+11 -1
View File
@@ -662,7 +662,17 @@ Vitest работает в Node без DOM, поэтому ограничени
- Обработчик убит посреди задания (его пул закрыт, поэтому вернуть задание он не может): другой обработчик ничего не берет, пока аренда жива, забирает задание после ее истечения и завершает его с тем же ключом прогона: один прогон у исполнителя, одна учтенная попытка захвата и один результат; позднее завершение от убитого обработчика отклоняется и не меняет результат.
- Второй отладочный прогон, пока первый не завершен, и третий в пределах минуты получают 429 `rate_limited` с `Retry-After` и ничего не сохраняют.
Unit-тесты: `usecase/practice/execute_test.go` с подделками проверяет, что недоступный исполнитель сохраняет ключ прогона, сбой инфраструктуры и повторно использованный ключ повышают поколение, неверный запрос и последняя попытка завершаются без сохраненного результата, потерянный прогон отправляется снова, а остановка возвращает задание без учета попытки. `config/practice_test.go` проверяет значения по умолчанию и отклоняемые значения настроек практики. Тесты не запускают код в песочнице и не доказывают время работы настоящего исполнителя.
`TestAssessmentPracticeRunnerProtocol` в `backend/integration_test/assessment_practice_runner_test.go` использует ту же обвязку с настоящим обработчиком очереди и настоящим клиентом исполнителя кода по TLS 1.3 (`adapter/secondary/code_runner`) против локальной подделки протокола исполнителя (`practice_runner_fixture_test.go`: TLS-сервер `httptest` с bearer-токеном, PUT и GET на `/v1/runs/{id}`, одним прогоном на ID прогона и 422 для другого содержимого). Подделка не запускает код: она узнает одну программу на Python и одну на Go, которые печатают сумму двух целых, и сравнивает их вывод с ожидаемым выводом каждого теста; у проваленного публичного теста вывод программы лежит в диагностике. Боевая VM исполнителя не вызывается. Последовательные случаи:
- Отладочные прогоны на Python и на Go двух кандидатов завершаются через API. Собственный тест каждого кандидата ожидает неверную сумму, поэтому диагностика показывает, что напечатала программа: `got 42` у отправки на Python и `got 123` у отправки на Go, но не наоборот. Задание хранит `runner_run_id` прогона, и подделка запустила этот прогон из исходного кода именно этой отправки. Запрос на проводе содержит только поля `groups`, `language`, `limits` и `source`, группы `public` и `custom` и ни одной скрытой, заголовки только транспортные и сервисный токен, ID прогона версии 8, который не совпадает ни с ID пользователя, попытки, практики или отправки, и ни одного из этих ID, email и cookie сессии в пути, заголовках и теле. Другой кандидат читает прогон как 404.
- Финальное решение, ответ на которое оборван после приема прогона исполнителем (соединение сброшено), повторяется после паузы с тем же ключом прогона: у исполнителя один прогон, задание `finished` с одной учтенной попыткой и поколением 0, сохранен ровно один финальный результат, и его `runner_run_id` - этот прогон. Запрос финального решения содержит только группы `hidden-1`...`hidden-3`.
- Отладочный прогон, ответ на который идет дольше тайм-аута запроса, завершает попытку повтором, прогон читается как `queued`, а повтор присоединяется к прогону, который исполнитель уже держит.
- Обработчик, умерший посреди прогона (его пул закрыт), заменяется после истечения аренды обработчиком с новым клиентом, собранным из тех же настроек. Новый клиент получает тот же ID прогона, поэтому у исполнителя по-прежнему один прогон, учтен один захват, сохранены один результат и один `runner_run_id`.
- При остановленном исполнителе отладочный прогон остается `queued`, пока есть попытки, затем читается как `failed` с `sandbox_error`, без результата и `runner_run_id`, со временем завершения. Состояние и версия попытки, число результатов и подтвержденные категории кандидата до и после одинаковы, а практика остается `not_started`. Новый отладочный прогон той же практики принимается и завершается, когда исполнитель снова работает. Финальное решение при остановленном исполнителе переводит практику в `failed` с `sandbox_error` без результата, не меняет состояние кандидата и принимается снова и завершается рабочим исполнителем. В конце ни один `runner_run_id` не принадлежит двум заданиям.
Подделка доказывает путь по протоколу и правила хранения и повтора; она не доказывает, что настоящая песочница собирает и запускает Python и Go, и не доказывает время работы настоящего исполнителя.
Unit-тесты: `usecase/practice/execute_test.go` с подделками проверяет, что недоступный исполнитель сохраняет ключ прогона, сбой инфраструктуры и повторно использованный ключ повышают поколение, неверный запрос и последняя попытка завершаются без сохраненного результата, потерянный прогон отправляется снова, остановка возвращает задание без учета попытки, а завершенный прогон без верного ID повторяется и не сохраняет результат, тогда как верный ID сохраняется вместе с результатом. `config/practice_test.go` проверяет значения по умолчанию и отклоняемые значения настроек практики. Тесты не запускают код в песочнице и не доказывают время работы настоящего исполнителя.
## Тесты семантического подбора