feat(practice): queue practice runs with one running and ten waiting
This commit is contained in:
1 parent
51770eea6c
commit
754c745fba
40 files changed
+3040
-70
No files matched your search
+15
-2
@@ -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 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.
|
||||
Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; scoring the verdict of a final solution (the port, its client, the stored submissions, and the run queue 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 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).
|
||||
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. The practice queue worker calls the port (see [Practice queue](#practice-queue)); scoring is 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.
|
||||
@@ -816,6 +816,19 @@ Implemented: the storage of practice items, their submissions, and the execution
|
||||
|
||||
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.
|
||||
|
||||
#### 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.
|
||||
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
Logs carry the submission ID, mode, generation, attempts, and error class, never the source, the tests, or the account. Queue metrics are not implemented 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.
|
||||
|
||||
+20
-1
@@ -895,7 +895,7 @@ Checked on 2026-10-11 with the runner at commit `dcf03cb861e2` plus two fixes. T
|
||||
|
||||
## Code runner client
|
||||
|
||||
The backend calls the own code runner (see [the runner](ARCHITECTURE.md#code-runner)) through the `CodeRunner` port. It is off unless `CODE_RUNNER_URL` is set: the backend then selects a disabled runner, logs `code runner selected` with `enabled=false` and a warning, and reports every request as unavailable without running or grading anything. `.env.example` and the Compose file pass every variable below as empty, so a default stack never contacts a runner. Nothing in this build calls the port yet; the settings are validated at startup and the TLS client is built (no network call), so a wrong value fails fast.
|
||||
The backend calls the own code runner (see [the runner](ARCHITECTURE.md#code-runner)) through the `CodeRunner` port. It is off unless `CODE_RUNNER_URL` is set: the backend then selects a disabled runner, logs `code runner selected` with `enabled=false` and a warning, and reports every request as unavailable without running or grading anything. `.env.example` and the Compose file pass every variable below as empty, so a default stack never contacts a runner. Only the practice queue worker calls the port (see [below](#practice-queue-and-debug-run-limits)); the settings are validated at startup and the TLS client is built (no network call), so a wrong value fails fast.
|
||||
|
||||
When `CODE_RUNNER_URL` is empty, no other `CODE_RUNNER_*` variable may be set: the backend refuses to start rather than ignore a token. Errors name the setting and never print its value; the startup log names neither the URL nor a secret.
|
||||
|
||||
@@ -919,6 +919,25 @@ Checking a real runner. The unit tests run against a local protocol stand-in. To
|
||||
|
||||
`CODE_RUNNER_SERVER_NAME` is honored too. The target stops with an error when the three variables are unset, and the same tests are skipped by a plain `go test` because they run only when `CODE_RUNNER_LIVE_URL` is set. A pass proves that the client, the TLS settings, the token, and the runner agree on the protocol and that the runner grades the fixed programs as expected; it does not replace the A16 suite.
|
||||
|
||||
### Practice queue and debug run limits
|
||||
|
||||
With a code runner configured, the backend runs the practice queue worker as a goroutine next to the HTTP servers (design in [ARCHITECTURE.md](ARCHITECTURE.md#practice-queue)). It needs `DATABASE_URL`, uses its own PostgreSQL pool of at most two connections, and does not start without `CODE_RUNNER_URL`; queued jobs then wait in the database. One job runs at a time across all backend instances and ten more may wait; the limits are product rules, not settings. At shutdown the worker gives its job back at once; a killed backend leaves the job running until its lease expires, and then another instance or the restarted one takes it over without starting a second run. Compose passes none of the settings below, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. They are validated at startup even without a runner.
|
||||
|
||||
| Variable | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `PRACTICE_RUNS_PER_MINUTE` | `6` | New debug runs of one candidate per minute, from 1 to 600 (Redis limiter). Beyond it the run answers 429 with `Retry-After`. |
|
||||
| `PRACTICE_RUNS_PER_HOUR` | `60` | New debug runs of one candidate per hour, from `PRACTICE_RUNS_PER_MINUTE` to 36000. |
|
||||
| `PRACTICE_POLL_INTERVAL` | `1s` | Wait between two reads of a running run and after a pass that found nothing to run, from 10ms to 30s. |
|
||||
| `PRACTICE_JOB_LEASE` | `30s` | How long a claimed job belongs to one worker without a renewal; every poll renews it. Above `CODE_RUNNER_REQUEST_TIMEOUT` plus `PRACTICE_POLL_INTERVAL`, at most 10m. A crashed worker delays its job by at most this long. |
|
||||
| `PRACTICE_JOB_MAX_ATTEMPTS` | `5` | Failed tries and expired leases of a job before it fails without a verdict, from 1 to 100. A busy runner and a shutdown do not count. |
|
||||
|
||||
Leases are compared with the backend clock, so keep the hosts of all backend instances synchronized with NTP. A job that failed is `failed` in `assessment_practice_jobs` with `last_error_class` `runner_unavailable`, `runner_infrastructure_failure`, `invalid_request`, `run_timeout`, or `lease_expired`; the worker logs it at error level as `practice job failed in the infrastructure; nothing was graded`. The candidate can submit again; a failed job is never retried by an operator. Queue metrics are not implemented yet; count unfinished jobs with psql:
|
||||
|
||||
SELECT state, mode, count(*), min(available_at)
|
||||
FROM assessment_practice_jobs
|
||||
WHERE state IN ('queued', 'running')
|
||||
GROUP BY state, mode;
|
||||
|
||||
## Services and images
|
||||
|
||||
Container images use moving `latest` or `alpine` tags where the upstream publishes them. Check the current Compose references when updating the stack. These tags can move; the [release manifest](#release-manifest) records the actual image digests of a release. An SBOM is not produced yet. Application dependency lockfiles remain checked in separately.
|
||||
|
||||
+11
-1
@@ -652,7 +652,17 @@ What the tests do not prove: isolation in the production VM until the suite has
|
||||
- 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.
|
||||
`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.
|
||||
|
||||
`TestAssessmentPracticeQueue` in `backend/integration_test/assessment_practice_queue_test.go` uses the same harness with the Redis limiter (two debug runs a minute), the real PostgreSQL job store, executor, and worker, a fake runner that is idempotent by run key and counts the runs it starts, and a test clock for leases and waits. Its sequential cases are:
|
||||
|
||||
- Twelve candidates start a debug run at the same moment: eleven are accepted and exactly one answers 503 `service_unavailable` with `Retry-After` and stores nothing. While the runner holds the run, the jobs are one `running` and ten `queued`, and a second worker claims nothing. After the runner finishes, all eleven are `finished`, each submission ran once, and eleven results are stored.
|
||||
- With eleven runs queued, a final solution is answered with the practice `failed` and `sandbox_busy`: no submission is stored and the attempt version does not move. After the queue drains, the same solution is accepted and finished.
|
||||
- A busy runner puts the job back without a counted attempt and the job waits for the runner's `Retry-After`; an infrastructure failure counts one attempt, raises the generation, and keeps the practice `pending` without a result; after the backoff the next try finishes it.
|
||||
- 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.
|
||||
|
||||
## Semantic matching tests
|
||||
|
||||
|
||||
+15
-2
@@ -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 и мониторингом; обработчик очереди прогонов, который вызывает порт backend, и подсчет баллов (порт, его клиент и хранение отправок реализованы, см. ниже); метрики сервиса; прогон набора A16 на VM исполнителя.
|
||||
Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; подсчет баллов за вердикт финального решения (порт, его клиент, хранение отправок и очередь прогонов реализованы, см. ниже); метрики сервиса; прогон набора 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 выбирает отключенного исполнителя, заданный - клиент, а непригодная настройка останавливает запуск и не откатывается к другому варианту. Порт пока никто не вызывает: отправки, которые он будет запускать, хранятся (см. [Отправки практики](#отправки-практики)), а обработчик очереди прогонов и подсчет баллов запланированы. Переменные окружения описаны в [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`, и вызывающий отправляет прогон заново.
|
||||
@@ -816,6 +816,19 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи
|
||||
|
||||
Поток попытки пока не выдает элементы практики, поэтому в production практик нет; назначение (`AssessmentPracticeRepository.Create`) вызывают только тесты. Срок хранения исходного кода еще не определен.
|
||||
|
||||
#### Очередь практики
|
||||
|
||||
Реализовано: долговечная очередь с одним выполняемым и десятью ожидающими заданиями. Код: миграция `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`. Это не среда заданий по сроку: задание по сроку выполняет обработчик внутри транзакции, которая его завершает, а попытка практики секунды или минуты ждет внешний прогон, и держать транзакцию открытой так долго нельзя.
|
||||
|
||||
- Состояния. Задание бывает `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_RUNS_PER_MINUTE` и `PRACTICE_RUNS_PER_HOUR` новых отладочных прогонов (ограничитель в Redis по ключевому дайджесту аккаунта) и один незавершенный прогон на практику; оба лимита отвечают 429 с `Retry-After`. Сбой ограничителя отклоняет прогон как недоступный.
|
||||
- Без исполнителя выключено. Без `CODE_RUNNER_URL` обработчик не запускается, а операции отвечают 503 и ничего не сохраняют. Обработчик может работать на нескольких экземплярах backend; захват оставляет среди них одно выполняемое задание.
|
||||
|
||||
Логи содержат ID отправки, режим, поколение, попытки и класс сбоя, но не исходный код, тесты и аккаунт. Метрики очереди пока не реализованы.
|
||||
|
||||
## Подбор и объяснение
|
||||
|
||||
Реализован как детерминированный поиск, который не вызывает 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`. Видимость не получила новых запросов: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре.
|
||||
|
||||
+20
-1
@@ -897,7 +897,7 @@ systemd запускает Go-супервизор с `RootDirectory=/opt/lincod
|
||||
|
||||
## Клиент исполнителя кода
|
||||
|
||||
Backend вызывает собственный исполнитель кода (см. [исполнитель](ARCHITECTURE.md#исполнитель-кода)) через порт `CodeRunner`. Он выключен, пока не задан `CODE_RUNNER_URL`: тогда backend выбирает отключенного исполнителя, пишет в лог `code runner selected` с `enabled=false` и предупреждение, а каждый запрос сообщает как недоступный, ничего не запуская и не оценивая. `.env.example` и Compose-файл передают все переменные ниже пустыми, поэтому стек по умолчанию никогда не обращается к исполнителю. В этой сборке порт пока никто не вызывает; настройки проверяются при запуске и TLS-клиент создается (без сетевого вызова), поэтому неверное значение обнаруживается сразу.
|
||||
Backend вызывает собственный исполнитель кода (см. [исполнитель](ARCHITECTURE.md#исполнитель-кода)) через порт `CodeRunner`. Он выключен, пока не задан `CODE_RUNNER_URL`: тогда backend выбирает отключенного исполнителя, пишет в лог `code runner selected` с `enabled=false` и предупреждение, а каждый запрос сообщает как недоступный, ничего не запуская и не оценивая. `.env.example` и Compose-файл передают все переменные ниже пустыми, поэтому стек по умолчанию никогда не обращается к исполнителю. Порт вызывает только обработчик очереди практики (см. [ниже](#очередь-практики-и-лимиты-отладочных-прогонов)); настройки проверяются при запуске и TLS-клиент создается (без сетевого вызова), поэтому неверное значение обнаруживается сразу.
|
||||
|
||||
Когда `CODE_RUNNER_URL` пуст, ни одна другая переменная `CODE_RUNNER_*` задаваться не должна: backend отказывается запускаться, а не молча игнорирует токен. Ошибки называют настройку и не печатают ее значение; в стартовом логе нет ни URL, ни секретов.
|
||||
|
||||
@@ -921,6 +921,25 @@ Backend вызывает собственный исполнитель кода
|
||||
|
||||
`CODE_RUNNER_SERVER_NAME` тоже учитывается. Цель завершается ошибкой, если три переменные не заданы, а те же тесты при обычном `go test` пропускаются, потому что запускаются только при заданном `CODE_RUNNER_LIVE_URL`. Успех доказывает, что клиент, настройки TLS, токен и исполнитель согласованы по протоколу и что исполнитель оценивает фиксированные программы ожидаемо; он не заменяет набор A16.
|
||||
|
||||
### Очередь практики и лимиты отладочных прогонов
|
||||
|
||||
Когда исполнитель кода настроен, backend запускает обработчик очереди практики как горутину рядом с HTTP-серверами (устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#очередь-практики)). Ему нужен `DATABASE_URL`, он использует свой пул PostgreSQL не больше чем из двух соединений и не запускается без `CODE_RUNNER_URL`; задания в очереди тогда ждут в базе. На всех экземплярах backend одновременно выполняется одно задание и еще десять могут ждать; эти лимиты - правила продукта, а не настройки. При остановке обработчик сразу возвращает задание; убитый backend оставляет задание выполняемым до истечения аренды, а затем его забирает другой экземпляр или перезапущенный, не запуская второй прогон. Compose не передает ни одну из настроек ниже, поэтому стек использует значения по умолчанию; чтобы изменить настройку, добавьте ее в `environment` backend в `deploy/docker/docker-compose.yml`. Они проверяются при запуске и без исполнителя.
|
||||
|
||||
| Переменная | По умолчанию | Значение |
|
||||
| --- | --- | --- |
|
||||
| `PRACTICE_RUNS_PER_MINUTE` | `6` | Новые отладочные прогоны одного кандидата в минуту, от 1 до 600 (ограничитель в Redis). Сверх лимита прогон получает 429 с `Retry-After`. |
|
||||
| `PRACTICE_RUNS_PER_HOUR` | `60` | Новые отладочные прогоны одного кандидата в час, от `PRACTICE_RUNS_PER_MINUTE` до 36000. |
|
||||
| `PRACTICE_POLL_INTERVAL` | `1s` | Пауза между двумя чтениями выполняемого прогона и после прохода, который ничего не нашел, от 10ms до 30s. |
|
||||
| `PRACTICE_JOB_LEASE` | `30s` | Сколько взятое задание принадлежит одному обработчику без продления; каждый опрос его продлевает. Больше `CODE_RUNNER_REQUEST_TIMEOUT` плюс `PRACTICE_POLL_INTERVAL`, не больше 10m. Упавший обработчик задерживает свое задание не дольше этого срока. |
|
||||
| `PRACTICE_JOB_MAX_ATTEMPTS` | `5` | Неудачные попытки и истекшие аренды задания, после которых оно завершается без вердикта, от 1 до 100. Занятый исполнитель и остановка не считаются. |
|
||||
|
||||
Аренды сравниваются по часам backend, поэтому часы всех экземпляров backend нужно синхронизировать через NTP. Неудавшееся задание имеет в `assessment_practice_jobs` состояние `failed` и `last_error_class` `runner_unavailable`, `runner_infrastructure_failure`, `invalid_request`, `run_timeout` или `lease_expired`; обработчик пишет в лог на уровне error `practice job failed in the infrastructure; nothing was graded`. Кандидат может отправить решение снова; оператор неудавшиеся задания не перезапускает. Метрики очереди пока не реализованы; незавершенные задания можно посчитать через psql:
|
||||
|
||||
SELECT state, mode, count(*), min(available_at)
|
||||
FROM assessment_practice_jobs
|
||||
WHERE state IN ('queued', 'running')
|
||||
GROUP BY state, mode;
|
||||
|
||||
## Сервисы и образы
|
||||
|
||||
Для контейнерных образов выбраны moving tags `latest` или `alpine`, если upstream публикует такой вариант. При обновлении Compose сверяйте актуальные ссылки на образы. Теги `latest` и `alpine` могут перемещаться; фактические image digests выпуска фиксирует [манифест выпуска](#манифест-выпуска). SBOM пока не формируется. Lockfiles прикладных зависимостей сохраняются отдельно.
|
||||
|
||||
+11
-1
@@ -652,7 +652,17 @@ Vitest работает в Node без DOM, поэтому ограничени
|
||||
- Финальное решение переводит практику в `pending` и сохраняется с одним заданием; повтор возвращает его, то же решение под новым ключом ничего не сохраняет, другое решение дает конфликт, а ключ с другим телом отклоняется. База отказывает в замене исходного кода или языка сохраненного решения, в его удалении и во второй записи результата. После сбоя песочницы практика принимает другое решение, а первое остается неизменным.
|
||||
- С отключенным исполнителем прогон отклоняется как недоступный, и ничего не сохраняется. В конце у каждой сохраненной отправки ровно одно задание.
|
||||
|
||||
`backend/internal/usecase/practice/request_test.go` проверяет, что запрос к исполнителю для отладочного прогона содержит только публичные примеры и тесты кандидата, а для финального решения - ровно три скрытые группы. Тесты не запускают код: обработчик очереди прогонов запланирован.
|
||||
`backend/internal/usecase/practice/request_test.go` проверяет, что запрос к исполнителю для отладочного прогона содержит только публичные примеры и тесты кандидата, а для финального решения - ровно три скрытые группы.
|
||||
|
||||
`TestAssessmentPracticeQueue` в `backend/integration_test/assessment_practice_queue_test.go` использует ту же обвязку с ограничителем в Redis (два отладочных прогона в минуту), настоящие хранилище заданий PostgreSQL, исполнитель и обработчик, поддельного исполнителя кода, который идемпотентен по ключу прогона и считает запущенные прогоны, и тестовые часы для аренд и ожиданий. Последовательные случаи:
|
||||
|
||||
- Двенадцать кандидатов одновременно запускают отладочный прогон: одиннадцать принимаются, и ровно один получает 503 `service_unavailable` с `Retry-After` и ничего не сохраняет. Пока исполнитель держит прогон, задания - одно `running` и десять `queued`, а второй обработчик ничего не берет. После того как исполнитель закончил, все одиннадцать `finished`, каждая отправка выполнена один раз и сохранено одиннадцать результатов.
|
||||
- Пока в очереди одиннадцать прогонов, финальное решение получает практику в `failed` с `sandbox_busy`: отправка не сохраняется, версия попытки не меняется. Когда очередь освободилась, то же решение принимается и завершается.
|
||||
- Занятый исполнитель возвращает задание без учтенной попытки, и задание ждет его `Retry-After`; сбой инфраструктуры учитывает одну попытку, повышает поколение и оставляет практику в `pending` без результата; после паузы следующая попытка ее завершает.
|
||||
- Обработчик убит посреди задания (его пул закрыт, поэтому вернуть задание он не может): другой обработчик ничего не берет, пока аренда жива, забирает задание после ее истечения и завершает его с тем же ключом прогона: один прогон у исполнителя, одна учтенная попытка захвата и один результат; позднее завершение от убитого обработчика отклоняется и не меняет результат.
|
||||
- Второй отладочный прогон, пока первый не завершен, и третий в пределах минуты получают 429 `rate_limited` с `Retry-After` и ничего не сохраняют.
|
||||
|
||||
Unit-тесты: `usecase/practice/execute_test.go` с подделками проверяет, что недоступный исполнитель сохраняет ключ прогона, сбой инфраструктуры и повторно использованный ключ повышают поколение, неверный запрос и последняя попытка завершаются без сохраненного результата, потерянный прогон отправляется снова, а остановка возвращает задание без учета попытки. `config/practice_test.go` проверяет значения по умолчанию и отклоняемые значения настроек практики. Тесты не запускают код в песочнице и не доказывают время работы настоящего исполнителя.
|
||||
|
||||
## Тесты семантического подбора
|
||||
|
||||
|
||||
Reference in new issue
Block a user