diff --git a/api/README.en.md b/api/README.en.md index fa6f324..d0f84e7 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -267,7 +267,7 @@ The `assessment` tag covers the assessment attempts of the current candidate (PR | `GET /api/v1/me/assessment-attempts/{attempt_id}` | `GetMyAssessmentAttempt` | session | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | | `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions` | `StartMyAssessmentAttemptSession` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | | `POST /api/v1/me/assessment-attempts/{attempt_id}/answers` | `SubmitMyAssessmentAnswer` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | -| `POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs` | `CreateMyAssessmentPracticeRun` | session and CSRF, Idempotency-Key | 202 `PracticeRun`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict`, 422, 503 `service_unavailable` | +| `POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs` | `CreateMyAssessmentPracticeRun` | session and CSRF, Idempotency-Key | 202 `PracticeRun`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict`, 422, 429 `rate_limited`, 503 `service_unavailable` | | `GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}` | `GetMyAssessmentPracticeRun` | session | 200 `PracticeRun`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | | `PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `HoldMyAssessmentWorkSession` | session and CSRF, `X-Attempt-Client` | 200 `AssessmentWorkSession`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` (another page holds it, or the attempt has no work session) | | `DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `ReleaseMyAssessmentWorkSession` | session and CSRF, `X-Attempt-Client` | 204, `Cache-Control: no-store` | 400, 401, 403, 404 | @@ -322,7 +322,7 @@ Items and answers: - One open window. A real attempt allows one open page at a time. The page generates a random identifier when it loads and sends it as `X-Attempt-Client` (16 to 64 characters of `A-Za-z0-9_-`) to `HoldMyAssessmentWorkSession`, which holds the work session for 120 seconds and asks the page to renew every 15 seconds, and to `ReleaseMyAssessmentWorkSession` when it closes. `StartMyAssessmentAttemptSession` and `SubmitMyAssessmentAnswer` take the same header as an optional parameter; while another page holds the session, a request from a different page or from none answers 409 `state_conflict` and changes nothing, and that refusal is not stored under the Idempotency-Key. An attempt that nobody holds, a released hold, and a hold that stopped renewing admit every page. It is a one-page-at-a-time rule, not a security boundary, and it is separate from `sessions` (`used`, `max`, `idle_timeout_seconds`), which count sequential work sessions. The server keeps only keyed digests of the page identifier and of the User-Agent bound to the attempt. No new problem code is added, so the page reads 409 on these operations as "open in another window". - An answer (`AssessmentAnswer`) has the same seven formats and carries only the answer. Unknown fields such as `score`, `duration`, or `seed` answer 400. The server records the times and scores the answer with the key of the item instance; time never enters the grade decision. Responses never say whether an answer was correct. - The practice solution runs asynchronously in the sandbox against three hidden check groups; the client polls the attempt while it is `pending`. The verdict shows only the score 0-3 and the pass state of each group. Every outcome caused by the solution (a compilation or runtime error, a time or memory limit) is `finished` with groups not passed. `failed` (`sandbox_busy` or `sandbox_error`) means only that the infrastructure could not run it; it consumes nothing. This keeps `failed` from acting as an oracle for hidden checks and from allowing endless retries. After `finished` no other solution is accepted. -- Debug runs (`CreateMyAssessmentPracticeRun`, `GetMyAssessmentPracticeRun`) run a solution against the public examples and up to ten tests of the candidate while the practice is the current item. They never run, list, or score a hidden check, and change neither the practice state, the verdict, nor the attempt version. A run is queued and read by its own identifier; a repeat with the same Idempotency-Key and body returns the stored run. Without a configured sandbox the operation answers 503 `service_unavailable` and stores nothing. +- Debug runs (`CreateMyAssessmentPracticeRun`, `GetMyAssessmentPracticeRun`) run a solution against the public examples and up to ten tests of the candidate while the practice is the current item. They never run, list, or score a hidden check, and change neither the practice state, the verdict, nor the attempt version. A run is queued and read by its own identifier; a repeat with the same Idempotency-Key and body returns the stored run. A per-candidate rate limit and one unfinished run per practice answer 429 `rate_limited` with `Retry-After`. The sandbox queue holds one running and ten waiting runs and solutions together; when it is full, a run answers 503 `service_unavailable` with `Retry-After`, and a final solution leaves the practice `failed` with `sandbox_busy`, which consumes nothing. Without a configured sandbox the operation answers 503 `service_unavailable` without `Retry-After`. A refusal stores nothing. - If the latest submission is still `failed` when the limit passes, the result is `not_determined` with the reason `sandbox_unavailable`. A practice never submitted gives `practice_incomplete`. - An attempt has no practice only in `demo_basic` while code practice is disabled until the sandbox isolation is verified; the result then lists the `practice_not_included` limitation. diff --git a/api/README.md b/api/README.md index 4d8dd13..7c3e51b 100644 --- a/api/README.md +++ b/api/README.md @@ -267,7 +267,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro | `GET /api/v1/me/assessment-attempts/{attempt_id}` | `GetMyAssessmentAttempt` | сессия | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | | `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions` | `StartMyAssessmentAttemptSession` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | | `POST /api/v1/me/assessment-attempts/{attempt_id}/answers` | `SubmitMyAssessmentAnswer` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | -| `POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs` | `CreateMyAssessmentPracticeRun` | сессия и CSRF, Idempotency-Key | 202 `PracticeRun`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict`, 422, 503 `service_unavailable` | +| `POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs` | `CreateMyAssessmentPracticeRun` | сессия и CSRF, Idempotency-Key | 202 `PracticeRun`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict`, 422, 429 `rate_limited`, 503 `service_unavailable` | | `GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}` | `GetMyAssessmentPracticeRun` | сессия | 200 `PracticeRun`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | | `PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `HoldMyAssessmentWorkSession` | сессия и CSRF, `X-Attempt-Client` | 200 `AssessmentWorkSession`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` (сеанс занят другой страницей или у попытки нет рабочего сеанса) | | `DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `ReleaseMyAssessmentWorkSession` | сессия и CSRF, `X-Attempt-Client` | 204, `Cache-Control: no-store` | 400, 401, 403, 404 | @@ -322,7 +322,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Одно открытое окно. Реальная попытка допускает одну открытую страницу за раз. Страница при загрузке создает случайный идентификатор и отправляет его как `X-Attempt-Client` (от 16 до 64 символов `A-Za-z0-9_-`) в `HoldMyAssessmentWorkSession`, который занимает рабочий сеанс на 120 секунд и просит страницу продлевать его раз в 15 секунд, и в `ReleaseMyAssessmentWorkSession` при закрытии. `StartMyAssessmentAttemptSession` и `SubmitMyAssessmentAnswer` принимают тот же заголовок как необязательный параметр; пока сеанс занят другой страницей, запрос от другой страницы или без заголовка получает 409 `state_conflict` и ничего не меняет, а этот отказ не сохраняется под Idempotency-Key. Попытка, которую никто не держит, освобожденное занятие и переставшее продлеваться пускают любую страницу. Это правило "одна страница за раз", а не граница безопасности, и оно отделено от `sessions` (`used`, `max`, `idle_timeout_seconds`), которые считают последовательные рабочие сеансы. Сервер хранит только ключевые отпечатки идентификатора страницы и User-Agent, привязанные к попытке. Новый код ошибки не добавлялся, поэтому страница читает 409 на этих операциях как "открыто в другом окне". - Ответ (`AssessmentAnswer`) имеет те же семь форматов и несет только ответ. Неизвестные поля вроде `score`, `duration` или `seed` дают 400. Сервер сам записывает время и оценивает ответ по ключу экземпляра задания; время не входит в решение о грейде. Ответы API никогда не сообщают, был ли ответ правильным. - Решение практики исполняется в песочнице асинхронно на трех группах скрытых проверок; клиент опрашивает попытку, пока оно `pending`. Вердикт показывает только балл 0-3 и прохождение каждой группы. Любой исход, вызванный самим решением (ошибка компиляции или выполнения, лимит времени или памяти), - это `finished` с непройденными группами. `failed` (`sandbox_busy` или `sandbox_error`) означает только, что инфраструктура не смогла исполнить решение; он ничего не расходует. Так `failed` не становится оракулом для скрытых проверок и не дает бесконечных повторов. После `finished` другое решение не принимается. -- Отладочные прогоны (`CreateMyAssessmentPracticeRun`, `GetMyAssessmentPracticeRun`) исполняют решение на публичных примерах и до десяти тестах кандидата, пока практика - текущий элемент. Они никогда не запускают, не показывают и не оценивают скрытые проверки и не меняют ни состояние практики, ни вердикт, ни версию попытки. Прогон ставится в очередь и читается по своему идентификатору; повтор с тем же Idempotency-Key и телом возвращает сохраненный прогон. Без настроенной песочницы операция отвечает 503 `service_unavailable` и ничего не сохраняет. +- Отладочные прогоны (`CreateMyAssessmentPracticeRun`, `GetMyAssessmentPracticeRun`) исполняют решение на публичных примерах и до десяти тестах кандидата, пока практика - текущий элемент. Они никогда не запускают, не показывают и не оценивают скрытые проверки и не меняют ни состояние практики, ни вердикт, ни версию попытки. Прогон ставится в очередь и читается по своему идентификатору; повтор с тем же Idempotency-Key и телом возвращает сохраненный прогон. Лимит на кандидата и один незавершенный прогон на практику отвечают 429 `rate_limited` с `Retry-After`. Очередь песочницы вмещает один выполняемый и десять ожидающих прогонов и решений вместе; когда она заполнена, прогон получает 503 `service_unavailable` с `Retry-After`, а финальное решение оставляет практику в `failed` с `sandbox_busy`, что ничего не расходует. Без настроенной песочницы операция отвечает 503 `service_unavailable` без `Retry-After`. Отказ ничего не сохраняет. - Если к истечению лимита последняя отправка все еще `failed`, результат - `not_determined` с причиной `sandbox_unavailable`. Неотправленная практика дает `practice_incomplete`. - Попытка бывает без практики только в `demo_basic`, пока кодовая практика выключена до проверки изоляции песочницы; результат тогда содержит ограничение `practice_not_included`. diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 5471f7c..96861b9 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -1292,11 +1292,11 @@ paths: The practice must be the current item: the attempt is in `practice_pending` for the main practice or `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the server answers 409 state_conflict. - Availability. When code practice is not enabled on this server, the server answers 503 service_unavailable and stores nothing. + Limits. Debug runs are bounded by a per-candidate rate limit and by one unfinished run per practice; either answers 429 rate_limited with Retry-After. The sandbox queue holds one running and ten waiting runs and submissions together; when it is full the server answers 503 service_unavailable with Retry-After and stores nothing. When code practice is not enabled on this server, the server answers 503 service_unavailable without Retry-After and stores nothing. - Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in its current state with 202, without starting another run. A different body with the same key answers 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are evaluated again. + Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in its current state with 202, without starting another run. A different body with the same key answers 422 idempotency_key_reused. Refusals (400, 404, 409, 429, 503) are not stored under the key and are evaluated again. - Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of another candidate), the state (409), then the solution against the item (400 with a pointer such as `/language` or `/source_code`). + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of another candidate), the state (409), the solution against the item (400 with a pointer such as `/language` or `/source_code`), the limits (429), then the queue (503). security: - sessionCookie: [] sessionCsrf: [] @@ -1357,6 +1357,8 @@ paths: $ref: '#/components/responses/StateConflict' '422': $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' '503': $ref: '#/components/responses/ServiceUnavailable' default: diff --git a/api/core/routes/candidate_assessment_attempt_practice_runs.yml b/api/core/routes/candidate_assessment_attempt_practice_runs.yml index bf637b4..1edf6c4 100644 --- a/api/core/routes/candidate_assessment_attempt_practice_runs.yml +++ b/api/core/routes/candidate_assessment_attempt_practice_runs.yml @@ -8,11 +8,11 @@ post: The practice must be the current item: the attempt is in `practice_pending` for the main practice or `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the server answers 409 state_conflict. - Availability. When code practice is not enabled on this server, the server answers 503 service_unavailable and stores nothing. + Limits. Debug runs are bounded by a per-candidate rate limit and by one unfinished run per practice; either answers 429 rate_limited with Retry-After. The sandbox queue holds one running and ten waiting runs and submissions together; when it is full the server answers 503 service_unavailable with Retry-After and stores nothing. When code practice is not enabled on this server, the server answers 503 service_unavailable without Retry-After and stores nothing. - Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in its current state with 202, without starting another run. A different body with the same key answers 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are evaluated again. + Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in its current state with 202, without starting another run. A different body with the same key answers 422 idempotency_key_reused. Refusals (400, 404, 409, 429, 503) are not stored under the key and are evaluated again. - Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of another candidate), the state (409), then the solution against the item (400 with a pointer such as `/language` or `/source_code`). + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of another candidate), the state (409), the solution against the item (400 with a pointer such as `/language` or `/source_code`), the limits (429), then the queue (503). security: - sessionCookie: [] sessionCsrf: [] @@ -70,6 +70,8 @@ post: $ref: ../components/responses.yml#/StateConflict "422": $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests "503": $ref: ../components/responses.yml#/ServiceUnavailable default: diff --git a/backend/config/config.go b/backend/config/config.go index e995db1..44daea9 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -162,6 +162,8 @@ type Config struct { // CodeRunner configures the client of the own code runner. It is disabled // unless CODE_RUNNER_URL is set. CodeRunner CodeRunnerSettings + // Practice configures the debug run limits and the practice queue worker. + Practice PracticeSettings // TrustedProxyCIDRs are the reverse proxies in front of the API. The // client address is taken from X-Forwarded-For only through them (see @@ -267,6 +269,11 @@ func (config *Config) loadIdentityAndProxySettings(lookup LookupEnv) error { return err } config.CodeRunner = codeRunner + practice, err := LoadPracticeSettings(lookup, codeRunner.RequestTimeout) + if err != nil { + return err + } + config.Practice = practice return config.loadTrustedProxies(lookup) } diff --git a/backend/config/practice.go b/backend/config/practice.go new file mode 100644 index 0000000..845d5ac --- /dev/null +++ b/backend/config/practice.go @@ -0,0 +1,95 @@ +package config + +import ( + "fmt" + "time" +) + +const ( + // Debug runs of one candidate are a technical abuse brake on the shared + // sandbox, not a product quota: a few runs a minute and a working + // session's worth an hour. + defaultPracticeRunsPerMinute = 6 + defaultPracticeRunsPerHour = 60 + maxPracticeRunsPerMinute = 600 + maxPracticeRunsPerHour = 36000 + // defaultPracticePollInterval is the wait between two reads of a running + // run and after a pass that found nothing to run. It is also the usual + // delay before a queued run starts. + defaultPracticePollInterval = time.Second + minPracticePollInterval = 10 * time.Millisecond + maxPracticePollInterval = 30 * time.Second + // defaultPracticeJobLease is how long a claimed practice job belongs to + // one worker without a renewal; every poll renews it. A worker that + // crashed delays its job by at most this long. + defaultPracticeJobLease = 30 * time.Second + maxPracticeJobLease = 10 * time.Minute + // defaultPracticeJobMaxAttempts bounds the failed tries and expired + // leases of a job before it fails without a verdict. + defaultPracticeJobMaxAttempts = 5 + maxPracticeJobMaxAttempts = 100 +) + +// PracticeSettings configure code practice: the rate limit of debug runs and +// the practice queue worker. The queue limits (one running, ten queued) are +// product rules in the practice usecase, not settings. +type PracticeSettings struct { + // RunsPerMinute and RunsPerHour bound the debug runs of one candidate. + RunsPerMinute int64 + RunsPerHour int64 + // PollInterval is the wait between two reads of a running run and after + // an empty pass of the queue worker. + PollInterval time.Duration + // JobLease is how long a claimed job belongs to one worker without a + // renewal. + JobLease time.Duration + // JobMaxAttempts bounds the failed tries of a job. + JobMaxAttempts int +} + +// LoadPracticeSettings reads the practice settings. requestTimeout is the +// code runner request timeout: a lease must outlast one runner call and one +// poll, or another worker could take a job over while its call is still +// running. +func LoadPracticeSettings(lookup LookupEnv, requestTimeout time.Duration) (PracticeSettings, error) { + settings := PracticeSettings{} + perMinute, err := intOrDefault(lookup, "PRACTICE_RUNS_PER_MINUTE", defaultPracticeRunsPerMinute) + if err != nil { + return PracticeSettings{}, err + } + perHour, err := intOrDefault(lookup, "PRACTICE_RUNS_PER_HOUR", defaultPracticeRunsPerHour) + if err != nil { + return PracticeSettings{}, err + } + settings.RunsPerMinute, settings.RunsPerHour = int64(perMinute), int64(perHour) + if settings.PollInterval, err = durationOrDefault(lookup, "PRACTICE_POLL_INTERVAL", defaultPracticePollInterval); err != nil { + return PracticeSettings{}, err + } + if settings.JobLease, err = durationOrDefault(lookup, "PRACTICE_JOB_LEASE", defaultPracticeJobLease); err != nil { + return PracticeSettings{}, err + } + if settings.JobMaxAttempts, err = intOrDefault(lookup, "PRACTICE_JOB_MAX_ATTEMPTS", defaultPracticeJobMaxAttempts); err != nil { + return PracticeSettings{}, err + } + return settings, settings.Validate(requestTimeout) +} + +// Validate checks the ranges. They are checked even without a code runner, so +// enabling the runner later cannot surface an old mistake. +func (settings PracticeSettings) Validate(requestTimeout time.Duration) error { + const location = "PracticeSettings.Validate" + switch { + case settings.RunsPerMinute < 1 || settings.RunsPerMinute > maxPracticeRunsPerMinute: + return fmt.Errorf("%s - PRACTICE_RUNS_PER_MINUTE must be between 1 and %d", location, maxPracticeRunsPerMinute) + case settings.RunsPerHour < settings.RunsPerMinute || settings.RunsPerHour > maxPracticeRunsPerHour: + return fmt.Errorf("%s - PRACTICE_RUNS_PER_HOUR must be between PRACTICE_RUNS_PER_MINUTE and %d", location, maxPracticeRunsPerHour) + case settings.PollInterval < minPracticePollInterval || settings.PollInterval > maxPracticePollInterval: + return fmt.Errorf("%s - PRACTICE_POLL_INTERVAL must be between %s and %s", location, minPracticePollInterval, maxPracticePollInterval) + case settings.JobLease <= requestTimeout+settings.PollInterval || settings.JobLease > maxPracticeJobLease: + return fmt.Errorf("%s - PRACTICE_JOB_LEASE must exceed CODE_RUNNER_REQUEST_TIMEOUT plus PRACTICE_POLL_INTERVAL and be at most %s", + location, maxPracticeJobLease) + case settings.JobMaxAttempts < 1 || settings.JobMaxAttempts > maxPracticeJobMaxAttempts: + return fmt.Errorf("%s - PRACTICE_JOB_MAX_ATTEMPTS must be between 1 and %d", location, maxPracticeJobMaxAttempts) + } + return nil +} diff --git a/backend/config/practice_test.go b/backend/config/practice_test.go new file mode 100644 index 0000000..16e48c7 --- /dev/null +++ b/backend/config/practice_test.go @@ -0,0 +1,43 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +func TestLoadFromEnvPracticeDefaults(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(nil)) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + want := PracticeSettings{RunsPerMinute: 6, RunsPerHour: 60, PollInterval: time.Second, JobLease: 30 * time.Second, JobMaxAttempts: 5} + if settings.Practice != want { + t.Fatalf("practice defaults = %+v, want %+v", settings.Practice, want) + } +} + +func TestLoadFromEnvRejectsInvalidPracticeSettings(t *testing.T) { + cases := map[string]struct { + values map[string]string + message string + }{ + "zero runs per minute": {map[string]string{"PRACTICE_RUNS_PER_MINUTE": "0"}, "PRACTICE_RUNS_PER_MINUTE"}, + "hour below minute": { + map[string]string{"PRACTICE_RUNS_PER_MINUTE": "10", "PRACTICE_RUNS_PER_HOUR": "5"}, "PRACTICE_RUNS_PER_HOUR", + }, + "poll too short": {map[string]string{"PRACTICE_POLL_INTERVAL": "1ms"}, "PRACTICE_POLL_INTERVAL"}, + // The lease must outlast one runner request (10s by default) and a poll. + "lease within a request": {map[string]string{"PRACTICE_JOB_LEASE": "10s"}, "PRACTICE_JOB_LEASE"}, + "no attempts": {map[string]string{"PRACTICE_JOB_MAX_ATTEMPTS": "0"}, "PRACTICE_JOB_MAX_ATTEMPTS"}, + "malformed duration": {map[string]string{"PRACTICE_JOB_LEASE": "soon"}, "PRACTICE_JOB_LEASE"}, + } + for name, testCase := range cases { + t.Run(name, func(t *testing.T) { + _, err := LoadFromEnv(testEnvironment(testCase.values)) + if err == nil || !strings.Contains(err.Error(), testCase.message) { + t.Fatalf("LoadFromEnv() error = %v, want one naming %s", err, testCase.message) + } + }) + } +} diff --git a/backend/db/migrations/00053_create_assessment_practice_queue.sql b/backend/db/migrations/00053_create_assessment_practice_queue.sql new file mode 100644 index 0000000..a4ad633 --- /dev/null +++ b/backend/db/migrations/00053_create_assessment_practice_queue.sql @@ -0,0 +1,73 @@ +-- +goose Up +-- The practice queue: the execution jobs of practice submissions become +-- durable work items that one worker at a time runs on the code runner. +-- +-- The queue holds at most one running and ten queued jobs. Admission and +-- the claim both take the transaction-scoped advisory lock of the queue and +-- count the unfinished jobs, so the limits hold across backend instances. A +-- job beyond them is never inserted: the command answers busy and stores +-- nothing that would consume an attempt. +-- +-- A running job holds a lease. A worker that stops without finishing leaves +-- the lease to expire, and the next claim takes the job over with the same +-- generation, so the runner, which is idempotent by run ID, returns the run +-- it already has instead of starting a second one. Lease and retry times come +-- from the application clock. +ALTER TABLE assessment_practice_jobs +-- Generation of the run key: raised after the runner could not evaluate +-- the source, so the next try is a new run. +ADD COLUMN generation integer NOT NULL DEFAULT 0, +-- Failed tries and expired leases counted so far. A busy runner counts +-- nothing. +ADD COLUMN attempts integer NOT NULL DEFAULT 0, +-- When a worker may claim a queued job: at once, after the wait the runner +-- asked for when it was busy, or after the backoff of a failed try. +ADD COLUMN available_at timestamptz, +ADD COLUMN lease_owner uuid, +ADD COLUMN lease_expires_at timestamptz, +-- When the running try was claimed; it bounds how long a run may stay +-- unfinished on the runner. +ADD COLUMN started_at timestamptz, +-- Bounded cause of the last failed try; never runner or candidate text. +ADD COLUMN last_error_class text; + +UPDATE assessment_practice_jobs SET available_at = created_at; + +ALTER TABLE assessment_practice_jobs +ALTER COLUMN available_at SET NOT NULL, +ADD CONSTRAINT assessment_practice_jobs_lease_when_running CHECK ( + (state = 'running') = (lease_owner IS NOT NULL) + AND (lease_owner IS NULL) = (lease_expires_at IS NULL) + AND (lease_owner IS NULL) = (started_at IS NULL) +), +ADD CONSTRAINT assessment_practice_jobs_counters CHECK ( + generation >= 0 AND attempts BETWEEN 0 AND 100 +), +ADD CONSTRAINT assessment_practice_jobs_error_class CHECK ( + last_error_class IS NULL OR last_error_class IN ( + 'runner_unavailable', + 'runner_infrastructure_failure', + 'invalid_request', + 'run_timeout', + 'lease_expired' + ) +); + +-- Serves the claim of the next queued job. +CREATE INDEX assessment_practice_jobs_queued_idx +ON assessment_practice_jobs (available_at, created_at) +WHERE state = 'queued'; + +-- +goose Down +DROP INDEX assessment_practice_jobs_queued_idx; +ALTER TABLE assessment_practice_jobs +DROP CONSTRAINT assessment_practice_jobs_error_class, +DROP CONSTRAINT assessment_practice_jobs_counters, +DROP CONSTRAINT assessment_practice_jobs_lease_when_running, +DROP COLUMN last_error_class, +DROP COLUMN started_at, +DROP COLUMN lease_expires_at, +DROP COLUMN lease_owner, +DROP COLUMN available_at, +DROP COLUMN attempts, +DROP COLUMN generation; diff --git a/backend/db/queries/assessment_practice.sql b/backend/db/queries/assessment_practice.sql index 4257d98..02841ec 100644 --- a/backend/db/queries/assessment_practice.sql +++ b/backend/db/queries/assessment_practice.sql @@ -124,12 +124,13 @@ INSERT INTO assessment_practice_submissions ( ); -- Queues the execution job of a submission in the transaction that stores --- the submission. +-- the submission. The job is available at once. -- name: InsertAssessmentPracticeJob :exec INSERT INTO assessment_practice_jobs ( submission_id, mode, state, + available_at, created_at, updated_at ) VALUES ( @@ -137,6 +138,7 @@ INSERT INTO assessment_practice_jobs ( sqlc.arg(mode), 'queued', sqlc.arg(created_at), + sqlc.arg(created_at), sqlc.arg(created_at) ); diff --git a/backend/db/queries/assessment_practice_queue.sql b/backend/db/queries/assessment_practice_queue.sql new file mode 100644 index 0000000..a186189 --- /dev/null +++ b/backend/db/queries/assessment_practice_queue.sql @@ -0,0 +1,192 @@ +-- The practice queue. Admission and the claim take the same +-- transaction-scoped advisory lock, so the count of unfinished jobs and the +-- change that depends on it are atomic across backend instances. A command +-- takes the lock after its attempt and practice row locks; the claim takes +-- it first and then skips job rows that another transaction locks, so a +-- claim never waits for a row lock while it holds the queue lock. + +-- name: LockAssessmentPracticeQueue :exec +SELECT pg_advisory_xact_lock(hashtextextended('lincodex.assessment.practice_queue', 0)); + +-- Counts the queued and running jobs; the caller holds the queue lock. +-- name: CountActiveAssessmentPracticeJobs :one +SELECT count(*)::integer AS active +FROM assessment_practice_jobs AS job +WHERE job.state IN ('queued', 'running'); + +-- Counts the unfinished debug runs of a practice; the caller holds the +-- practice row lock. +-- name: CountActiveAssessmentPracticeRuns :one +SELECT count(*)::integer AS active +FROM assessment_practice_jobs AS job +INNER JOIN assessment_practice_submissions AS submission ON job.submission_id = submission.id +WHERE + submission.practice_id = sqlc.arg(practice_id) + AND job.mode = 'public' + AND job.state IN ('queued', 'running'); + +-- Counts running jobs whose lease has not expired by now, the application +-- clock; the caller holds the queue lock. +-- name: CountLiveRunningAssessmentPracticeJobs :one +SELECT count(*)::integer AS running +FROM assessment_practice_jobs AS job +WHERE + job.state = 'running' + AND job.lease_expires_at > sqlc.arg(now)::timestamptz; + +-- Claims one job under the queue lock: first a running job whose lease +-- expired (its worker stopped without finishing it), then the next queued +-- job, final submissions before debug runs. A takeover keeps the generation, +-- so the runner returns the run it already has, and counts one attempt. +-- name: ClaimAssessmentPracticeJob :one +WITH candidate AS ( + SELECT + job.submission_id, + job.state = 'running' AS reclaimed + FROM assessment_practice_jobs AS job + WHERE + (job.state = 'queued' AND job.available_at <= sqlc.arg(now)::timestamptz) + OR (job.state = 'running' AND job.lease_expires_at <= sqlc.arg(now)::timestamptz) + ORDER BY + job.state = 'running' DESC, + job.mode = 'final' DESC, + job.available_at ASC, + job.created_at ASC, + job.submission_id ASC + LIMIT 1 + FOR UPDATE SKIP LOCKED +) + +UPDATE assessment_practice_jobs AS job +SET + state = 'running', + lease_owner = sqlc.arg(lease_owner), + lease_expires_at = sqlc.arg(lease_expires_at), + started_at = sqlc.arg(now)::timestamptz, + attempts = job.attempts + CASE WHEN candidate.reclaimed THEN 1 ELSE 0 END, + last_error_class = CASE + WHEN candidate.reclaimed THEN 'lease_expired' ELSE job.last_error_class + END, + updated_at = greatest(job.updated_at, clock_timestamp()) +FROM candidate +WHERE job.submission_id = candidate.submission_id +RETURNING + job.submission_id, + job.mode, + job.generation, + job.attempts, + candidate.reclaimed; + +-- Reads what a claimed job runs: the submission and the task of its +-- practice. +-- name: GetAssessmentPracticeJobWork :one +SELECT + submission.id, + submission.practice_id, + submission.user_id, + submission.mode, + submission.language, + submission.source, + submission.custom_tests, + submission.created_at, + practice.task +FROM assessment_practice_submissions AS submission +INNER JOIN assessment_practices AS practice ON submission.practice_id = practice.id +WHERE submission.id = sqlc.arg(submission_id); + +-- Renews the lease of a running try. The owner and the start time identify +-- the try, so a worker whose job was taken over changes nothing. +-- name: ExtendAssessmentPracticeJobLease :execrows +UPDATE assessment_practice_jobs +SET + lease_expires_at = sqlc.arg(lease_expires_at), + updated_at = greatest(updated_at, clock_timestamp()) +WHERE + submission_id = sqlc.arg(submission_id) + AND state = 'running' + AND lease_owner = sqlc.arg(lease_owner) + AND started_at = sqlc.arg(started_at); + +-- Puts a running try back into the queue: after a busy runner, a failed +-- try, or at shutdown. counted adds the try to the attempts. +-- name: RequeueAssessmentPracticeJob :execrows +UPDATE assessment_practice_jobs +SET + state = 'queued', + available_at = sqlc.arg(available_at), + generation = sqlc.arg(generation), + attempts = attempts + sqlc.arg(counted)::integer, + last_error_class = coalesce(sqlc.narg(error_class), last_error_class), + lease_owner = NULL, + lease_expires_at = NULL, + started_at = NULL, + updated_at = greatest(updated_at, clock_timestamp()) +WHERE + submission_id = sqlc.arg(submission_id) + AND state = 'running' + AND lease_owner = sqlc.arg(lease_owner) + AND started_at = sqlc.arg(started_at); + +-- Locks a running try for its completion and checks that it still belongs +-- to the worker. +-- name: LockClaimedAssessmentPracticeJob :one +SELECT job.mode +FROM assessment_practice_jobs AS job +WHERE + job.submission_id = sqlc.arg(submission_id) + AND job.state = 'running' + AND job.lease_owner = sqlc.arg(lease_owner) + AND job.started_at = sqlc.arg(started_at) +FOR UPDATE; + +-- Stores the result of a submission once; a second result changes nothing. +-- name: StoreAssessmentPracticeResult :execrows +UPDATE assessment_practice_submissions +SET + result = sqlc.arg(result), + result_at = greatest(created_at, clock_timestamp()) +WHERE + id = sqlc.arg(id) + AND result IS NULL; + +-- Ends a running try as finished or failed. +-- name: FinishAssessmentPracticeJob :execrows +UPDATE assessment_practice_jobs +SET + state = sqlc.arg(state), + finished_at = greatest(created_at, clock_timestamp()), + last_error_class = coalesce(sqlc.narg(error_class), last_error_class), + lease_owner = NULL, + lease_expires_at = NULL, + started_at = NULL, + updated_at = greatest(updated_at, clock_timestamp()) +WHERE + submission_id = sqlc.arg(submission_id) + AND state = 'running' + AND lease_owner = sqlc.arg(lease_owner) + AND started_at = sqlc.arg(started_at); + +-- Moves the practice of a final submission out of pending, but only while +-- that submission is the latest final one of the practice. +-- name: SettleAssessmentPracticeAfterJob :execrows +UPDATE assessment_practices AS practice +SET + status = sqlc.arg(status), + failure_reason = sqlc.narg(failure_reason), + updated_at = greatest(practice.updated_at, clock_timestamp()) +WHERE + practice.status = 'pending' + AND practice.id = ( + SELECT submission.practice_id + FROM assessment_practice_submissions AS submission + WHERE submission.id = sqlc.arg(submission_id) + ) + AND sqlc.arg(submission_id)::uuid = ( + SELECT latest.id + FROM assessment_practice_submissions AS latest + WHERE + latest.practice_id = practice.id + AND latest.mode = 'final' + ORDER BY latest.created_at DESC, latest.id DESC + LIMIT 1 + ); diff --git a/backend/integration_test/assessment_practice_http_test.go b/backend/integration_test/assessment_practice_http_test.go index 7ba3a20..3a0ea43 100644 --- a/backend/integration_test/assessment_practice_http_test.go +++ b/backend/integration_test/assessment_practice_http_test.go @@ -42,6 +42,9 @@ func TestAssessmentPracticeSubmissionStorage(t *testing.T) { }) owner := newPracticeCandidate(ctx, t, harness, "practice-owner", 10) other := newPracticeCandidate(ctx, t, harness, "practice-other", 20) + // firstRun is the debug run that the first case stores; it stays queued, + // as no worker runs here, until a later case gives it a result. + var firstRun uuid.UUID t.Run("debug run is stored with its job and shows no hidden content", func(t *testing.T) { body := practiceRunBody(t, owner.practiceID, "python", practiceSource, []domain.PracticeTest{{Input: "4 5\n", ExpectedOutput: "9\n"}}) @@ -58,6 +61,7 @@ func TestAssessmentPracticeSubmissionStorage(t *testing.T) { } assertPracticeResponseIsPublic(t, created) assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1) + firstRun = run.ID replay := practiceRunRequest(t, harness, owner, body, "run-first") if replay.Code != http.StatusAccepted || decodePracticeRun(t, replay).ID != run.ID { @@ -90,15 +94,9 @@ func TestAssessmentPracticeSubmissionStorage(t *testing.T) { }) t.Run("a stored result is shown without hidden groups", func(t *testing.T) { - body := practiceRunBody(t, owner.practiceID, "go", "package main\nfunc main() {}\n", nil) - created := practiceRunRequest(t, harness, owner, body, "run-with-result") - if created.Code != http.StatusAccepted { - t.Fatalf("create run = %d %s", created.Code, created.Body.String()) - } - run := decodePracticeRun(t, created) // A result that holds a hidden group, which a debug run never gets, // proves that the presentation drops it. - storePracticeResult(t, ctx, harness.pool, run.ID, domain.PracticeRunResult{ + storePracticeResult(t, ctx, harness.pool, firstRun, domain.PracticeRunResult{ Outcome: domain.PracticeOutcomeWrongAnswer, DurationMs: 42, Groups: []domain.PracticeGroupOutcome{ {ID: practice.PublicGroupID, Outcome: domain.PracticeOutcomeWrongAnswer, PassedTests: 1, TotalTests: 2, Tests: []domain.PracticeTestOutcome{ @@ -108,7 +106,7 @@ func TestAssessmentPracticeSubmissionStorage(t *testing.T) { {ID: "hidden-1", Hidden: true, Outcome: domain.PracticeOutcomeAccepted, PassedTests: 1, TotalTests: 1}, }, }) - read := practiceRunRead(t, harness, owner, owner.attemptID, run.ID) + read := practiceRunRead(t, harness, owner, owner.attemptID, firstRun) finished := decodePracticeRun(t, read) if read.Code != http.StatusOK || finished.State != "finished" || finished.Result == nil || len(finished.Result.Tests) != 2 { t.Fatalf("finished run = %d %s", read.Code, read.Body.String()) @@ -196,6 +194,8 @@ type practiceHarness struct { *assessmentAttemptHTTPHarness service *practice.Service passwordHash domain.PasswordHash + // databaseURL names the isolated database of the harness. + databaseURL string } // newPracticeHarness builds the router on an isolated, migrated database with @@ -225,7 +225,9 @@ func newPracticeHarness( if err != nil { t.Fatalf("HashNewPassword() error = %v", err) } - return &practiceHarness{assessmentAttemptHTTPHarness: attemptHarness, service: service, passwordHash: passwordHash} + return &practiceHarness{ + assessmentAttemptHTTPHarness: attemptHarness, service: service, passwordHash: passwordHash, databaseURL: databaseURL, + } } // practiceCandidate is a candidate whose real attempt is at its main practice. diff --git a/backend/integration_test/assessment_practice_queue_test.go b/backend/integration_test/assessment_practice_queue_test.go new file mode 100644 index 0000000..bc971dc --- /dev/null +++ b/backend/integration_test/assessment_practice_queue_test.go @@ -0,0 +1,680 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/practice" + "lincodex/backend/internal/worker/practicequeue" + "lincodex/backend/internal/worker/retry" +) + +const ( + practiceQueueTimeout = 8 * time.Minute + // practiceQueueLease is the lease of the queue tests, on their clock. + practiceQueueLease = 5 * time.Second + // practiceRunsPerMinute is the debug run limit of the tests. + practiceRunsPerMinute = 2 + // fakeRunnerBusyWait is the Retry-After of the fake runner when busy. + fakeRunnerBusyWait = 30 * time.Second +) + +func TestAssessmentPracticeQueue(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), practiceQueueTimeout) + defer cancel() + harness := newPracticeHarness(ctx, t, env, func(parts assessmentHarnessParts) (*practice.Service, error) { + service, err := practice.NewService(parts.transactor, parts.keyring, parts.clock.Now, true) + if err != nil { + return nil, err + } + return service.WithRunRateLimit(env.Redis, outbound.RateLimitRule{Window: time.Minute, Limit: practiceRunsPerMinute}), nil + }) + clock := &practiceQueueClock{} + runner := newFakePracticeRunner() + queue := newPracticeQueueRig(t, harness.pool, runner, clock) + + candidates := make([]practiceCandidate, practice.MaxRunningJobs+practice.MaxQueuedJobs+1) + for index := range candidates { + candidates[index] = newPracticeCandidate(ctx, t, harness, fmt.Sprintf("practice-queue-%02d", index), 30+index) + } + + t.Run("twelve runs at once fill one running and ten queued slots and the last is busy", func(t *testing.T) { + responses := make([]*httptest.ResponseRecorder, len(candidates)) + start := make(chan struct{}) + var wait sync.WaitGroup + for index, candidate := range candidates { + wait.Add(1) + go func() { + defer wait.Done() + <-start + body := practiceRunBody(t, candidate.practiceID, "python", practiceSource, nil) + responses[index] = practiceRunRequest(t, harness, candidate, body, "queue-run") + }() + } + close(start) + wait.Wait() + busy := -1 + for index, response := range responses { + switch response.Code { + case http.StatusAccepted: + case http.StatusServiceUnavailable: + if busy >= 0 { + t.Fatalf("a second run was refused as busy: %s", response.Body.String()) + } + busy = index + requireSessionProblem(t, response, http.StatusServiceUnavailable, "service_unavailable") + if response.Header().Get("Retry-After") != "10" { + t.Fatalf("busy Retry-After = %q, want 10", response.Header().Get("Retry-After")) + } + default: + t.Fatalf("run %d = %d %s", index, response.Code, response.Body.String()) + } + } + if busy < 0 { + t.Fatal("no run was refused as busy") + } + assertPracticeRows(t, ctx, harness.pool, candidates[busy].practiceID, "public", 0) + assertPracticeJobStates(t, ctx, harness.pool, map[string]int{"queued": 11}) + + // One worker holds the only running slot while the runner works; a + // second worker finds nothing it may run. + runner.hold(true) + workerCtx, stopWorker := context.WithCancel(ctx) + workerDone := make(chan struct{}) + go func() { + defer close(workerDone) + queue.worker.Run(workerCtx) + }() + waitForPracticeJobStates(t, ctx, harness.pool, map[string]int{"running": 1, "queued": 10}) + other := queue.newWorker(t) + if _, claimed, err := other.RunOnce(ctx); err != nil || claimed { + t.Fatalf("second worker claimed = %v, error %v; want nothing while one job runs", claimed, err) + } + runner.hold(false) + waitForPracticeJobStates(t, ctx, harness.pool, map[string]int{"finished": 11}) + stopWorker() + <-workerDone + runner.requireOneRunPerSubmission(t, 11) + assertPracticeResultsStored(t, ctx, harness.pool, 11) + }) + + t.Run("a full queue answers a final solution busy and consumes nothing", func(t *testing.T) { + latecomer := candidates[len(candidates)-1] + for _, candidate := range candidates[:len(candidates)-1] { + body := practiceRunBody(t, candidate.practiceID, "python", practiceSource+"# second run\n", nil) + if response := practiceRunRequest(t, harness, candidate, body, "queue-refill"); response.Code != http.StatusAccepted { + t.Fatalf("refill run = %d %s", response.Code, response.Body.String()) + } + } + versionBefore := practiceAttemptVersion(t, ctx, harness.pool, latecomer.attemptID) + command := practice.FinalCommand{ + ActorID: latecomer.userID, AttemptID: domain.AssessmentAttemptID(latecomer.attemptID), PracticeID: latecomer.practiceID, + IdempotencyKey: "final-while-full", Language: languagePointer(domain.TaskLanguagePython), Source: practiceSource, + } + busy, err := harness.service.SubmitFinal(ctx, command) + if err != nil || busy.RetryAfter <= 0 || busy.Practice.Status != domain.AssessmentPracticeFailed || + busy.Practice.FailureReason != domain.AssessmentPracticeSandboxBusy { + t.Fatalf("final solution with a full queue = %+v, error %v; want failed with sandbox_busy", busy, err) + } + assertPracticeRows(t, ctx, harness.pool, latecomer.practiceID, "final", 0) + if version := practiceAttemptVersion(t, ctx, harness.pool, latecomer.attemptID); version != versionBefore { + t.Fatalf("attempt version = %d after a busy refusal, want %d", version, versionBefore) + } + + queue.drain(t, ctx) + command.IdempotencyKey = "final-after-full" + accepted, err := harness.service.SubmitFinal(ctx, command) + if err != nil || accepted.Practice.Status != domain.AssessmentPracticePending { + t.Fatalf("final solution after the queue drained = %+v, error %v", accepted, err) + } + queue.drain(t, ctx) + assertPracticeStatus(t, ctx, harness.pool, latecomer.practiceID, "finished", "") + }) + + t.Run("a busy runner and an infrastructure failure never grade or consume", func(t *testing.T) { + candidate := candidates[0] + submitPracticeFinal(t, ctx, harness, candidate, "final-runner-busy") + runner.answerBusy(1) + if outcome, claimed, err := queue.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeBusy { + t.Fatalf("try on a busy runner = %q claimed %v, error %v; want busy", outcome, claimed, err) + } + job := readPracticeJob(t, ctx, harness.pool, candidate.practiceID) + if job.state != "queued" || job.attempts != 0 || job.generation != 0 { + t.Fatalf("job after a busy runner = %+v, want queued without a counted attempt", job) + } + assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "pending", "") + // The job waits for the time the runner asked for. + if _, claimed, err := queue.worker.RunOnce(ctx); err != nil || claimed { + t.Fatalf("claim before the runner's wait = %v, error %v", claimed, err) + } + clock.advance(fakeRunnerBusyWait + time.Second) + + runner.failInfrastructure(1) + if outcome, _, err := queue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeRetry { + t.Fatalf("try after an infrastructure failure = %q, error %v; want retry", outcome, err) + } + job = readPracticeJob(t, ctx, harness.pool, candidate.practiceID) + if job.state != "queued" || job.attempts != 1 || job.generation != 1 || job.errorClass != "runner_infrastructure_failure" { + t.Fatalf("job after an infrastructure failure = %+v, want queued with a new generation", job) + } + assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "pending", "") + assertNoPracticeResult(t, ctx, harness.pool, candidate.practiceID) + + clock.advance(time.Minute) + if outcome, _, err := queue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeFinished { + t.Fatalf("try after the backoff = %q, error %v; want finished", outcome, err) + } + assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "finished", "") + }) + + t.Run("a worker restarted mid-job recovers it with a single run and result", func(t *testing.T) { + candidate := candidates[1] + submitPracticeFinal(t, ctx, harness, candidate, "final-restart") + runner.hold(true) + defer runner.hold(false) + + crashedPool := newPoolFor(ctx, t, harness.databaseURL) + crashed := queue.workerOn(t, crashedPool) + crashCtx, crash := context.WithCancel(ctx) + crashedDone := make(chan struct{}) + go func() { + defer close(crashedDone) + _, _, _ = crashed.worker.RunOnce(crashCtx) + }() + waitForPracticeJobStates(t, ctx, harness.pool, map[string]int{"running": 1}) + submissionID := latestPracticeSubmission(t, ctx, harness.pool, candidate.practiceID, "final") + runner.waitForRuns(t, ctx, submissionID, 1) + // The process dies: its connections are gone, so it cannot give the + // job back, and the lease keeps the job running. + crashedPool.Close() + crash() + <-crashedDone + stale := crashed.lastClaim() + job := readPracticeJob(t, ctx, harness.pool, candidate.practiceID) + if job.state != "running" || job.leaseOwner != stale.LeaseOwner { + t.Fatalf("job after the crash = %+v, want running under the crashed lease", job) + } + + restarted := queue.newWorker(t) + if _, claimed, err := restarted.RunOnce(ctx); err != nil || claimed { + t.Fatalf("claim during the crashed lease = %v, error %v; want none", claimed, err) + } + clock.advance(practiceQueueLease + time.Second) + runner.hold(false) + if outcome, claimed, err := restarted.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeFinished { + t.Fatalf("restarted worker = %q claimed %v, error %v; want the job finished", outcome, claimed, err) + } + job = readPracticeJob(t, ctx, harness.pool, candidate.practiceID) + if job.state != "finished" || job.attempts != 1 || job.generation != 0 { + t.Fatalf("recovered job = %+v, want finished on the same run key with one counted takeover", job) + } + if runs := runner.runsOf(submissionID); runs != 1 { + t.Fatalf("runner started %d runs for the recovered job, want 1", runs) + } + result := readPracticeResult(t, ctx, harness.pool, candidate.practiceID, "final") + + // The crashed worker coming back late cannot add a second result. + lateStore := postgresadapter.NewPracticeJobStore(newPoolFor(ctx, t, harness.databaseURL)) + held, err := lateStore.Complete(ctx, stale, domain.PracticeRunResult{Outcome: domain.PracticeOutcomeWrongAnswer, Groups: []domain.PracticeGroupOutcome{}}) + if err != nil || held { + t.Fatalf("late completion held = %v, error %v; want refused", held, err) + } + if again := readPracticeResult(t, ctx, harness.pool, candidate.practiceID, "final"); again != result { + t.Fatalf("result changed after a late completion: %s, was %s", again, result) + } + assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "finished", "") + }) + + t.Run("debug runs have a technical rate limit and consume nothing when refused", func(t *testing.T) { + candidate := newPracticeCandidate(ctx, t, harness, "practice-limits", 60) + run := func(key string) *httptest.ResponseRecorder { + body := practiceRunBody(t, candidate.practiceID, "go", "package main\nfunc main() {}\n// "+key+"\n", nil) + return practiceRunRequest(t, harness, candidate, body, key) + } + if response := run("limit-first"); response.Code != http.StatusAccepted { + t.Fatalf("first run = %d %s", response.Code, response.Body.String()) + } + unfinished := run("limit-while-unfinished") + requireSessionProblem(t, unfinished, http.StatusTooManyRequests, "rate_limited") + if unfinished.Header().Get("Retry-After") == "" { + t.Fatal("refused run has no Retry-After") + } + queue.drain(t, ctx) + if response := run("limit-second"); response.Code != http.StatusAccepted { + t.Fatalf("second run = %d %s", response.Code, response.Body.String()) + } + queue.drain(t, ctx) + limited := run("limit-third") + requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited") + if limited.Header().Get("Retry-After") == "" { + t.Fatal("rate-limited run has no Retry-After") + } + assertPracticeRows(t, ctx, harness.pool, candidate.practiceID, "public", 2) + assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "not_started", "") + }) + + assertEverySubmissionHasOneJob(t, ctx, harness.pool) +} + +// practiceQueueRig builds workers on the test clock and the fake runner. +type practiceQueueRig struct { + pool *pgxpool.Pool + runner *fakePracticeRunner + clock *practiceQueueClock + logger *slog.Logger + worker *practicequeue.Worker +} + +func newPracticeQueueRig(t *testing.T, pool *pgxpool.Pool, runner *fakePracticeRunner, clock *practiceQueueClock) *practiceQueueRig { + t.Helper() + rig := &practiceQueueRig{pool: pool, runner: runner, clock: clock, logger: slog.New(slog.DiscardHandler)} + rig.worker = rig.newWorker(t) + return rig +} + +func (rig *practiceQueueRig) newWorker(t *testing.T) *practicequeue.Worker { + t.Helper() + return rig.workerOn(t, rig.pool).worker +} + +// recordedWorker is a worker whose store remembers its last claim, so a test +// can act as that worker after it stopped. +type recordedWorker struct { + worker *practicequeue.Worker + store *recordingPracticeStore +} + +func (worker recordedWorker) lastClaim() outbound.ClaimedPracticeJob { + worker.store.mu.Lock() + defer worker.store.mu.Unlock() + return worker.store.claimed +} + +func (rig *practiceQueueRig) workerOn(t *testing.T, pool *pgxpool.Pool) recordedWorker { + t.Helper() + store := &recordingPracticeStore{PracticeJobStore: postgresadapter.NewPracticeJobStore(pool)} + executor, err := practice.NewExecutor(rig.runner, store, rig.clock.now, practice.ExecutionSettings{ + PollInterval: 20 * time.Millisecond, Lease: practiceQueueLease, RunTimeout: time.Hour, MaxAttempts: 3, + BackoffInitial: 10 * time.Second, BackoffMax: 40 * time.Second, StoreTimeout: 5 * time.Second, + }, rig.logger) + if err != nil { + t.Fatalf("NewExecutor() error = %v", err) + } + worker, err := practicequeue.New(store, executor, rig.logger, practicequeue.Settings{ + PollInterval: 20 * time.Millisecond, Lease: practiceQueueLease, StoreTimeout: 5 * time.Second, + Backoff: retry.Backoff{Initial: 20 * time.Millisecond, Max: 100 * time.Millisecond}, + }, rig.clock.now) + if err != nil { + t.Fatalf("practicequeue.New() error = %v", err) + } + return recordedWorker{worker: worker, store: store} +} + +// drain runs jobs until none is left unfinished, moving the clock past any +// wait. +func (rig *practiceQueueRig) drain(t *testing.T, ctx context.Context) { + t.Helper() + for range 100 { + if _, claimed, err := rig.worker.RunOnce(ctx); err != nil { + t.Fatalf("drain the practice queue: %v", err) + } else if claimed { + continue + } + var active int + if err := rig.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_jobs WHERE state IN ('queued', 'running')`).Scan(&active); err != nil { + t.Fatalf("count unfinished practice jobs: %v", err) + } + if active == 0 { + return + } + rig.clock.advance(time.Minute) + } + t.Fatal("the practice queue did not drain") +} + +type recordingPracticeStore struct { + outbound.PracticeJobStore + mu sync.Mutex + claimed outbound.ClaimedPracticeJob +} + +func (store *recordingPracticeStore) Claim(ctx context.Context, claim outbound.PracticeJobClaim) (outbound.ClaimedPracticeJob, bool, error) { + job, claimed, err := store.PracticeJobStore.Claim(ctx, claim) + if claimed { + store.mu.Lock() + store.claimed = job + store.mu.Unlock() + } + return job, claimed, err +} + +// practiceQueueClock is the application clock of the queue tests: the real +// time moved forward by the test, so jobs stored with the database time are +// due at once. +type practiceQueueClock struct { + mu sync.Mutex + offset time.Duration +} + +func (clock *practiceQueueClock) now() time.Time { + clock.mu.Lock() + defer clock.mu.Unlock() + return time.Now().UTC().Add(clock.offset) +} + +func (clock *practiceQueueClock) advance(by time.Duration) { + clock.mu.Lock() + defer clock.mu.Unlock() + clock.offset += by +} + +// fakePracticeRunner stands in for the code runner. It is idempotent by run +// key like the real one, so a second submit of a key returns the stored run, +// and it counts the runs it started per practice item. +type fakePracticeRunner struct { + mu sync.Mutex + runs map[outbound.CodeRunKey]*fakePracticeRun + // started counts the runs started per submission. + started map[uuid.UUID]int + holding bool + busy int + failures int +} + +type fakePracticeRun struct { + request outbound.CodeRunRequest + finished bool +} + +func newFakePracticeRunner() *fakePracticeRunner { + return &fakePracticeRunner{runs: map[outbound.CodeRunKey]*fakePracticeRun{}, started: map[uuid.UUID]int{}} +} + +func (runner *fakePracticeRunner) Submit(_ context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) { + runner.mu.Lock() + defer runner.mu.Unlock() + if runner.busy > 0 { + runner.busy-- + return outbound.CodeRunStatus{State: outbound.CodeRunBusy, RetryAfter: fakeRunnerBusyWait}, nil + } + if runner.failures > 0 { + runner.failures-- + return outbound.CodeRunStatus{}, fmt.Errorf("fake runner: %w", outbound.ErrCodeRunnerInfrastructureFailure) + } + run, exists := runner.runs[request.Key] + if !exists { + run = &fakePracticeRun{request: request} + runner.runs[request.Key] = run + runner.started[request.Key.SubmissionID]++ + } + return runner.statusLocked(run), nil +} + +func (runner *fakePracticeRunner) Poll(_ context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) { + runner.mu.Lock() + defer runner.mu.Unlock() + run, exists := runner.runs[request.Key] + if !exists { + return outbound.CodeRunStatus{}, outbound.ErrCodeRunNotFound + } + return runner.statusLocked(run), nil +} + +func (runner *fakePracticeRunner) statusLocked(run *fakePracticeRun) outbound.CodeRunStatus { + if runner.holding && !run.finished { + return outbound.CodeRunStatus{State: outbound.CodeRunRunning, RunID: "fake"} + } + run.finished = true + result := outbound.CodeRunResult{Outcome: outbound.CodeOutcomeAccepted, Duration: 10 * time.Millisecond} + for _, group := range run.request.Groups { + groupResult := outbound.CodeGroupResult{ + ID: group.ID, Visibility: group.Visibility, Outcome: outbound.CodeOutcomeAccepted, + PassedTests: len(group.Tests), TotalTests: len(group.Tests), + } + for _, test := range group.Tests { + groupResult.Tests = append(groupResult.Tests, outbound.CodeTestResult{ID: test.ID, Outcome: outbound.CodeOutcomeAccepted, TimeMs: 1, MemoryKB: 512}) + } + result.Groups = append(result.Groups, groupResult) + } + return outbound.CodeRunStatus{State: outbound.CodeRunFinished, RunID: "fake", Result: &result} +} + +// hold keeps new and unfinished runs running until it is turned off. +func (runner *fakePracticeRunner) hold(holding bool) { + runner.mu.Lock() + defer runner.mu.Unlock() + runner.holding = holding +} + +func (runner *fakePracticeRunner) answerBusy(times int) { + runner.mu.Lock() + defer runner.mu.Unlock() + runner.busy = times +} + +func (runner *fakePracticeRunner) failInfrastructure(times int) { + runner.mu.Lock() + defer runner.mu.Unlock() + runner.failures = times +} + +func (runner *fakePracticeRunner) runsOf(submissionID uuid.UUID) int { + runner.mu.Lock() + defer runner.mu.Unlock() + return runner.started[submissionID] +} + +func (runner *fakePracticeRunner) waitForRuns(t *testing.T, ctx context.Context, submissionID uuid.UUID, want int) { + t.Helper() + for ctx.Err() == nil { + if runner.runsOf(submissionID) >= want { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("runner did not start %d runs", want) +} + +// requireOneRunPerSubmission checks that every submission ran exactly once. +func (runner *fakePracticeRunner) requireOneRunPerSubmission(t *testing.T, want int) { + t.Helper() + runner.mu.Lock() + defer runner.mu.Unlock() + submissions := map[uuid.UUID]int{} + for key := range runner.runs { + submissions[key.SubmissionID]++ + } + if len(submissions) != want { + t.Fatalf("runner ran %d submissions, want %d", len(submissions), want) + } + for submission, runs := range submissions { + if runs != 1 { + t.Fatalf("submission %s ran %d times", submission, runs) + } + } +} + +func submitPracticeFinal(t *testing.T, ctx context.Context, harness *practiceHarness, candidate practiceCandidate, key string) { + t.Helper() + result, err := harness.service.SubmitFinal(ctx, practice.FinalCommand{ + ActorID: candidate.userID, AttemptID: domain.AssessmentAttemptID(candidate.attemptID), PracticeID: candidate.practiceID, + IdempotencyKey: key, Language: languagePointer(domain.TaskLanguagePython), Source: practiceSource, + }) + if err != nil || result.Practice.Status != domain.AssessmentPracticePending { + t.Fatalf("final submission = %+v, error %v", result, err) + } +} + +func latestPracticeSubmission(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, mode string) uuid.UUID { + t.Helper() + var id uuid.UUID + if err := pool.QueryRow(ctx, `SELECT id FROM assessment_practice_submissions + WHERE practice_id = $1 AND mode = $2 ORDER BY created_at DESC LIMIT 1`, practiceID, mode).Scan(&id); err != nil { + t.Fatalf("read latest practice submission: %v", err) + } + return id +} + +type practiceJobRow struct { + state string + attempts int + generation int + errorClass string + leaseOwner uuid.UUID +} + +// readPracticeJob reads the job of the latest final submission of a practice. +func readPracticeJob(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID) practiceJobRow { + t.Helper() + var job practiceJobRow + var owner *uuid.UUID + var class *string + if err := pool.QueryRow(ctx, `SELECT job.state, job.attempts, job.generation, job.last_error_class, job.lease_owner + FROM assessment_practice_jobs AS job + JOIN assessment_practice_submissions AS submission ON submission.id = job.submission_id + WHERE submission.practice_id = $1 AND submission.mode = 'final' + ORDER BY submission.created_at DESC LIMIT 1`, practiceID).Scan(&job.state, &job.attempts, &job.generation, &class, &owner); err != nil { + t.Fatalf("read practice job: %v", err) + } + if owner != nil { + job.leaseOwner = *owner + } + if class != nil { + job.errorClass = *class + } + return job +} + +func readPracticeResult(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, mode string) string { + t.Helper() + var result []byte + if err := pool.QueryRow(ctx, `SELECT result FROM assessment_practice_submissions + WHERE practice_id = $1 AND mode = $2 ORDER BY created_at DESC LIMIT 1`, practiceID, mode).Scan(&result); err != nil || len(result) == 0 { + t.Fatalf("read practice result: %v (%d bytes)", err, len(result)) + } + var decoded domain.PracticeRunResult + if err := json.Unmarshal(result, &decoded); err != nil || decoded.Outcome != domain.PracticeOutcomeAccepted { + t.Fatalf("stored result %s, decode error %v", result, err) + } + return string(result) +} + +// assertNoPracticeResult checks that no final submission of the practice has +// a result. +func assertNoPracticeResult(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID) { + t.Helper() + var stored int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_submissions + WHERE practice_id = $1 AND mode = 'final' AND result IS NOT NULL`, practiceID).Scan(&stored); err != nil { + t.Fatalf("count practice results: %v", err) + } + if stored != 0 { + t.Fatalf("%d practice results stored, want none", stored) + } +} + +func assertPracticeResultsStored(t *testing.T, ctx context.Context, pool *pgxpool.Pool, want int) { + t.Helper() + var stored int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_submissions WHERE result IS NOT NULL`).Scan(&stored); err != nil { + t.Fatalf("count practice results: %v", err) + } + if stored != want { + t.Fatalf("%d practice results stored, want %d", stored, want) + } +} + +func assertPracticeStatus(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, status, reason string) { + t.Helper() + var gotStatus string + var gotReason *string + if err := pool.QueryRow(ctx, `SELECT status, failure_reason FROM assessment_practices WHERE id = $1`, practiceID).Scan(&gotStatus, &gotReason); err != nil { + t.Fatalf("read practice status: %v", err) + } + if gotStatus != status || (gotReason != nil) != (reason != "") || (gotReason != nil && *gotReason != reason) { + t.Fatalf("practice status = %s %v, want %s %q", gotStatus, gotReason, status, reason) + } +} + +func practiceAttemptVersion(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) int64 { + t.Helper() + var version int64 + if err := pool.QueryRow(ctx, `SELECT version FROM assessment_attempts WHERE id = $1`, attemptID).Scan(&version); err != nil { + t.Fatalf("read attempt version: %v", err) + } + return version +} + +func practiceJobStates(t *testing.T, ctx context.Context, pool *pgxpool.Pool) map[string]int { + t.Helper() + rows, err := pool.Query(ctx, `SELECT state, count(*) FROM assessment_practice_jobs GROUP BY state`) + if err != nil { + t.Fatalf("count practice jobs: %v", err) + } + defer rows.Close() + states := map[string]int{} + for rows.Next() { + var state string + var count int + if err := rows.Scan(&state, &count); err != nil { + t.Fatalf("scan practice job count: %v", err) + } + states[state] = count + } + if err := rows.Err(); err != nil { + t.Fatalf("read practice job counts: %v", err) + } + return states +} + +func assertPracticeJobStates(t *testing.T, ctx context.Context, pool *pgxpool.Pool, want map[string]int) { + t.Helper() + if got := practiceJobStates(t, ctx, pool); !sameJobStates(got, want) { + t.Fatalf("practice jobs = %v, want %v", got, want) + } +} + +func waitForPracticeJobStates(t *testing.T, ctx context.Context, pool *pgxpool.Pool, want map[string]int) { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for { + got := practiceJobStates(t, ctx, pool) + if sameJobStates(got, want) { + return + } + if time.Now().After(deadline) || ctx.Err() != nil { + t.Fatalf("practice jobs = %v, want %v", got, want) + } + time.Sleep(20 * time.Millisecond) + } +} + +// sameJobStates compares the counts of the states in want; finished jobs of +// earlier cases are ignored unless want names them. +func sameJobStates(got, want map[string]int) bool { + for _, state := range []string{"queued", "running", "failed"} { + if got[state] != want[state] { + return false + } + } + if finished, named := want["finished"]; named && got["finished"] != finished { + return false + } + return true +} diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index 19e7916..7806dd8 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -1499,19 +1499,22 @@ func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEsca // `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the // server answers 409 state_conflict. // -// Availability. When code practice is not enabled on this server, the server answers 503 -// service_unavailable and stores nothing. +// Limits. Debug runs are bounded by a per-candidate rate limit and by one unfinished run per practice; +// either answers 429 rate_limited with Retry-After. The sandbox queue holds one running and ten +// waiting runs and submissions together; when it is full the server answers 503 service_unavailable +// with Retry-After and stores nothing. When code practice is not enabled on this server, the server +// answers 503 service_unavailable without Retry-After and stores nothing. // // Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in // its current state with 202, without starting another run. A different body with the same key answers -// 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are +// 422 idempotency_key_reused. Refusals (400, 404, 409, 429, 503) are not stored under the key and are // evaluated again. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, // replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of -// another candidate), the state (409), then the solution against the item (400 with a pointer such as -// `/language` or `/source_code`). +// another candidate), the state (409), the solution against the item (400 with a pointer such as +// `/language` or `/source_code`), the limits (429), then the queue (503). // // POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs func (s *Server) handleCreateMyAssessmentPracticeRunRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index dd9c097..9bd2997 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -778,6 +778,38 @@ func encodeCreateMyAssessmentPracticeRunResponse(response CreateMyAssessmentPrac return nil + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + case *ServiceUnavailableHeaders: w.Header().Set("Content-Type", "application/problem+json") w.Header().Set("Access-Control-Expose-Headers", "Retry-After") diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index 5af0d7b..6d0d032 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -32842,6 +32842,7 @@ func (*TooManyRequestsHeaders) cancelMyInvitationRes() {} func (*TooManyRequestsHeaders) confirmEmailByCodeRes() {} func (*TooManyRequestsHeaders) confirmEmailRes() {} func (*TooManyRequestsHeaders) createMyAssessmentAttemptRes() {} +func (*TooManyRequestsHeaders) createMyAssessmentPracticeRunRes() {} func (*TooManyRequestsHeaders) createMySupportCaseRes() {} func (*TooManyRequestsHeaders) createOrganizationInvitationRes() {} func (*TooManyRequestsHeaders) createOrganizationNeedRes() {} diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index f592bb0..79f87c1 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -247,19 +247,22 @@ type Handler interface { // `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the // server answers 409 state_conflict. // - // Availability. When code practice is not enabled on this server, the server answers 503 - // service_unavailable and stores nothing. + // Limits. Debug runs are bounded by a per-candidate rate limit and by one unfinished run per practice; + // either answers 429 rate_limited with Retry-After. The sandbox queue holds one running and ten + // waiting runs and submissions together; when it is full the server answers 503 service_unavailable + // with Retry-After and stores nothing. When code practice is not enabled on this server, the server + // answers 503 service_unavailable without Retry-After and stores nothing. // // Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in // its current state with 202, without starting another run. A different body with the same key answers - // 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are + // 422 idempotency_key_reused. Refusals (400, 404, 409, 429, 503) are not stored under the key and are // evaluated again. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, // replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of - // another candidate), the state (409), then the solution against the item (400 with a pointer such as - // `/language` or `/source_code`). + // another candidate), the state (409), the solution against the item (400 with a pointer such as + // `/language` or `/source_code`), the limits (429), then the queue (503). // // POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs CreateMyAssessmentPracticeRun(ctx context.Context, req *PracticeRunCreate, params CreateMyAssessmentPracticeRunParams) (CreateMyAssessmentPracticeRunRes, error) diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index d7e46c8..bb33017 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -270,19 +270,22 @@ func (UnimplementedHandler) CreateMyAssessmentAttempt(ctx context.Context, req A // `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the // server answers 409 state_conflict. // -// Availability. When code practice is not enabled on this server, the server answers 503 -// service_unavailable and stores nothing. +// Limits. Debug runs are bounded by a per-candidate rate limit and by one unfinished run per practice; +// either answers 429 rate_limited with Retry-After. The sandbox queue holds one running and ten +// waiting runs and submissions together; when it is full the server answers 503 service_unavailable +// with Retry-After and stores nothing. When code practice is not enabled on this server, the server +// answers 503 service_unavailable without Retry-After and stores nothing. // // Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in // its current state with 202, without starting another run. A different body with the same key answers -// 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are +// 422 idempotency_key_reused. Refusals (400, 404, 409, 429, 503) are not stored under the key and are // evaluated again. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, // replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of -// another candidate), the state (409), then the solution against the item (400 with a pointer such as -// `/language` or `/source_code`). +// another candidate), the state (409), the solution against the item (400 with a pointer such as +// `/language` or `/source_code`), the limits (429), then the queue (503). // // POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs func (UnimplementedHandler) CreateMyAssessmentPracticeRun(ctx context.Context, req *PracticeRunCreate, params CreateMyAssessmentPracticeRunParams) (r CreateMyAssessmentPracticeRunRes, _ error) { diff --git a/backend/internal/adapter/primary/http/v1/practice.go b/backend/internal/adapter/primary/http/v1/practice.go index 50be5ef..67ed7c7 100644 --- a/backend/internal/adapter/primary/http/v1/practice.go +++ b/backend/internal/adapter/primary/http/v1/practice.go @@ -115,7 +115,15 @@ func (handler *PracticeHandler) GetMyAssessmentPracticeRun( func practiceRunFailure(ctx context.Context, err error) (api.CreateMyAssessmentPracticeRunRes, error) { var fieldError *practice.FieldError + var retryError *practice.RetryError switch { + case errors.As(err, &retryError) && errors.Is(err, practice.ErrRateLimited): + return problem.RateLimited(ctx, wholeSeconds(retryError.RetryAfter)), nil + case errors.As(err, &retryError) && errors.Is(err, practice.ErrQueueBusy): + busy := problem.New(ctx, api.ProblemCodeServiceUnavailable) + return &api.ServiceUnavailableHeaders{ + RetryAfter: api.NewOptInt32(max(wholeSeconds(retryError.RetryAfter), 1)), Response: busy.Response, + }, nil case errors.As(err, &fieldError): return (*api.CreateMyAssessmentPracticeRunBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "/"+fieldError.Field).Response), nil case errors.Is(err, practice.ErrInvalidKey): diff --git a/backend/internal/adapter/secondary/postgres/assessment_practice.go b/backend/internal/adapter/secondary/postgres/assessment_practice.go index f4a9ccf..7d66707 100644 --- a/backend/internal/adapter/secondary/postgres/assessment_practice.go +++ b/backend/internal/adapter/secondary/postgres/assessment_practice.go @@ -162,6 +162,26 @@ func (repository assessmentPracticeRepository) LatestFinal(ctx context.Context, return solution, true, nil } +func (repository assessmentPracticeRepository) LockQueue(ctx context.Context) (int, error) { + const location = "assessmentPracticeRepository.LockQueue" + if err := repository.queries.LockAssessmentPracticeQueue(ctx); err != nil { + return 0, fmt.Errorf("%s - lock queue: %w", location, mapAssessmentError(err)) + } + active, err := repository.queries.CountActiveAssessmentPracticeJobs(ctx) + if err != nil { + return 0, fmt.Errorf("%s - count unfinished jobs: %w", location, mapAssessmentError(err)) + } + return int(active), nil +} + +func (repository assessmentPracticeRepository) ActiveRuns(ctx context.Context, practiceID uuid.UUID) (int, error) { + active, err := repository.queries.CountActiveAssessmentPracticeRuns(ctx, pgUUID(practiceID)) + if err != nil { + return 0, fmt.Errorf("assessmentPracticeRepository.ActiveRuns - count unfinished runs: %w", mapAssessmentError(err)) + } + return int(active), nil +} + func (repository assessmentPracticeRepository) Submit( ctx context.Context, submission domain.PracticeSubmission, diff --git a/backend/internal/adapter/secondary/postgres/assessment_practice_queue.go b/backend/internal/adapter/secondary/postgres/assessment_practice_queue.go new file mode 100644 index 0000000..fff2bb9 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/assessment_practice_queue.go @@ -0,0 +1,296 @@ +package postgres + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "math" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// Job states the worker side of the practice queue writes. +const ( + practiceJobFinished = "finished" + practiceJobFailed = "failed" +) + +// PracticeJobStore implements outbound.PracticeJobStore with a pgx pool owned +// by the caller. Every method is one short transaction or statement, so no +// transaction stays open while the runner works. +type PracticeJobStore struct { + pool *pgxpool.Pool +} + +var _ outbound.PracticeJobStore = (*PracticeJobStore)(nil) + +func NewPracticeJobStore(pool *pgxpool.Pool) *PracticeJobStore { + return &PracticeJobStore{pool: pool} +} + +func (store *PracticeJobStore) Claim(ctx context.Context, claim outbound.PracticeJobClaim) (outbound.ClaimedPracticeJob, bool, error) { + const location = "PracticeJobStore.Claim" + if claim.Owner == uuid.Nil || claim.Now.IsZero() || claim.Lease <= 0 || claim.MaxRunning < 1 { + return outbound.ClaimedPracticeJob{}, false, errors.New(location + " - owner, now, lease, and running limit must be set") + } + expiresAt := claim.Now.Add(claim.Lease) + var job outbound.ClaimedPracticeJob + claimed := false + err := store.inTransaction(ctx, func(queries *sqlc.Queries) error { + if err := queries.LockAssessmentPracticeQueue(ctx); err != nil { + return fmt.Errorf("lock queue: %w", err) + } + running, err := queries.CountLiveRunningAssessmentPracticeJobs(ctx, timestamp(claim.Now)) + if err != nil { + return fmt.Errorf("count running jobs: %w", err) + } + if int(running) >= claim.MaxRunning { + return nil + } + row, err := queries.ClaimAssessmentPracticeJob(ctx, sqlc.ClaimAssessmentPracticeJobParams{ + LeaseOwner: pgUUID(claim.Owner), LeaseExpiresAt: timestamp(expiresAt), Now: timestamp(claim.Now), + }) + if errors.Is(err, pgx.ErrNoRows) { + return nil + } + if err != nil { + return fmt.Errorf("claim job: %w", err) + } + mode := domain.PracticeSubmissionMode(row.Mode) + if !row.SubmissionID.Valid || !mode.IsKnown() || row.Generation < 0 || row.Attempts < 0 { + return fmt.Errorf("claimed job is incomplete: %w", domain.ErrInvalidAssessmentPractice) + } + job = outbound.ClaimedPracticeJob{ + SubmissionID: row.SubmissionID.Bytes, Mode: mode, Generation: uint32(row.Generation), Attempts: int(row.Attempts), + LeaseOwner: claim.Owner, LeaseExpiresAt: expiresAt, StartedAt: claim.Now, Reclaimed: row.Reclaimed, + } + claimed = true + return nil + }) + if err != nil { + return outbound.ClaimedPracticeJob{}, false, fmt.Errorf("%s - %w", location, err) + } + return job, claimed, nil +} + +func (store *PracticeJobStore) Work(ctx context.Context, job outbound.ClaimedPracticeJob) (outbound.PracticeJobWork, error) { + const location = "PracticeJobStore.Work" + row, err := sqlc.New(store.pool).GetAssessmentPracticeJobWork(ctx, pgUUID(job.SubmissionID)) + if err != nil { + return outbound.PracticeJobWork{}, fmt.Errorf("%s - read submission: %w", location, sanitizedDatabaseError(err)) + } + var task domain.PracticeTask + if err := json.Unmarshal(row.Task, &task); err != nil { + return outbound.PracticeJobWork{}, fmt.Errorf("%s - decode task: %w", location, domain.ErrInvalidAssessmentPractice) + } + submission := domain.PracticeSubmission{ + ID: row.ID.Bytes, PracticeID: row.PracticeID.Bytes, UserID: row.UserID.Bytes, + Mode: domain.PracticeSubmissionMode(row.Mode), Language: domain.TaskLanguageCode(row.Language), + Source: row.Source, CreatedAt: row.CreatedAt.Time.UTC(), + } + if len(row.CustomTests) > 0 { + if err := json.Unmarshal(row.CustomTests, &submission.CustomTests); err != nil { + return outbound.PracticeJobWork{}, fmt.Errorf("%s - decode custom tests: %w", location, domain.ErrInvalidAssessmentPractice) + } + } + if err := task.Validate(); err != nil { + return outbound.PracticeJobWork{}, fmt.Errorf("%s - validate task: %w", location, err) + } + if err := submission.Validate(task); err != nil { + return outbound.PracticeJobWork{}, fmt.Errorf("%s - validate submission: %w", location, err) + } + return outbound.PracticeJobWork{Submission: submission, Task: task}, nil +} + +func (store *PracticeJobStore) Extend( + ctx context.Context, + job outbound.ClaimedPracticeJob, + expiresAt time.Time, +) (outbound.ClaimedPracticeJob, bool, error) { + const location = "PracticeJobStore.Extend" + if expiresAt.IsZero() { + return outbound.ClaimedPracticeJob{}, false, errors.New(location + " - expiry must be set") + } + renewed, err := sqlc.New(store.pool).ExtendAssessmentPracticeJobLease(ctx, sqlc.ExtendAssessmentPracticeJobLeaseParams{ + LeaseExpiresAt: timestamp(expiresAt), SubmissionID: pgUUID(job.SubmissionID), + LeaseOwner: pgUUID(job.LeaseOwner), StartedAt: timestamp(job.StartedAt), + }) + if err != nil { + return outbound.ClaimedPracticeJob{}, false, fmt.Errorf("%s - renew lease: %w", location, sanitizedDatabaseError(err)) + } + if renewed != 1 { + return outbound.ClaimedPracticeJob{}, false, nil + } + job.LeaseExpiresAt = expiresAt + return job, true, nil +} + +func (store *PracticeJobStore) Requeue(ctx context.Context, job outbound.ClaimedPracticeJob, requeue outbound.PracticeRequeue) (bool, error) { + const location = "PracticeJobStore.Requeue" + if requeue.AvailableAt.IsZero() || requeue.Generation > math.MaxInt32 { + return false, errors.New(location + " - availability must be set and the generation in range") + } + counted := int32(0) + if requeue.Counted { + counted = 1 + } + updated, err := sqlc.New(store.pool).RequeueAssessmentPracticeJob(ctx, sqlc.RequeueAssessmentPracticeJobParams{ + AvailableAt: timestamp(requeue.AvailableAt), Generation: int32(requeue.Generation), Counted: counted, + ErrorClass: pgOptionalText(string(requeue.ErrorClass)), SubmissionID: pgUUID(job.SubmissionID), + LeaseOwner: pgUUID(job.LeaseOwner), StartedAt: timestamp(job.StartedAt), + }) + if err != nil { + return false, fmt.Errorf("%s - requeue job: %w", location, sanitizedDatabaseError(err)) + } + return updated == 1, nil +} + +func (store *PracticeJobStore) Complete(ctx context.Context, job outbound.ClaimedPracticeJob, result domain.PracticeRunResult) (bool, error) { + const location = "PracticeJobStore.Complete" + if err := result.Validate(); err != nil { + return false, fmt.Errorf("%s - validate result: %w", location, err) + } + encoded, err := json.Marshal(result) + if err != nil { + return false, fmt.Errorf("%s - encode result: %w", location, domain.ErrInvalidAssessmentPractice) + } + held := false + err = store.inTransaction(ctx, func(queries *sqlc.Queries) error { + mode, locked, err := lockClaimedPracticeJob(ctx, queries, job) + if err != nil || !locked { + return err + } + stored, err := queries.StoreAssessmentPracticeResult(ctx, sqlc.StoreAssessmentPracticeResultParams{ + Result: encoded, ID: pgUUID(job.SubmissionID), + }) + if err != nil { + return fmt.Errorf("store result: %w", err) + } + if stored != 1 { + return outbound.ErrPracticeResultExists + } + if err := finishPracticeJob(ctx, queries, job, practiceJobFinished, ""); err != nil { + return err + } + if mode == domain.PracticeModeFinal { + if err := settlePractice(ctx, queries, job, domain.AssessmentPracticeFinished, ""); err != nil { + return err + } + } + held = true + return nil + }) + if err != nil { + return false, fmt.Errorf("%s - %w", location, err) + } + return held, nil +} + +func (store *PracticeJobStore) Fail(ctx context.Context, job outbound.ClaimedPracticeJob, class outbound.PracticeJobErrorClass) (bool, error) { + const location = "PracticeJobStore.Fail" + if class == "" { + return false, errors.New(location + " - error class must be set") + } + held := false + err := store.inTransaction(ctx, func(queries *sqlc.Queries) error { + mode, locked, err := lockClaimedPracticeJob(ctx, queries, job) + if err != nil || !locked { + return err + } + if err := finishPracticeJob(ctx, queries, job, practiceJobFailed, class); err != nil { + return err + } + if mode == domain.PracticeModeFinal { + if err := settlePractice(ctx, queries, job, domain.AssessmentPracticeFailed, domain.AssessmentPracticeSandboxError); err != nil { + return err + } + } + held = true + return nil + }) + if err != nil { + return false, fmt.Errorf("%s - %w", location, err) + } + return held, nil +} + +// lockClaimedPracticeJob locks the job of a try and reports whether the try +// still holds it. +func lockClaimedPracticeJob( + ctx context.Context, + queries *sqlc.Queries, + job outbound.ClaimedPracticeJob, +) (domain.PracticeSubmissionMode, bool, error) { + mode, err := queries.LockClaimedAssessmentPracticeJob(ctx, sqlc.LockClaimedAssessmentPracticeJobParams{ + SubmissionID: pgUUID(job.SubmissionID), LeaseOwner: pgUUID(job.LeaseOwner), StartedAt: timestamp(job.StartedAt), + }) + if errors.Is(err, pgx.ErrNoRows) { + return "", false, nil + } + if err != nil { + return "", false, fmt.Errorf("lock job: %w", err) + } + return domain.PracticeSubmissionMode(mode), true, nil +} + +func finishPracticeJob( + ctx context.Context, + queries *sqlc.Queries, + job outbound.ClaimedPracticeJob, + state string, + class outbound.PracticeJobErrorClass, +) error { + finished, err := queries.FinishAssessmentPracticeJob(ctx, sqlc.FinishAssessmentPracticeJobParams{ + State: state, ErrorClass: pgOptionalText(string(class)), SubmissionID: pgUUID(job.SubmissionID), + LeaseOwner: pgUUID(job.LeaseOwner), StartedAt: timestamp(job.StartedAt), + }) + if err != nil { + return fmt.Errorf("finish job: %w", err) + } + if finished != 1 { + return errors.New("finish job: the locked job changed") + } + return nil +} + +// settlePractice moves the practice of a final submission out of pending. It +// changes nothing when a later final submission replaced this one. +func settlePractice( + ctx context.Context, + queries *sqlc.Queries, + job outbound.ClaimedPracticeJob, + status domain.AssessmentPracticeStatus, + reason domain.AssessmentPracticeFailureReason, +) error { + if _, err := queries.SettleAssessmentPracticeAfterJob(ctx, sqlc.SettleAssessmentPracticeAfterJobParams{ + Status: string(status), FailureReason: pgOptionalText(string(reason)), SubmissionID: pgUUID(job.SubmissionID), + }); err != nil { + return fmt.Errorf("settle practice: %w", err) + } + return nil +} + +// inTransaction runs fn in one READ COMMITTED transaction and keeps only the +// SQLSTATE of a database error, whose text could quote submitted code. +func (store *PracticeJobStore) inTransaction(ctx context.Context, fn func(queries *sqlc.Queries) error) error { + tx, err := store.pool.BeginTx(ctx, transactionOptions) + if err != nil { + return fmt.Errorf("begin transaction: %w", sanitizeConnectError(err)) + } + if err := fn(sqlc.New(tx)); err != nil { + rollbackErr := rollback(ctx, tx) + return errors.Join(sanitizedDatabaseError(err), rollbackErr) + } + if err := tx.Commit(ctx); err != nil { + return fmt.Errorf("commit transaction: %w", sanitizedDatabaseError(err)) + } + return nil +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice.sql.go index bf6399f..51d2ac6 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice.sql.go @@ -172,6 +172,7 @@ INSERT INTO assessment_practice_jobs ( submission_id, mode, state, + available_at, created_at, updated_at ) VALUES ( @@ -179,6 +180,7 @@ INSERT INTO assessment_practice_jobs ( $2, 'queued', $3, + $3, $3 ) ` @@ -190,7 +192,7 @@ type InsertAssessmentPracticeJobParams struct { } // Queues the execution job of a submission in the transaction that stores -// the submission. +// the submission. The job is available at once. func (q *Queries) InsertAssessmentPracticeJob(ctx context.Context, arg InsertAssessmentPracticeJobParams) error { _, err := q.db.Exec(ctx, insertAssessmentPracticeJob, arg.SubmissionID, arg.Mode, arg.CreatedAt) return err diff --git a/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice_queue.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice_queue.sql.go new file mode 100644 index 0000000..c70981c --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice_queue.sql.go @@ -0,0 +1,407 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: assessment_practice_queue.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const claimAssessmentPracticeJob = `-- name: ClaimAssessmentPracticeJob :one +WITH candidate AS ( + SELECT + job.submission_id, + job.state = 'running' AS reclaimed + FROM assessment_practice_jobs AS job + WHERE + (job.state = 'queued' AND job.available_at <= $3::timestamptz) + OR (job.state = 'running' AND job.lease_expires_at <= $3::timestamptz) + ORDER BY + job.state = 'running' DESC, + job.mode = 'final' DESC, + job.available_at ASC, + job.created_at ASC, + job.submission_id ASC + LIMIT 1 + FOR UPDATE SKIP LOCKED +) + +UPDATE assessment_practice_jobs AS job +SET + state = 'running', + lease_owner = $1, + lease_expires_at = $2, + started_at = $3::timestamptz, + attempts = job.attempts + CASE WHEN candidate.reclaimed THEN 1 ELSE 0 END, + last_error_class = CASE + WHEN candidate.reclaimed THEN 'lease_expired' ELSE job.last_error_class + END, + updated_at = greatest(job.updated_at, clock_timestamp()) +FROM candidate +WHERE job.submission_id = candidate.submission_id +RETURNING + job.submission_id, + job.mode, + job.generation, + job.attempts, + candidate.reclaimed +` + +type ClaimAssessmentPracticeJobParams struct { + LeaseOwner pgtype.UUID + LeaseExpiresAt pgtype.Timestamptz + Now pgtype.Timestamptz +} + +type ClaimAssessmentPracticeJobRow struct { + SubmissionID pgtype.UUID + Mode string + Generation int32 + Attempts int32 + Reclaimed bool +} + +// Claims one job under the queue lock: first a running job whose lease +// expired (its worker stopped without finishing it), then the next queued +// job, final submissions before debug runs. A takeover keeps the generation, +// so the runner returns the run it already has, and counts one attempt. +func (q *Queries) ClaimAssessmentPracticeJob(ctx context.Context, arg ClaimAssessmentPracticeJobParams) (ClaimAssessmentPracticeJobRow, error) { + row := q.db.QueryRow(ctx, claimAssessmentPracticeJob, arg.LeaseOwner, arg.LeaseExpiresAt, arg.Now) + var i ClaimAssessmentPracticeJobRow + err := row.Scan( + &i.SubmissionID, + &i.Mode, + &i.Generation, + &i.Attempts, + &i.Reclaimed, + ) + return i, err +} + +const countActiveAssessmentPracticeJobs = `-- name: CountActiveAssessmentPracticeJobs :one +SELECT count(*)::integer AS active +FROM assessment_practice_jobs AS job +WHERE job.state IN ('queued', 'running') +` + +// Counts the queued and running jobs; the caller holds the queue lock. +func (q *Queries) CountActiveAssessmentPracticeJobs(ctx context.Context) (int32, error) { + row := q.db.QueryRow(ctx, countActiveAssessmentPracticeJobs) + var active int32 + err := row.Scan(&active) + return active, err +} + +const countActiveAssessmentPracticeRuns = `-- name: CountActiveAssessmentPracticeRuns :one +SELECT count(*)::integer AS active +FROM assessment_practice_jobs AS job +INNER JOIN assessment_practice_submissions AS submission ON job.submission_id = submission.id +WHERE + submission.practice_id = $1 + AND job.mode = 'public' + AND job.state IN ('queued', 'running') +` + +// Counts the unfinished debug runs of a practice; the caller holds the +// practice row lock. +func (q *Queries) CountActiveAssessmentPracticeRuns(ctx context.Context, practiceID pgtype.UUID) (int32, error) { + row := q.db.QueryRow(ctx, countActiveAssessmentPracticeRuns, practiceID) + var active int32 + err := row.Scan(&active) + return active, err +} + +const countLiveRunningAssessmentPracticeJobs = `-- name: CountLiveRunningAssessmentPracticeJobs :one +SELECT count(*)::integer AS running +FROM assessment_practice_jobs AS job +WHERE + job.state = 'running' + AND job.lease_expires_at > $1::timestamptz +` + +// Counts running jobs whose lease has not expired by now, the application +// clock; the caller holds the queue lock. +func (q *Queries) CountLiveRunningAssessmentPracticeJobs(ctx context.Context, now pgtype.Timestamptz) (int32, error) { + row := q.db.QueryRow(ctx, countLiveRunningAssessmentPracticeJobs, now) + var running int32 + err := row.Scan(&running) + return running, err +} + +const extendAssessmentPracticeJobLease = `-- name: ExtendAssessmentPracticeJobLease :execrows +UPDATE assessment_practice_jobs +SET + lease_expires_at = $1, + updated_at = greatest(updated_at, clock_timestamp()) +WHERE + submission_id = $2 + AND state = 'running' + AND lease_owner = $3 + AND started_at = $4 +` + +type ExtendAssessmentPracticeJobLeaseParams struct { + LeaseExpiresAt pgtype.Timestamptz + SubmissionID pgtype.UUID + LeaseOwner pgtype.UUID + StartedAt pgtype.Timestamptz +} + +// Renews the lease of a running try. The owner and the start time identify +// the try, so a worker whose job was taken over changes nothing. +func (q *Queries) ExtendAssessmentPracticeJobLease(ctx context.Context, arg ExtendAssessmentPracticeJobLeaseParams) (int64, error) { + result, err := q.db.Exec(ctx, extendAssessmentPracticeJobLease, + arg.LeaseExpiresAt, + arg.SubmissionID, + arg.LeaseOwner, + arg.StartedAt, + ) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const finishAssessmentPracticeJob = `-- name: FinishAssessmentPracticeJob :execrows +UPDATE assessment_practice_jobs +SET + state = $1, + finished_at = greatest(created_at, clock_timestamp()), + last_error_class = coalesce($2, last_error_class), + lease_owner = NULL, + lease_expires_at = NULL, + started_at = NULL, + updated_at = greatest(updated_at, clock_timestamp()) +WHERE + submission_id = $3 + AND state = 'running' + AND lease_owner = $4 + AND started_at = $5 +` + +type FinishAssessmentPracticeJobParams struct { + State string + ErrorClass pgtype.Text + SubmissionID pgtype.UUID + LeaseOwner pgtype.UUID + StartedAt pgtype.Timestamptz +} + +// Ends a running try as finished or failed. +func (q *Queries) FinishAssessmentPracticeJob(ctx context.Context, arg FinishAssessmentPracticeJobParams) (int64, error) { + result, err := q.db.Exec(ctx, finishAssessmentPracticeJob, + arg.State, + arg.ErrorClass, + arg.SubmissionID, + arg.LeaseOwner, + arg.StartedAt, + ) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getAssessmentPracticeJobWork = `-- name: GetAssessmentPracticeJobWork :one +SELECT + submission.id, + submission.practice_id, + submission.user_id, + submission.mode, + submission.language, + submission.source, + submission.custom_tests, + submission.created_at, + practice.task +FROM assessment_practice_submissions AS submission +INNER JOIN assessment_practices AS practice ON submission.practice_id = practice.id +WHERE submission.id = $1 +` + +type GetAssessmentPracticeJobWorkRow struct { + ID pgtype.UUID + PracticeID pgtype.UUID + UserID pgtype.UUID + Mode string + Language string + Source string + CustomTests []byte + CreatedAt pgtype.Timestamptz + Task []byte +} + +// Reads what a claimed job runs: the submission and the task of its +// practice. +func (q *Queries) GetAssessmentPracticeJobWork(ctx context.Context, submissionID pgtype.UUID) (GetAssessmentPracticeJobWorkRow, error) { + row := q.db.QueryRow(ctx, getAssessmentPracticeJobWork, submissionID) + var i GetAssessmentPracticeJobWorkRow + err := row.Scan( + &i.ID, + &i.PracticeID, + &i.UserID, + &i.Mode, + &i.Language, + &i.Source, + &i.CustomTests, + &i.CreatedAt, + &i.Task, + ) + return i, err +} + +const lockAssessmentPracticeQueue = `-- name: LockAssessmentPracticeQueue :exec + +SELECT pg_advisory_xact_lock(hashtextextended('lincodex.assessment.practice_queue', 0)) +` + +// The practice queue. Admission and the claim take the same +// transaction-scoped advisory lock, so the count of unfinished jobs and the +// change that depends on it are atomic across backend instances. A command +// takes the lock after its attempt and practice row locks; the claim takes +// it first and then skips job rows that another transaction locks, so a +// claim never waits for a row lock while it holds the queue lock. +func (q *Queries) LockAssessmentPracticeQueue(ctx context.Context) error { + _, err := q.db.Exec(ctx, lockAssessmentPracticeQueue) + return err +} + +const lockClaimedAssessmentPracticeJob = `-- name: LockClaimedAssessmentPracticeJob :one +SELECT job.mode +FROM assessment_practice_jobs AS job +WHERE + job.submission_id = $1 + AND job.state = 'running' + AND job.lease_owner = $2 + AND job.started_at = $3 +FOR UPDATE +` + +type LockClaimedAssessmentPracticeJobParams struct { + SubmissionID pgtype.UUID + LeaseOwner pgtype.UUID + StartedAt pgtype.Timestamptz +} + +// Locks a running try for its completion and checks that it still belongs +// to the worker. +func (q *Queries) LockClaimedAssessmentPracticeJob(ctx context.Context, arg LockClaimedAssessmentPracticeJobParams) (string, error) { + row := q.db.QueryRow(ctx, lockClaimedAssessmentPracticeJob, arg.SubmissionID, arg.LeaseOwner, arg.StartedAt) + var mode string + err := row.Scan(&mode) + return mode, err +} + +const requeueAssessmentPracticeJob = `-- name: RequeueAssessmentPracticeJob :execrows +UPDATE assessment_practice_jobs +SET + state = 'queued', + available_at = $1, + generation = $2, + attempts = attempts + $3::integer, + last_error_class = coalesce($4, last_error_class), + lease_owner = NULL, + lease_expires_at = NULL, + started_at = NULL, + updated_at = greatest(updated_at, clock_timestamp()) +WHERE + submission_id = $5 + AND state = 'running' + AND lease_owner = $6 + AND started_at = $7 +` + +type RequeueAssessmentPracticeJobParams struct { + AvailableAt pgtype.Timestamptz + Generation int32 + Counted int32 + ErrorClass pgtype.Text + SubmissionID pgtype.UUID + LeaseOwner pgtype.UUID + StartedAt pgtype.Timestamptz +} + +// Puts a running try back into the queue: after a busy runner, a failed +// try, or at shutdown. counted adds the try to the attempts. +func (q *Queries) RequeueAssessmentPracticeJob(ctx context.Context, arg RequeueAssessmentPracticeJobParams) (int64, error) { + result, err := q.db.Exec(ctx, requeueAssessmentPracticeJob, + arg.AvailableAt, + arg.Generation, + arg.Counted, + arg.ErrorClass, + arg.SubmissionID, + arg.LeaseOwner, + arg.StartedAt, + ) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const settleAssessmentPracticeAfterJob = `-- name: SettleAssessmentPracticeAfterJob :execrows +UPDATE assessment_practices AS practice +SET + status = $1, + failure_reason = $2, + updated_at = greatest(practice.updated_at, clock_timestamp()) +WHERE + practice.status = 'pending' + AND practice.id = ( + SELECT submission.practice_id + FROM assessment_practice_submissions AS submission + WHERE submission.id = $3 + ) + AND $3::uuid = ( + SELECT latest.id + FROM assessment_practice_submissions AS latest + WHERE + latest.practice_id = practice.id + AND latest.mode = 'final' + ORDER BY latest.created_at DESC, latest.id DESC + LIMIT 1 + ) +` + +type SettleAssessmentPracticeAfterJobParams struct { + Status string + FailureReason pgtype.Text + SubmissionID pgtype.UUID +} + +// Moves the practice of a final submission out of pending, but only while +// that submission is the latest final one of the practice. +func (q *Queries) SettleAssessmentPracticeAfterJob(ctx context.Context, arg SettleAssessmentPracticeAfterJobParams) (int64, error) { + result, err := q.db.Exec(ctx, settleAssessmentPracticeAfterJob, arg.Status, arg.FailureReason, arg.SubmissionID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const storeAssessmentPracticeResult = `-- name: StoreAssessmentPracticeResult :execrows +UPDATE assessment_practice_submissions +SET + result = $1, + result_at = greatest(created_at, clock_timestamp()) +WHERE + id = $2 + AND result IS NULL +` + +type StoreAssessmentPracticeResultParams struct { + Result []byte + ID pgtype.UUID +} + +// Stores the result of a submission once; a second result changes nothing. +func (q *Queries) StoreAssessmentPracticeResult(ctx context.Context, arg StoreAssessmentPracticeResultParams) (int64, error) { + result, err := q.db.Exec(ctx, storeAssessmentPracticeResult, arg.Result, arg.ID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index c29a09b..ed6f51c 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -243,12 +243,19 @@ type AssessmentPractice struct { } type AssessmentPracticeJob struct { - SubmissionID pgtype.UUID - Mode string - State string - CreatedAt pgtype.Timestamptz - UpdatedAt pgtype.Timestamptz - FinishedAt pgtype.Timestamptz + SubmissionID pgtype.UUID + Mode string + State string + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz + FinishedAt pgtype.Timestamptz + Generation int32 + Attempts int32 + AvailableAt pgtype.Timestamptz + LeaseOwner pgtype.UUID + LeaseExpiresAt pgtype.Timestamptz + StartedAt pgtype.Timestamptz + LastErrorClass pgtype.Text } type AssessmentPracticeSubmission struct { diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 12e2b97..8fa0eed 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -74,6 +74,11 @@ type Querier interface { // organization already appears in their own access history or is already // hidden. Unknown and unseen organizations produce the same no-row result. CandidateCanSeeOrganization(ctx context.Context, arg CandidateCanSeeOrganizationParams) (CandidateCanSeeOrganizationRow, error) + // Claims one job under the queue lock: first a running job whose lease + // expired (its worker stopped without finishing it), then the next queued + // job, final submissions before debug runs. A takeover keeps the generation, + // so the runner returns the run it already has, and counts one attempt. + ClaimAssessmentPracticeJob(ctx context.Context, arg ClaimAssessmentPracticeJobParams) (ClaimAssessmentPracticeJobRow, error) // Claims the most overdue delivery that the sending worker may send, in one // statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds // (the literals match the predicate of deliveries_due_idx, so an idle poll @@ -148,6 +153,11 @@ type Querier interface { // returned registration version in the same transaction, rolled back when it // matches no row. ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error) + // Counts the queued and running jobs; the caller holds the queue lock. + CountActiveAssessmentPracticeJobs(ctx context.Context) (int32, error) + // Counts the unfinished debug runs of a practice; the caller holds the + // practice row lock. + CountActiveAssessmentPracticeRuns(ctx context.Context, practiceID pgtype.UUID) (int32, error) // Count events only for the already owner-locked attempt. CountAssessmentSignalEvents(ctx context.Context, attemptID pgtype.UUID) (int64, error) // Counts the hiding records of one candidate for the settings read. @@ -163,6 +173,9 @@ type Querier interface { // row stays attributed to the organization that consumed it. CountCompanyInvitationQuotaHoldingWindow(ctx context.Context, arg CountCompanyInvitationQuotaHoldingWindowParams) (CountCompanyInvitationQuotaHoldingWindowRow, error) CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error) + // Counts running jobs whose lease has not expired by now, the application + // clock; the caller holds the queue lock. + CountLiveRunningAssessmentPracticeJobs(ctx context.Context, now pgtype.Timestamptz) (int32, error) // Counts the invitations of one organization need that wait for an answer: // delivered, viewed, or the planned counter offer. The send counts them under // the organization lock, which every send takes first, so no other send can @@ -272,6 +285,9 @@ type Querier interface { // sets the timeout reason. No row is returned when it lost a race or the // deadline has not passed. ExpireInvitation(ctx context.Context, arg ExpireInvitationParams) (pgtype.UUID, error) + // Renews the lease of a running try. The owner and the start time identify + // the try, so a worker whose job was taken over changes nothing. + ExtendAssessmentPracticeJobLease(ctx context.Context, arg ExtendAssessmentPracticeJobLeaseParams) (int64, error) // Records a failed attempt after its handler transaction rolled back: the // job waits for its retry at retry_at (status failed) or is dead, with a // NULL retry_at. due_at keeps the deadline. The same guard as the @@ -291,6 +307,8 @@ type Querier interface { // made at or after reserved_since. A retry of the delivery inside the // provider's idempotency window reuses it instead of counting again. FindOpenMailQuotaReservation(ctx context.Context, arg FindOpenMailQuotaReservationParams) (FindOpenMailQuotaReservationRow, error) + // Ends a running try as finished or failed. + FinishAssessmentPracticeJob(ctx context.Context, arg FinishAssessmentPracticeJobParams) (int64, error) // Reads the durable active deletion request when an earlier request already // exists. A completed request does not suppress a later explicit request. GetActiveAccountDeletionRequest(ctx context.Context, subjectID pgtype.UUID) (GetActiveAccountDeletionRequestRow, error) @@ -317,6 +335,9 @@ type Querier interface { GetAssessmentClientSignalTotals(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentClientSignalTotalsRow, error) GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error) GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error) + // Reads what a claimed job runs: the submission and the task of its + // practice. + GetAssessmentPracticeJobWork(ctx context.Context, submissionID pgtype.UUID) (GetAssessmentPracticeJobWorkRow, error) // Reads a debug run of the owner's attempt with the state of its job. GetAssessmentPracticeRun(ctx context.Context, arg GetAssessmentPracticeRunParams) (GetAssessmentPracticeRunRow, error) // The attempt a review job works on: real attempts only. @@ -497,7 +518,7 @@ type Querier interface { InsertAssessmentOriginMark(ctx context.Context, arg InsertAssessmentOriginMarkParams) error InsertAssessmentPractice(ctx context.Context, arg InsertAssessmentPracticeParams) error // Queues the execution job of a submission in the transaction that stores - // the submission. + // the submission. The job is available at once. InsertAssessmentPracticeJob(ctx context.Context, arg InsertAssessmentPracticeJobParams) error InsertAssessmentPracticeSubmission(ctx context.Context, arg InsertAssessmentPracticeSubmissionParams) error InsertAssessmentReviewRead(ctx context.Context, arg InsertAssessmentReviewReadParams) error @@ -859,6 +880,13 @@ type Querier interface { LockAssessmentCategory(ctx context.Context, category string) error // Locks one practice of the owner's attempt for a state change. LockAssessmentPractice(ctx context.Context, arg LockAssessmentPracticeParams) (LockAssessmentPracticeRow, error) + // The practice queue. Admission and the claim take the same + // transaction-scoped advisory lock, so the count of unfinished jobs and the + // change that depends on it are atomic across backend instances. A command + // takes the lock after its attempt and practice row locks; the claim takes + // it first and then skips job rows that another transaction locks, so a + // claim never waits for a row lock while it holds the queue lock. + LockAssessmentPracticeQueue(ctx context.Context) error // Serializes the evaluations of one review. A job takes these locks for every // attempt it will write, in ascending attempt order, before it reads any fact, // so what it reads is what the previous writer committed. @@ -880,6 +908,9 @@ type Querier interface { // keeps the consent-revoked reason after later grants. The returned time is // the effective close time used by the privacy history event. LockCandidatePublicationForConsentRevocation(ctx context.Context, arg LockCandidatePublicationForConsentRevocationParams) (pgtype.Timestamptz, error) + // Locks a running try for its completion and checks that it still belongs + // to the worker. + LockClaimedAssessmentPracticeJob(ctx context.Context, arg LockClaimedAssessmentPracticeJobParams) (string, error) // Locks the delivery row of the lease holder until the transaction ends, so // every path that settles a send takes the delivery lock before the quota // rows, the same order as the claim. No row means that owner no longer holds @@ -1158,6 +1189,9 @@ type Querier interface { ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error) // A new repository starts pending; a known one only records the request. RequestCandidateProjectRepositoryCheck(ctx context.Context, arg RequestCandidateProjectRepositoryCheckParams) error + // Puts a running try back into the queue: after a busy runner, a failed + // try, or at shutdown. counted adds the try to the attempts. + RequeueAssessmentPracticeJob(ctx context.Context, arg RequeueAssessmentPracticeJobParams) (int64, error) // Stores the replay record of a command. A record whose retention has passed // is replaced, so the key is accepted as new after the retention. A live // record is left as it is and nothing is returned; the caller then reads it @@ -1218,6 +1252,9 @@ type Querier interface { // handler, which releases the job row lock so the job can be reclaimed once // its lease expires. SetScheduledJobTransactionTimeouts(ctx context.Context, arg SetScheduledJobTransactionTimeoutsParams) error + // Moves the practice of a final submission out of pending, but only while + // that submission is the latest final one of the practice. + SettleAssessmentPracticeAfterJob(ctx context.Context, arg SettleAssessmentPracticeAfterJobParams) (int64, error) // Starts a claimed attempt right before its handler transaction: it renews // the lease from now and records the start, committed on its own. It // changes nothing when the lease already expired by now or no longer @@ -1229,6 +1266,8 @@ type Querier interface { // fictitious provider attempt, for example when the 23-hour safety cutoff is // reached after the claim but before the provider call. StopUnknownDeliveryRetry(ctx context.Context, arg StopUnknownDeliveryRetryParams) (int64, error) + // Stores the result of a submission once; a second result changes nothing. + StoreAssessmentPracticeResult(ctx context.Context, arg StoreAssessmentPracticeResultParams) (int64, error) // Records activity on an active session and reports whether it is active. // The row is written only when last_seen_at is older than touch_cutoff, so // frequent requests do not rewrite it. last_seen_at never moves back, and a diff --git a/backend/internal/bootstrap/app.go b/backend/internal/bootstrap/app.go index 14d53a7..f40f976 100644 --- a/backend/internal/bootstrap/app.go +++ b/backend/internal/bootstrap/app.go @@ -22,6 +22,7 @@ import ( "lincodex/backend/internal/worker/jobrunner" "lincodex/backend/internal/worker/mailsender" "lincodex/backend/internal/worker/outboxrelay" + "lincodex/backend/internal/worker/practicequeue" ) const ( @@ -37,9 +38,9 @@ type Application struct { // mailSender is the transport selected by EMAIL_PROVIDER. Only the mail // sending worker calls it. mailSender outbound.MailSender - // codeRunner is the runner selected by CODE_RUNNER_URL: the disabled one - // when unset. Practice usecases receive it from here once they exist. - codeRunner outbound.CodeRunner + // practiceQueue runs practice jobs on the code runner while the servers + // run. It is nil without a configured code runner or database. + practiceQueue *practicequeue.Worker // relay publishes outbox events while the servers run. It is nil when // the relay is disabled or the database is not configured. relay *outboxrelay.Relay @@ -156,10 +157,18 @@ func start(ctx context.Context, config config.Config, logger *slog.Logger) (*App if err != nil { return nil, nil, fmt.Errorf("bootstrap.start - initialize application: %w", err) } - // No dependency needs the runner yet, so it is attached here rather than - // injected; the practice usecases will take it from the injector. - application.codeRunner = codeRunner - return application, cleanup, nil + // The worker is the only consumer of the runner, so it is built here + // with the runner rather than through the injector. + practiceQueue, closeQueue, err := newPracticeQueueWorker(ctx, config, logger, codeRunner) + if err != nil { + cleanup() + return nil, nil, fmt.Errorf("bootstrap.start - create practice queue worker: %w", err) + } + application.practiceQueue = practiceQueue + return application, func() { + closeQueue() + cleanup() + }, nil } func logLevel(value string) logkit.Level { @@ -223,7 +232,8 @@ func (application *Application) run(ctx context.Context) error { } // startWorkers runs the relay, every consumer, the scheduled job worker, the -// mail sending worker, and the delivery metrics sampler until ctx ends and returns a channel that +// mail sending worker, the delivery metrics sampler, and the practice queue +// worker until ctx ends and returns a channel that // closes when all of them have stopped. The workers stop together with the // servers; none of them depends on another. func (application *Application) startWorkers(ctx context.Context) <-chan struct{} { @@ -246,6 +256,9 @@ func (application *Application) startWorkers(ctx context.Context) <-chan struct{ if application.deliveryMetrics != nil { workers.Go(func() { application.deliveryMetrics.Run(ctx) }) } + if application.practiceQueue != nil { + workers.Go(func() { application.practiceQueue.Run(ctx) }) + } stopped := make(chan struct{}) go func() { defer close(stopped) diff --git a/backend/internal/bootstrap/practice.go b/backend/internal/bootstrap/practice.go index 06caa52..1160ee2 100644 --- a/backend/internal/bootstrap/practice.go +++ b/backend/internal/bootstrap/practice.go @@ -10,31 +10,54 @@ import ( "lincodex/backend/config" v1 "lincodex/backend/internal/adapter/primary/http/v1" "lincodex/backend/internal/adapter/secondary/postgres" + redisadapter "lincodex/backend/internal/adapter/secondary/redis" + "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/identity" "lincodex/backend/internal/usecase/practice" + "lincodex/backend/internal/worker/practicequeue" + "lincodex/backend/internal/worker/retry" ) -// practicePoolMaxConns covers concurrent debug run requests; each holds one -// short transaction. -const practicePoolMaxConns = 4 +const ( + // practicePoolMaxConns covers concurrent debug run requests; each holds + // one short transaction. + practicePoolMaxConns = 4 + // practiceQueuePoolMaxConns covers the one job in progress and its + // claim: every store call is one short transaction. + practiceQueuePoolMaxConns = 2 + // practiceRunTimeout bounds how long a run may stay unfinished on the + // runner. The runner bounds one run by its CPU budget of 300 s plus the + // compile phase and the queue of its own slots, so this is far above a + // healthy run. + practiceRunTimeout = 10 * time.Minute + // A failed try waits 2 s, doubling up to a minute, so a short runner + // outage costs few attempts. + practiceBackoffInitial = 2 * time.Second + practiceBackoffMax = time.Minute + // practiceStoreTimeout bounds one write of the job state; each is one + // short transaction. + practiceStoreTimeout = 5 * time.Second +) // newPracticeHandler builds the debug run operations of code practice and the // PostgreSQL pool they own. Nothing connects here. It returns no handler when // DATABASE_URL is unset, and the operations then answer 501. Without a code // runner (CODE_RUNNER_URL unset) the operations answer 503 and store nothing. -// The application clock is time.Now. +// The rate limit of debug runs uses the Redis limiter. The application clock +// is time.Now. func newPracticeHandler( ctx context.Context, settings config.Config, logger *slog.Logger, keyring *identity.Keyring, + cache *redisadapter.Cache, ) (*v1.PracticeHandler, func(), error) { if settings.DatabaseURL == "" { logger.Warn("code practice operations are not served because DATABASE_URL is not set") return nil, func() {}, nil } - if keyring == nil { - return nil, nil, errors.New("bootstrap.newPracticeHandler - identity keyring must be set") + if keyring == nil || cache == nil { + return nil, nil, errors.New("bootstrap.newPracticeHandler - identity keyring and Redis cache must be set") } pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, practicePoolMaxConns) if err != nil { @@ -45,5 +68,62 @@ func newPracticeHandler( pool.Close() return nil, nil, fmt.Errorf("bootstrap.newPracticeHandler - create service: %w", err) } + service.WithRunRateLimit(cache, + outbound.RateLimitRule{Window: time.Minute, Limit: settings.Practice.RunsPerMinute}, + outbound.RateLimitRule{Window: time.Hour, Limit: settings.Practice.RunsPerHour}, + ) return v1.NewPracticeHandler(service), pool.Close, nil } + +// newPracticeQueueWorker builds the worker that runs practice jobs on the code +// runner and the PostgreSQL pool it owns. Nothing connects here, so an +// unavailable database or runner never blocks startup. It returns no worker +// without a code runner or without DATABASE_URL: queued jobs then wait in the +// database. The application clock is time.Now. +func newPracticeQueueWorker( + ctx context.Context, + settings config.Config, + logger *slog.Logger, + runner outbound.CodeRunner, +) (*practicequeue.Worker, func(), error) { + switch { + case !settings.CodeRunner.Enabled(): + logger.Info("practice queue worker is off because the code runner is disabled") + return nil, func() {}, nil + case settings.DatabaseURL == "": + logger.Warn("practice queue worker skipped because DATABASE_URL is not set") + return nil, func() {}, nil + } + pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, practiceQueuePoolMaxConns) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newPracticeQueueWorker - create pool: %w", err) + } + store := postgres.NewPracticeJobStore(pool) + workerLogger := logger.With(slog.String("component", "practice_queue")) + executor, err := practice.NewExecutor(runner, store, time.Now, practice.ExecutionSettings{ + PollInterval: settings.Practice.PollInterval, + Lease: settings.Practice.JobLease, + RunTimeout: practiceRunTimeout, + MaxAttempts: settings.Practice.JobMaxAttempts, + BackoffInitial: practiceBackoffInitial, + BackoffMax: practiceBackoffMax, + StoreTimeout: practiceStoreTimeout, + }, workerLogger) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newPracticeQueueWorker - create executor: %w", err) + } + worker, err := practicequeue.New(store, executor, workerLogger, practicequeue.Settings{ + PollInterval: settings.Practice.PollInterval, + Lease: settings.Practice.JobLease, + StoreTimeout: practiceStoreTimeout, + Backoff: retry.Backoff{Initial: practiceBackoffInitial, Max: practiceBackoffMax}, + }, time.Now) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newPracticeQueueWorker - create worker: %w", err) + } + // The application stops the worker before this cleanup runs, so no job + // uses the pool while it closes. + return worker, pool.Close, nil +} diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index 8fa438d..608f68c 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -184,7 +184,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - practiceHandler, cleanup15, err := newPracticeHandler(ctx, config2, logger, keyring) + practiceHandler, cleanup15, err := newPracticeHandler(ctx, config2, logger, keyring, cache) if err != nil { cleanup14() cleanup13() diff --git a/backend/internal/port/outbound/assessment_practice.go b/backend/internal/port/outbound/assessment_practice.go index b4d8be1..2fed1fa 100644 --- a/backend/internal/port/outbound/assessment_practice.go +++ b/backend/internal/port/outbound/assessment_practice.go @@ -74,8 +74,16 @@ type AssessmentPracticeRepository interface { FindByScope(ctx context.Context, userID uuid.UUID, scope [IdempotencyDigestSize]byte) (PracticeSubmissionReplay, bool, error) // LatestFinal returns the latest final submission of a practice, if any. LatestFinal(ctx context.Context, practiceID uuid.UUID) (PracticeFinalSolution, bool, error) + // LockQueue takes the transaction-scoped lock of the practice queue and + // returns the number of queued and running jobs. Admission and the claim + // of the worker take the same lock, so a count and the insert that + // depends on it are atomic. Take it after the attempt and practice locks. + LockQueue(ctx context.Context) (active int, err error) + // ActiveRuns counts the queued and running debug runs of a practice. + ActiveRuns(ctx context.Context, practiceID uuid.UUID) (int, error) // Submit stores a submission under the idempotency scope and queues its - // execution job in the same transaction. + // execution job in the same transaction. The caller holds the queue lock + // and has checked its limits. Submit(ctx context.Context, submission domain.PracticeSubmission, scope [IdempotencyDigestSize]byte) error // GetRun reads a debug run of the owner's attempt with the state of its // job. It never returns a final submission; an unknown, foreign, or final diff --git a/backend/internal/port/outbound/assessment_practice_queue.go b/backend/internal/port/outbound/assessment_practice_queue.go new file mode 100644 index 0000000..99128fa --- /dev/null +++ b/backend/internal/port/outbound/assessment_practice_queue.go @@ -0,0 +1,109 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +// ErrPracticeResultExists reports a completion of a submission that already +// has a result. Nothing was written. +var ErrPracticeResultExists = errors.New("practice submission already has a result") + +// PracticeJobErrorClass is the bounded cause of a failed or abandoned try of +// a practice job. It never carries runner or candidate text. +type PracticeJobErrorClass string + +const ( + // PracticeJobRunnerUnavailable: the runner could not be reached, refused + // the token, or answered outside its contract; the try is repeated with + // the same run key. + PracticeJobRunnerUnavailable PracticeJobErrorClass = "runner_unavailable" + // PracticeJobInfrastructureFailure: the runner could not evaluate the + // source; the next try uses a new generation. + PracticeJobInfrastructureFailure PracticeJobErrorClass = "runner_infrastructure_failure" + // PracticeJobInvalidRequest: the stored task or submission cannot form a + // valid runner request, a content bug; the job fails at once. + PracticeJobInvalidRequest PracticeJobErrorClass = "invalid_request" + // PracticeJobRunTimeout: the run stayed unfinished on the runner longer + // than the run timeout. + PracticeJobRunTimeout PracticeJobErrorClass = "run_timeout" + // PracticeJobLeaseExpired: the worker of the try stopped without + // finishing it, and another claim took the job over. + PracticeJobLeaseExpired PracticeJobErrorClass = "lease_expired" +) + +// PracticeJobClaim asks for the next practice job. Now is the application +// clock; the database clock never decides whether a lease expired. +type PracticeJobClaim struct { + Owner uuid.UUID + Now time.Time + Lease time.Duration + // MaxRunning bounds the running jobs whose leases have not expired. + MaxRunning int +} + +// ClaimedPracticeJob is one running try of a practice job. The owner and the +// start time identify the try: every change of the job checks both, so a +// worker whose job was taken over changes nothing. +type ClaimedPracticeJob struct { + SubmissionID uuid.UUID + Mode domain.PracticeSubmissionMode + Generation uint32 + Attempts int + LeaseOwner uuid.UUID + LeaseExpiresAt time.Time + StartedAt time.Time + // Reclaimed reports that the previous try's lease expired and this + // claim took the job over. + Reclaimed bool +} + +// PracticeJobWork is what a claimed job runs. +type PracticeJobWork struct { + Submission domain.PracticeSubmission + Task domain.PracticeTask +} + +// PracticeRequeue puts a running try back into the queue. +type PracticeRequeue struct { + AvailableAt time.Time + Generation uint32 + // Counted adds the try to the attempts of the job; a busy runner and a + // shutdown do not count. + Counted bool + ErrorClass PracticeJobErrorClass +} + +// PracticeJobStore keeps the practice queue for the worker. Each method is +// one short transaction; no transaction stays open while the runner works. +type PracticeJobStore interface { + // Claim takes the next job under the queue lock when fewer than + // MaxRunning jobs hold a live lease: a running job whose lease expired + // first, then the next queued job that is available, final submissions + // before debug runs. claimed is false when there is nothing to run. + Claim(ctx context.Context, claim PracticeJobClaim) (job ClaimedPracticeJob, claimed bool, err error) + // Work reads the submission and the task of a claimed job. Stored + // content that fails validation returns an error wrapping + // domain.ErrInvalidAssessmentPractice. + Work(ctx context.Context, job ClaimedPracticeJob) (PracticeJobWork, error) + // Extend renews the lease of a try until expiresAt. held is false when + // the job no longer belongs to the try. + Extend(ctx context.Context, job ClaimedPracticeJob, expiresAt time.Time) (renewed ClaimedPracticeJob, held bool, err error) + // Requeue puts a try back into the queue; held is false when the job no + // longer belongs to the try. + Requeue(ctx context.Context, job ClaimedPracticeJob, requeue PracticeRequeue) (held bool, err error) + // Complete stores the result of the submission once, finishes the job, + // and, for the latest final submission of a pending practice, finishes + // the practice, all in one transaction. held is false, with nothing + // written, when the job no longer belongs to the try. + Complete(ctx context.Context, job ClaimedPracticeJob, result domain.PracticeRunResult) (held bool, err error) + // Fail ends the job as failed with the error class and, for the latest + // final submission of a pending practice, marks the practice failed with + // sandbox_error. It never stores a verdict. + Fail(ctx context.Context, job ClaimedPracticeJob, class PracticeJobErrorClass) (held bool, err error) +} diff --git a/backend/internal/usecase/practice/execute.go b/backend/internal/usecase/practice/execute.go new file mode 100644 index 0000000..3df3365 --- /dev/null +++ b/backend/internal/usecase/practice/execute.go @@ -0,0 +1,327 @@ +package practice + +import ( + "context" + "errors" + "fmt" + "log/slog" + "time" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// ExecutionOutcome is how one try of a practice job ended. Every claimed job +// ends a try with exactly one. +type ExecutionOutcome string + +const ( + // OutcomeFinished: the result is stored, once. + OutcomeFinished ExecutionOutcome = "finished" + // OutcomeFailed: the infrastructure gave up on the job; nothing was + // graded and a final practice can be submitted again. + OutcomeFailed ExecutionOutcome = "failed" + // OutcomeBusy: the runner had no free slot; the job waits for the time + // the runner asked for, and the try does not count. + OutcomeBusy ExecutionOutcome = "busy" + // OutcomeRetry: the try failed in the infrastructure and the job waits + // for its backoff. + OutcomeRetry ExecutionOutcome = "retry" + // OutcomeLeaseLost: another worker took the job over; this try wrote + // nothing. + OutcomeLeaseLost ExecutionOutcome = "lease_lost" + // OutcomeReleased: the worker stopped and gave the job back unfinished + // without counting the try. + OutcomeReleased ExecutionOutcome = "released" +) + +// Bounds of the wait that a busy runner asks for. +const ( + minBusyWait = time.Second + maxBusyWait = time.Minute +) + +// ExecutionSettings are the limits of one try; config validates their +// ranges. +type ExecutionSettings struct { + // PollInterval is the wait between two reads of a running run. + PollInterval time.Duration + // Lease is how long a try holds its job; each poll renews it. + Lease time.Duration + // RunTimeout bounds how long a run may stay unfinished on the runner + // before the try counts as failed. + RunTimeout time.Duration + // MaxAttempts bounds the failed tries and expired leases of a job before + // it fails. + MaxAttempts int + // BackoffInitial is the wait after the first failed try; it doubles up + // to BackoffMax. + BackoffInitial time.Duration + BackoffMax time.Duration + // StoreTimeout bounds one write of the job state. + StoreTimeout time.Duration +} + +func (settings ExecutionSettings) validate() error { + if settings.PollInterval <= 0 || settings.Lease <= settings.PollInterval || settings.RunTimeout <= 0 || + settings.MaxAttempts < 1 || settings.BackoffInitial <= 0 || settings.BackoffMax < settings.BackoffInitial || + settings.StoreTimeout <= 0 { + return errors.New("practice.NewExecutor - intervals must be positive, the lease longer than a poll, and attempts at least one") + } + return nil +} + +// Executor runs one claimed practice job on the code runner: it submits the +// run, polls it while renewing the lease, and stores the result once. An +// infrastructure failure is retried and never becomes a verdict; a runner +// that could not evaluate the source gets a new generation of the run key. +type Executor struct { + runner outbound.CodeRunner + store outbound.PracticeJobStore + clock func() time.Time + settings ExecutionSettings + logger *slog.Logger +} + +func NewExecutor( + runner outbound.CodeRunner, + store outbound.PracticeJobStore, + clock func() time.Time, + settings ExecutionSettings, + logger *slog.Logger, +) (*Executor, error) { + if runner == nil || store == nil || clock == nil || logger == nil { + return nil, errors.New("practice.NewExecutor - runner, store, clock, and logger are required") + } + if err := settings.validate(); err != nil { + return nil, err + } + return &Executor{runner: runner, store: store, clock: clock, settings: settings, logger: logger}, nil +} + +// Execute runs one try of a claimed job until the job is finished, failed, +// back in the queue, or taken over. The error reports a database failure; the +// job is then released or waits for its lease to expire. +func (executor *Executor) Execute(ctx context.Context, job outbound.ClaimedPracticeJob) (ExecutionOutcome, error) { + if job.Attempts >= executor.settings.MaxAttempts { + return executor.fail(ctx, job, outbound.PracticeJobLeaseExpired) + } + work, err := executor.store.Work(ctx, job) + switch { + case errors.Is(err, domain.ErrInvalidAssessmentPractice): + return executor.fail(ctx, job, outbound.PracticeJobInvalidRequest) + case err != nil: + return executor.release(ctx, job, fmt.Errorf("Executor.Execute - read work: %w", err)) + } + request, err := RunRequest(work.Task, work.Submission, job.Generation) + if err != nil { + return executor.fail(ctx, job, outbound.PracticeJobInvalidRequest) + } + status, err := executor.runner.Submit(ctx, request) + for { + if err != nil { + return executor.runnerFailure(ctx, job, err) + } + switch status.State { + case outbound.CodeRunBusy: + return executor.requeueBusy(ctx, job, status.RetryAfter) + case outbound.CodeRunFinished: + return executor.complete(ctx, job, status) + case outbound.CodeRunRunning: + default: + return executor.runnerFailure(ctx, job, outbound.ErrCodeRunnerBadResponse) + } + if executor.clock().Sub(job.StartedAt) >= executor.settings.RunTimeout { + return executor.retry(ctx, job, job.Generation, outbound.PracticeJobRunTimeout) + } + if !waitFor(ctx, executor.settings.PollInterval) { + return executor.release(ctx, job, nil) + } + renewed, held, extendErr := executor.store.Extend(ctx, job, executor.clock().Add(executor.settings.Lease)) + switch { + case extendErr != nil: + return executor.release(ctx, job, fmt.Errorf("Executor.Execute - renew lease: %w", extendErr)) + case !held: + return OutcomeLeaseLost, nil + } + job = renewed + status, err = executor.runner.Poll(ctx, request) + if errors.Is(err, outbound.ErrCodeRunNotFound) { + // The runner lost the run in a restart or after its retention; + // the same key starts it again. + status, err = executor.runner.Submit(ctx, request) + } + } +} + +// runnerFailure decides on a runner error. None of them is a verdict. +func (executor *Executor) runnerFailure(ctx context.Context, job outbound.ClaimedPracticeJob, err error) (ExecutionOutcome, error) { + switch { + case ctx.Err() != nil: + return executor.release(ctx, job, nil) + case errors.Is(err, outbound.ErrInvalidCodeRunRequest): + return executor.fail(ctx, job, outbound.PracticeJobInvalidRequest) + case errors.Is(err, outbound.ErrCodeRunnerInfrastructureFailure), errors.Is(err, outbound.ErrCodeRunKeyReused): + // The runner keeps its stored failure, or another payload, under the + // old run ID, so the next try needs a new one. + return executor.retry(ctx, job, job.Generation+1, outbound.PracticeJobInfrastructureFailure) + default: + // The run may exist on the runner; the same key finds it again. + return executor.retry(ctx, job, job.Generation, outbound.PracticeJobRunnerUnavailable) + } +} + +func (executor *Executor) complete(ctx context.Context, job outbound.ClaimedPracticeJob, status outbound.CodeRunStatus) (ExecutionOutcome, error) { + if status.Result == nil { + return executor.runnerFailure(ctx, job, outbound.ErrCodeRunnerBadResponse) + } + storeCtx, cancel := executor.storeContext(ctx) + defer cancel() + held, err := executor.store.Complete(storeCtx, job, runResult(*status.Result)) + switch { + case err != nil: + return "", fmt.Errorf("Executor.complete - store result: %w", err) + case !held: + return OutcomeLeaseLost, nil + } + executor.logger.Info("practice job finished", jobAttributes(job, slog.String("outcome", string(status.Result.Outcome)))...) + return OutcomeFinished, nil +} + +func (executor *Executor) requeueBusy(ctx context.Context, job outbound.ClaimedPracticeJob, retryAfter time.Duration) (ExecutionOutcome, error) { + wait := min(max(retryAfter, minBusyWait), maxBusyWait) + return executor.requeue(ctx, job, outbound.PracticeRequeue{ + AvailableAt: executor.clock().Add(wait), Generation: job.Generation, + }, OutcomeBusy) +} + +// retry counts a failed try: the job waits for its backoff, or fails once +// the attempts ran out. +func (executor *Executor) retry( + ctx context.Context, + job outbound.ClaimedPracticeJob, + generation uint32, + class outbound.PracticeJobErrorClass, +) (ExecutionOutcome, error) { + attempts := job.Attempts + 1 + if attempts >= executor.settings.MaxAttempts { + return executor.fail(ctx, job, class) + } + executor.logger.Warn("practice job try failed in the infrastructure; retrying", + jobAttributes(job, slog.String("error_class", string(class)))...) + return executor.requeue(ctx, job, outbound.PracticeRequeue{ + AvailableAt: executor.clock().Add(executor.backoff(attempts)), Generation: generation, Counted: true, ErrorClass: class, + }, OutcomeRetry) +} + +func (executor *Executor) requeue( + ctx context.Context, + job outbound.ClaimedPracticeJob, + requeue outbound.PracticeRequeue, + outcome ExecutionOutcome, +) (ExecutionOutcome, error) { + storeCtx, cancel := executor.storeContext(ctx) + defer cancel() + held, err := executor.store.Requeue(storeCtx, job, requeue) + switch { + case err != nil: + return "", fmt.Errorf("Executor.requeue - requeue job: %w", err) + case !held: + return OutcomeLeaseLost, nil + } + return outcome, nil +} + +// fail ends the job without a verdict; a final practice becomes failed with +// sandbox_error and accepts a solution again. +func (executor *Executor) fail(ctx context.Context, job outbound.ClaimedPracticeJob, class outbound.PracticeJobErrorClass) (ExecutionOutcome, error) { + storeCtx, cancel := executor.storeContext(ctx) + defer cancel() + held, err := executor.store.Fail(storeCtx, job, class) + switch { + case err != nil: + return "", fmt.Errorf("Executor.fail - fail job: %w", err) + case !held: + return OutcomeLeaseLost, nil + } + executor.logger.Error("practice job failed in the infrastructure; nothing was graded", + jobAttributes(job, slog.String("error_class", string(class)))...) + return OutcomeFailed, nil +} + +// release gives the job back at once without counting the try, at shutdown +// or after a database failure. A failed release leaves the job to its lease. +func (executor *Executor) release(ctx context.Context, job outbound.ClaimedPracticeJob, cause error) (ExecutionOutcome, error) { + outcome, err := executor.requeue(ctx, job, outbound.PracticeRequeue{AvailableAt: executor.clock(), Generation: job.Generation}, OutcomeReleased) + if cause != nil { + return outcome, errors.Join(cause, err) + } + return outcome, err +} + +// storeContext lets a write of the job state finish after shutdown began, so +// a result or a failure is not lost to a restart. +func (executor *Executor) storeContext(ctx context.Context) (context.Context, context.CancelFunc) { + return context.WithTimeout(context.WithoutCancel(ctx), executor.settings.StoreTimeout) +} + +func (executor *Executor) backoff(attempts int) time.Duration { + delay := executor.settings.BackoffInitial + for range attempts - 1 { + if delay >= executor.settings.BackoffMax/2 { + return executor.settings.BackoffMax + } + delay *= 2 + } + return min(delay, executor.settings.BackoffMax) +} + +// runResult keeps what the stored result needs: per-test details of public +// groups only. A hidden group keeps its outcome and counts. +func runResult(result outbound.CodeRunResult) domain.PracticeRunResult { + stored := domain.PracticeRunResult{ + Outcome: domain.PracticeOutcome(result.Outcome), DurationMs: result.Duration.Milliseconds(), + Groups: make([]domain.PracticeGroupOutcome, 0, len(result.Groups)), + } + if result.Compile != nil && result.Outcome == outbound.CodeOutcomeCompileError { + stored.CompileDiagnostic = result.Compile.Diagnostic + } + for _, group := range result.Groups { + outcome := domain.PracticeGroupOutcome{ + ID: group.ID, Hidden: group.Visibility == outbound.CodeTestHidden, Outcome: domain.PracticeOutcome(group.Outcome), + PassedTests: group.PassedTests, TotalTests: group.TotalTests, + } + if !outcome.Hidden { + for _, test := range group.Tests { + outcome.Tests = append(outcome.Tests, domain.PracticeTestOutcome{ + ID: test.ID, Outcome: domain.PracticeOutcome(test.Outcome), TimeMs: test.TimeMs, + MemoryKB: test.MemoryKB, Diagnostic: test.Diagnostic, + }) + } + } + stored.Groups = append(stored.Groups, outcome) + } + return stored +} + +// jobAttributes identify a try in logs without the source, tests, or owner. +func jobAttributes(job outbound.ClaimedPracticeJob, extra ...any) []any { + return append([]any{ + slog.String("submission_id", job.SubmissionID.String()), + slog.String("mode", string(job.Mode)), + slog.Int("generation", int(job.Generation)), + slog.Int("attempts", job.Attempts), + }, extra...) +} + +// waitFor waits for the delay and reports false when ctx ended first. +func waitFor(ctx context.Context, delay time.Duration) bool { + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return false + case <-timer.C: + return true + } +} diff --git a/backend/internal/usecase/practice/execute_test.go b/backend/internal/usecase/practice/execute_test.go new file mode 100644 index 0000000..fdcffaf --- /dev/null +++ b/backend/internal/usecase/practice/execute_test.go @@ -0,0 +1,184 @@ +package practice + +import ( + "context" + "errors" + "log/slog" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func TestExecutorNeverTurnsAnInfrastructureFailureIntoAVerdict(t *testing.T) { + now := time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC) + cases := []struct { + name string + submitErr error + attempts int + wantOutcome ExecutionOutcome + wantGeneration uint32 + wantFailed outbound.PracticeJobErrorClass + }{ + {name: "unreachable runner keeps the run key", submitErr: outbound.ErrCodeRunnerBadResponse, + wantOutcome: OutcomeRetry, wantGeneration: 2}, + {name: "infrastructure failure starts a new run", submitErr: outbound.ErrCodeRunnerInfrastructureFailure, + wantOutcome: OutcomeRetry, wantGeneration: 3}, + {name: "reused key starts a new run", submitErr: outbound.ErrCodeRunKeyReused, + wantOutcome: OutcomeRetry, wantGeneration: 3}, + {name: "invalid request fails without a verdict", submitErr: outbound.ErrInvalidCodeRunRequest, + wantOutcome: OutcomeFailed, wantFailed: outbound.PracticeJobInvalidRequest}, + {name: "last attempt fails without a verdict", submitErr: outbound.ErrCodeRunnerUnavailable, attempts: 2, + wantOutcome: OutcomeFailed, wantFailed: outbound.PracticeJobRunnerUnavailable}, + {name: "exhausted takeover fails at once", attempts: 3, + wantOutcome: OutcomeFailed, wantFailed: outbound.PracticeJobLeaseExpired}, + } + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + store := &fakeJobStore{} + runner := &fakeRunner{submitErr: testCase.submitErr} + executor := testExecutor(t, runner, store, now) + job := outbound.ClaimedPracticeJob{SubmissionID: uuid.New(), Generation: 2, Attempts: testCase.attempts, StartedAt: now} + outcome, err := executor.Execute(t.Context(), job) + if err != nil || outcome != testCase.wantOutcome { + t.Fatalf("Execute() = %q, error %v; want %q", outcome, err, testCase.wantOutcome) + } + if store.completed { + t.Fatal("an infrastructure failure stored a result") + } + if testCase.wantFailed != "" && store.failedWith != testCase.wantFailed { + t.Fatalf("failed with %q, want %q", store.failedWith, testCase.wantFailed) + } + if testCase.wantOutcome == OutcomeRetry { + if !store.requeue.Counted || store.requeue.Generation != testCase.wantGeneration || + !store.requeue.AvailableAt.Equal(now.Add(time.Second)) { + t.Fatalf("requeue = %+v, want a counted try at generation %d after the first backoff", store.requeue, testCase.wantGeneration) + } + } + }) + } +} + +func TestExecutorHandlesPollFailuresAndShutdown(t *testing.T) { + now := time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC) + store := &fakeJobStore{} + runner := &fakeRunner{pollErr: outbound.ErrCodeRunNotFound, submits: []outbound.CodeRunState{outbound.CodeRunRunning, outbound.CodeRunFinished}} + executor := testExecutor(t, runner, store, now) + job := outbound.ClaimedPracticeJob{SubmissionID: uuid.New(), StartedAt: now} + if outcome, err := executor.Execute(t.Context(), job); err != nil || outcome != OutcomeFinished || !store.completed { + t.Fatalf("Execute() = %q, error %v, completed %v; want the resubmitted run finished", outcome, err, store.completed) + } + if runner.submitCalls != 2 || runner.pollCalls != 1 { + t.Fatalf("submits = %d, polls = %d; want a resubmit after the lost run", runner.submitCalls, runner.pollCalls) + } + + store = &fakeJobStore{} + runner = &fakeRunner{pollErr: outbound.ErrCodeRunnerInfrastructureFailure, submits: []outbound.CodeRunState{outbound.CodeRunRunning}} + executor = testExecutor(t, runner, store, now) + if outcome, err := executor.Execute(t.Context(), job); err != nil || outcome != OutcomeRetry || store.requeue.Generation != job.Generation+1 { + t.Fatalf("Execute() after a failed poll = %q, error %v, requeue %+v; want a retry on a new generation", outcome, err, store.requeue) + } + + store = &fakeJobStore{} + runner = &fakeRunner{submits: []outbound.CodeRunState{outbound.CodeRunRunning}} + executor = testExecutor(t, runner, store, now) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if outcome, err := executor.Execute(ctx, job); err != nil || outcome != OutcomeReleased { + t.Fatalf("Execute() at shutdown = %q, error %v; want released", outcome, err) + } + if store.requeue.Counted || store.requeue.Generation != job.Generation { + t.Fatalf("release = %+v, want an uncounted requeue on the same key", store.requeue) + } +} + +func testExecutor(t *testing.T, runner outbound.CodeRunner, store outbound.PracticeJobStore, now time.Time) *Executor { + t.Helper() + executor, err := NewExecutor(runner, store, func() time.Time { return now }, ExecutionSettings{ + PollInterval: time.Millisecond, Lease: time.Minute, RunTimeout: time.Hour, MaxAttempts: 3, + BackoffInitial: time.Second, BackoffMax: 4 * time.Second, StoreTimeout: time.Second, + }, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("NewExecutor() error = %v", err) + } + return executor +} + +type fakeRunner struct { + submitErr error + pollErr error + submits []outbound.CodeRunState + submitCalls int + pollCalls int +} + +func (runner *fakeRunner) Submit(_ context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) { + runner.submitCalls++ + if runner.submitErr != nil { + return outbound.CodeRunStatus{}, runner.submitErr + } + state := runner.submits[min(runner.submitCalls, len(runner.submits))-1] + return fakeStatus(state, request), nil +} + +func (runner *fakeRunner) Poll(_ context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) { + runner.pollCalls++ + if runner.pollErr != nil { + return outbound.CodeRunStatus{}, runner.pollErr + } + return fakeStatus(outbound.CodeRunFinished, request), nil +} + +func fakeStatus(state outbound.CodeRunState, request outbound.CodeRunRequest) outbound.CodeRunStatus { + if state != outbound.CodeRunFinished { + return outbound.CodeRunStatus{State: state} + } + result := outbound.CodeRunResult{Outcome: outbound.CodeOutcomeAccepted} + for _, group := range request.Groups { + result.Groups = append(result.Groups, outbound.CodeGroupResult{ + ID: group.ID, Visibility: group.Visibility, Outcome: outbound.CodeOutcomeAccepted, + PassedTests: len(group.Tests), TotalTests: len(group.Tests), + }) + } + return outbound.CodeRunStatus{State: state, Result: &result} +} + +type fakeJobStore struct { + requeue outbound.PracticeRequeue + failedWith outbound.PracticeJobErrorClass + completed bool +} + +func (store *fakeJobStore) Claim(context.Context, outbound.PracticeJobClaim) (outbound.ClaimedPracticeJob, bool, error) { + return outbound.ClaimedPracticeJob{}, false, errors.New("not used") +} + +func (store *fakeJobStore) Work(_ context.Context, job outbound.ClaimedPracticeJob) (outbound.PracticeJobWork, error) { + return outbound.PracticeJobWork{Task: testTask(), Submission: domain.PracticeSubmission{ + ID: job.SubmissionID, PracticeID: uuid.New(), UserID: uuid.New(), Mode: domain.PracticeModeFinal, + Language: domain.TaskLanguagePython, Source: "print(1)\n", CreatedAt: time.Now(), + }}, nil +} + +func (store *fakeJobStore) Extend(_ context.Context, job outbound.ClaimedPracticeJob, expiresAt time.Time) (outbound.ClaimedPracticeJob, bool, error) { + job.LeaseExpiresAt = expiresAt + return job, true, nil +} + +func (store *fakeJobStore) Requeue(_ context.Context, _ outbound.ClaimedPracticeJob, requeue outbound.PracticeRequeue) (bool, error) { + store.requeue = requeue + return true, nil +} + +func (store *fakeJobStore) Complete(context.Context, outbound.ClaimedPracticeJob, domain.PracticeRunResult) (bool, error) { + store.completed = true + return true, nil +} + +func (store *fakeJobStore) Fail(_ context.Context, _ outbound.ClaimedPracticeJob, class outbound.PracticeJobErrorClass) (bool, error) { + store.failedWith = class + return true, nil +} diff --git a/backend/internal/usecase/practice/service.go b/backend/internal/usecase/practice/service.go index 24cf32e..5073df7 100644 --- a/backend/internal/usecase/practice/service.go +++ b/backend/internal/usecase/practice/service.go @@ -6,6 +6,7 @@ package practice import ( "context" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -25,6 +26,29 @@ const ( maxIdempotencyKeyBytes = 255 ) +// Limits of the practice queue. The runner runs one program at a time, so one +// job runs and ten wait; a command beyond them is answered busy and stores +// nothing. +const ( + MaxRunningJobs = 1 + MaxQueuedJobs = 10 + // queueCapacity counts the running and the queued jobs together, as + // admission sees them: a job counts until it is finished. + queueCapacity = MaxRunningJobs + MaxQueuedJobs + // queueBusyRetryAfter is the wait a full queue announces. Runs take + // seconds, so a slot frees up within it most of the time. + queueBusyRetryAfter = 10 * time.Second + // activeRunRetryAfter is the wait announced while the previous debug run + // of the practice is unfinished. + activeRunRetryAfter = 2 * time.Second + // maxActiveRunsPerPractice keeps one candidate from filling the queue + // with debug runs of one practice. + maxActiveRunsPerPractice = 1 + // runBucketLabel separates the rate limit counters of debug runs from + // other uses of the keyed digest. + runBucketLabel = "lincodex/practice/run-bucket/v1" +) + // Request fields that a FieldError names. The HTTP adapter turns them into // pointers of its own body. const ( @@ -53,8 +77,26 @@ var ( // ErrUnavailable reports that code practice cannot run now, for example // because the code runner is disabled. Nothing was stored or graded. ErrUnavailable = errors.New("code practice unavailable") + // ErrQueueBusy reports that the practice queue is full. Nothing was + // stored; RetryError carries the wait. + ErrQueueBusy = errors.New("practice queue is full") + // ErrRateLimited reports a debug run beyond the technical limits: the + // rate limit of the candidate, or an unfinished run of the practice. + // Nothing was stored; RetryError carries the wait. + ErrRateLimited = errors.New("practice run limit reached") ) +// RetryError is a refusal that a later retry can pass, with the wait the +// caller announces. +type RetryError struct { + Err error + RetryAfter time.Duration +} + +func (retryError *RetryError) Error() string { return retryError.Err.Error() } + +func (retryError *RetryError) Unwrap() error { return retryError.Err } + // FieldError names the request field that ErrInvalidRequest is about. type FieldError struct { Field string @@ -80,6 +122,10 @@ type Service struct { // enabled is false when no code runner is configured: practice then // answers unavailable and stores nothing. enabled bool + // limiter and runRules bound the debug runs of one candidate; without a + // limiter only the queue limits apply. + limiter outbound.RateLimiter + runRules []outbound.RateLimitRule } func NewService(transactor outbound.Transactor, keyring Keyring, clock func() time.Time, enabled bool) (*Service, error) { @@ -89,6 +135,13 @@ func NewService(transactor outbound.Transactor, keyring Keyring, clock func() ti return &Service{transactor: transactor, keyring: keyring, clock: clock, enabled: enabled}, nil } +// WithRunRateLimit bounds the debug runs of one candidate by the rules, all +// counted at once. A limiter failure refuses the run as unavailable. +func (service *Service) WithRunRateLimit(limiter outbound.RateLimiter, rules ...outbound.RateLimitRule) *Service { + service.limiter, service.runRules = limiter, rules + return service +} + // RunCommand asks for a debug run of a solution against the public examples // and the candidate's own tests. type RunCommand struct { @@ -126,6 +179,10 @@ type FinalResult struct { // Unchanged reports that the same solution was already submitted and // nothing was stored. Unchanged bool + // RetryAfter is set when the queue was full: the practice is failed with + // sandbox_busy, the solution was not stored, and it can be submitted + // again after the wait. + RetryAfter time.Duration } type canonicalRequest struct { @@ -200,6 +257,9 @@ func (service *Service) submitRunInTransaction( if err != nil { return RunResult{}, fmt.Errorf("%s - build submission: %w", location, err) } + if err := service.admitRun(ctx, repository, command.ActorID, practice.ID); err != nil { + return RunResult{}, fmt.Errorf("%s - admit run: %w", location, err) + } if err := repository.Submit(ctx, submission, request.record.Scope); err != nil { return RunResult{}, fmt.Errorf("%s - store run: %w", location, err) } @@ -271,6 +331,20 @@ func (service *Service) submitFinalInTransaction( if !practice.Status.AcceptsFinalSubmission() { return finalRepeat(ctx, repository, practice, submission) } + active, err := repository.LockQueue(ctx) + if err != nil { + return FinalResult{}, fmt.Errorf("%s - lock queue: %w", location, err) + } + if active >= queueCapacity { + // The full queue consumes nothing: the solution is not stored, and + // the failed practice accepts it again. + practice.Status, practice.FailureReason, practice.SubmittedAt = + domain.AssessmentPracticeFailed, domain.AssessmentPracticeSandboxBusy, now + if err := repository.SaveState(ctx, practice, now); err != nil { + return FinalResult{}, fmt.Errorf("%s - mark practice busy: %w", location, err) + } + return FinalResult{Practice: practice.View(), RetryAfter: queueBusyRetryAfter}, nil + } if err := repository.Submit(ctx, submission, request.record.Scope); err != nil { return FinalResult{}, fmt.Errorf("%s - store final submission: %w", location, err) } @@ -281,6 +355,46 @@ func (service *Service) submitFinalInTransaction( return FinalResult{Practice: practice.View()}, nil } +// admitRun applies the limits of a debug run in its transaction, which holds +// the practice lock: one unfinished run per practice, the rate limit of the +// candidate, then the queue capacity under the queue lock. A refusal stores +// nothing. +func (service *Service) admitRun( + ctx context.Context, + repository outbound.AssessmentPracticeRepository, + actorID uuid.UUID, + practiceID uuid.UUID, +) error { + const location = "Service.admitRun" + running, err := repository.ActiveRuns(ctx, practiceID) + if err != nil { + return fmt.Errorf("%s - count unfinished runs: %w", location, err) + } + if running >= maxActiveRunsPerPractice { + return fmt.Errorf("%s - a run of the practice is unfinished: %w", location, + &RetryError{Err: ErrRateLimited, RetryAfter: activeRunRetryAfter}) + } + if service.limiter != nil { + digest := service.keyring.Fingerprint([]byte(runBucketLabel + "\x00" + actorID.String())) + decision, err := service.limiter.Take(ctx, "practice:run:"+hex.EncodeToString(digest[:]), service.runRules...) + if err != nil { + return fmt.Errorf("%s - take rate limit: %w: %w", location, ErrUnavailable, err) + } + if !decision.Allowed { + return fmt.Errorf("%s - rate limit reached: %w", location, + &RetryError{Err: ErrRateLimited, RetryAfter: decision.RetryAfter}) + } + } + active, err := repository.LockQueue(ctx) + if err != nil { + return fmt.Errorf("%s - lock queue: %w", location, err) + } + if active >= queueCapacity { + return fmt.Errorf("%s - queue is full: %w", location, &RetryError{Err: ErrQueueBusy, RetryAfter: queueBusyRetryAfter}) + } + return nil +} + // finalRepeat answers a final submission to a pending or finished practice: // the stored solution sent again changes nothing, anything else conflicts. func finalRepeat( diff --git a/backend/internal/worker/practicequeue/worker.go b/backend/internal/worker/practicequeue/worker.go new file mode 100644 index 0000000..c075d68 --- /dev/null +++ b/backend/internal/worker/practicequeue/worker.go @@ -0,0 +1,132 @@ +// Package practicequeue runs the practice queue: it claims one practice job +// at a time under a lease and hands it to the practice executor, which runs +// it on the code runner. The queue is not the scheduled job runtime because a +// practice try waits for an external run for seconds or minutes, while a +// scheduled job runs its handler inside the transaction that completes it; +// here no transaction stays open while the runner works. +package practicequeue + +import ( + "context" + "errors" + "fmt" + "log/slog" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/practice" + "lincodex/backend/internal/worker/retry" +) + +// Executor runs one claimed job. +type Executor interface { + Execute(ctx context.Context, job outbound.ClaimedPracticeJob) (practice.ExecutionOutcome, error) +} + +// Settings are the worker limits; config validates their ranges. +type Settings struct { + // PollInterval is the wait after a pass that found nothing to run. + PollInterval time.Duration + // Lease is how long a claimed job belongs to this worker before another + // may take it over; the executor renews it while the run lasts. + Lease time.Duration + // StoreTimeout bounds one claim. + StoreTimeout time.Duration + // Backoff spaces passes while the database fails. + Backoff retry.Backoff +} + +func (settings Settings) validate() error { + if settings.PollInterval <= 0 || settings.Lease <= 0 || settings.StoreTimeout <= 0 || + settings.Backoff.Initial <= 0 || settings.Backoff.Max < settings.Backoff.Initial { + return errors.New("practicequeue.New - poll interval, lease, store timeout, and backoff must be positive") + } + return nil +} + +// Worker claims practice jobs. Several workers may run against one database: +// the claim keeps at most practice.MaxRunningJobs jobs running across all of +// them. +type Worker struct { + owner uuid.UUID + store outbound.PracticeJobStore + executor Executor + logger *slog.Logger + settings Settings + clock func() time.Time +} + +// New builds a worker with a random lease owner ID. clock is the application +// clock that every lease decision uses. +func New(store outbound.PracticeJobStore, executor Executor, logger *slog.Logger, settings Settings, clock func() time.Time) (*Worker, error) { + if store == nil || executor == nil || logger == nil || clock == nil { + return nil, errors.New("practicequeue.New - store, executor, logger, and clock are required") + } + if err := settings.validate(); err != nil { + return nil, err + } + owner := uuid.New() + return &Worker{ + owner: owner, store: store, executor: executor, settings: settings, clock: clock, + logger: logger.With(slog.String("lease_owner", owner.String())), + }, nil +} + +// RunOnce claims one job and runs it. claimed is false when nothing could be +// claimed: the queue is empty, nothing is available yet, or the running limit +// is reached. Tests call it to drive the queue step by step; Run repeats it. +func (worker *Worker) RunOnce(ctx context.Context) (outcome practice.ExecutionOutcome, claimed bool, err error) { + claimCtx, cancel := context.WithTimeout(ctx, worker.settings.StoreTimeout) + job, claimed, err := worker.store.Claim(claimCtx, outbound.PracticeJobClaim{ + Owner: worker.owner, Now: worker.clock(), Lease: worker.settings.Lease, MaxRunning: practice.MaxRunningJobs, + }) + cancel() + if err != nil { + return "", false, fmt.Errorf("Worker.RunOnce - claim job: %w", err) + } + if !claimed { + return "", false, nil + } + if job.Reclaimed { + worker.logger.Info("practice job taken over after its lease expired", + slog.String("submission_id", job.SubmissionID.String()), slog.Int("attempts", job.Attempts)) + } + outcome, err = worker.executor.Execute(ctx, job) + if err != nil { + return outcome, true, fmt.Errorf("Worker.RunOnce - execute job: %w", err) + } + return outcome, true, nil +} + +// Run claims and runs jobs until ctx ends. After a pass that ran a job the +// next claim follows at once; otherwise the worker waits PollInterval, and +// after a database failure Backoff, which grows across consecutive failures. +// A job in progress when ctx ends is given back to the queue unfinished. +func (worker *Worker) Run(ctx context.Context) { + worker.logger.Info("practice queue worker started", + slog.Duration("poll_interval", worker.settings.PollInterval), slog.Duration("lease", worker.settings.Lease)) + defer worker.logger.Info("practice queue worker stopped") + failures := 0 + for ctx.Err() == nil { + outcome, claimed, err := worker.RunOnce(ctx) + var delay time.Duration + switch { + case err != nil && ctx.Err() == nil: + failures++ + delay = worker.settings.Backoff.Delay(failures) + worker.logger.Warn("practice queue pass failed in the database; the job is released or waits for its lease", + slog.Int("consecutive_failures", failures), slog.Duration("retry_in", delay), slog.Any("error", err)) + case claimed: + failures = 0 + worker.logger.Debug("practice job try ended", slog.String("outcome", string(outcome))) + default: + failures = 0 + delay = worker.settings.PollInterval + } + if delay > 0 && !retry.Wait(ctx, delay) { + return + } + } +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 48c797e..2989d9f 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -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. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index e4013ef..03d96c2 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -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. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 3aaff9b..2190aa2 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -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 diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index df10c79..90b9f61 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -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`. Видимость не получила новых запросов: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 28c506a..328ea3c 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -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 прикладных зависимостей сохраняются отдельно. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 35a2119..5f87249 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -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` проверяет значения по умолчанию и отклоняемые значения настроек практики. Тесты не запускают код в песочнице и не доказывают время работы настоящего исполнителя. ## Тесты семантического подбора diff --git a/frontend/src/shared/api/endpoints/assessment/assessment.ts b/frontend/src/shared/api/endpoints/assessment/assessment.ts index cc492da..27bd2ef 100644 --- a/frontend/src/shared/api/endpoints/assessment/assessment.ts +++ b/frontend/src/shared/api/endpoints/assessment/assessment.ts @@ -1194,11 +1194,11 @@ export const useSubmitMyAssessmentAnswer = , * * The practice must be the current item: the attempt is in `practice_pending` for the main practice or `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the server answers 409 state_conflict. * - * Availability. When code practice is not enabled on this server, the server answers 503 service_unavailable and stores nothing. + * Limits. Debug runs are bounded by a per-candidate rate limit and by one unfinished run per practice; either answers 429 rate_limited with Retry-After. The sandbox queue holds one running and ten waiting runs and submissions together; when it is full the server answers 503 service_unavailable with Retry-After and stores nothing. When code practice is not enabled on this server, the server answers 503 service_unavailable without Retry-After and stores nothing. * - * Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in its current state with 202, without starting another run. A different body with the same key answers 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are evaluated again. + * Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in its current state with 202, without starting another run. A different body with the same key answers 422 idempotency_key_reused. Refusals (400, 404, 409, 429, 503) are not stored under the key and are evaluated again. * - * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of another candidate), the state (409), then the solution against the item (400 with a pointer such as `/language` or `/source_code`). + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of another candidate), the state (409), the solution against the item (400 with a pointer such as `/language` or `/source_code`), the limits (429), then the queue (503). * @summary Start a debug run of a practice solution. */ export const createMyAssessmentPracticeRun = async (attemptId: string,