feat(practice): queue practice runs with one running and ten waiting

This commit is contained in:
shira committed 2026-10-11 15:01:07 +03:00
1 parent 51770eea6c
commit 754c745fba
40 files changed
+3040 -70

No files matched your search

+2 -2
View File
@@ -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.
+2 -2
View File
@@ -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`.
+5 -3
View File
@@ -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:
@@ -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: