feat(api): add candidate assessment attempt contract

This commit is contained in:
shira committed 2026-10-06 03:28:44 +03:00
1 parent 6c86c4e559
commit 565ef8d4f5
100 files changed
+30314 -74

No files matched your search

+82 -1
View File
@@ -14,7 +14,7 @@ From the repository root, `make -C api check` checks contracts and `make generat
## Contract conventions
`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation requires Idempotency-Key, but no operation stores keys yet.
`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation and the assessment commands require Idempotency-Key, but no operation stores keys yet.
### Errors
@@ -163,6 +163,80 @@ Questionnaire:
- PUT replaces the whole questionnaire and needs no Idempotency-Key. A body equal to the stored state changes nothing, keeps the version, and answers 200 even with an older `expected_version`, so a retry after a lost response does not fail with 412.
- Order of checks for a save: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), domain rules (400), version (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server.
### Assessment
The `assessment` tag covers the assessment attempts of the current candidate (PRD FR04 and FR05): availability, start and resume, answers including the code practice, finalization, and the result. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`).
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
| `GET /api/v1/me/assessment-availability` | `GetMyAssessmentAvailability` | session | 200 `AssessmentAvailability`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` |
| `POST /api/v1/me/assessment-attempts` | `CreateMyAssessmentAttempt` | session and CSRF, Idempotency-Key | 201 `AssessmentAttempt`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict` or `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
| `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}/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}/finalize` | `FinalizeMyAssessmentAttempt` | 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 |
| `GET /api/v1/me/assessment-attempts/{attempt_id}/result` | `GetMyAssessmentResult` | session | 200 `AssessmentResult`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found`, 409 `state_conflict` |
Every operation also declares the `default` problem response.
Access:
- The candidate comes only from the session; no operation takes a candidate identifier. An employer account answers 403 `forbidden`. An attempt of another candidate answers 404 `not_found`, the same as an unknown identifier, so attempt identifiers cannot be probed.
- No operation offers an employer the answers, the attempt history, or anti-cheat signals. Employers will see only the current category through a separate projection.
Modes and versions:
- `mode` is `demo_basic` or `adaptive`. The server picks it from the published bank of the category; the client never sends it. `demo_basic` scores a fixed form of reviewed demo items by their keys against the pass mark of the versioned basic grading policy, computes no ability estimate, and decides in one step: it never offers an additional practice. `adaptive` is the adaptive test of FR04.
- Creation fixes `versions`: `policy_version` (the number of the `product` policy version), `bank_version`, and `algorithm_version`. The attempt and its result keep them, so a result is reproduced from the stored answers and these versions, and a later version never rewrites it.
- The attempt `version` advances by exactly one with each committed change, including server-side transitions such as a verdict, a session start, expiry, or automatic finalization; a transition applied when the attempt is read is committed first and also advances it.
Attempt lifecycle, with the commands each state accepts:
| State | Meaning | Accepts |
| --- | --- | --- |
| `in_progress` | Items are being answered; `current_item` is the item to answer | an answer to `current_item` |
| `practice_pending` | The item part is done; the main practice has no finished verdict (not submitted, `pending`, or `failed`) | a practice solution while it is `not_started` or `failed` |
| `additional_practice_pending` | Adaptive only: finalize found the probability in the band below confirmation and offered one additional practice in the same attempt | the additional practice solution while it is `not_started` or `failed`; finalize in the same statuses declines the offer |
| `ready_to_finalize` | Every required part is done | finalize |
| `completed` | A decision was made; the result is available | only the repeat of finalize |
| `expired` | The time or session limit passed before the candidate finished; the result confirms no grade | none |
| `insufficient_bank` | The bank could not cover the blueprint within the limit; the result confirms no grade | none |
- Additional practice (PRD FR04): with 0.50 <= P_G < 0.80 in the demo policy, the first finalize of an adaptive attempt completes nothing. It appends a practice of kind `additional` to `practices`, moves the attempt to `additional_practice_pending`, and returns the attempt. The practice continues the same attempt, keeps its time and session limits, and spends no new attempt. The next finalize after its verdict decides; P_G still below 0.80 gives `not_confirmed`. Finalizing without submitting it declines the offer with the same outcome. `practices` is a list with a `kind` rather than one more nullable field, so later practice kinds stay additive.
- Finalize therefore always answers with `AssessmentAttempt`, never with a result or a `oneOf` of both. When the state is `completed`, the client reads `GetMyAssessmentResult`. One response type keeps generated clients unambiguous and leaves room for non-terminal decisions without a breaking change.
- Limits: `expires_at` and `sessions` (`used`, `max`, `idle_timeout_seconds`, null when the policy defines no session limit) come from the policy version; PRD FR04 allows two sessions within 72 hours. Creation starts session 1. A read or command on the active attempt after `idle_timeout_seconds` without one starts the next session; one beyond `max` starts none, and the attempt becomes `expired`. Reading a terminal attempt or a result never starts a session.
- At the limits: a practice already `pending` is graded first. Then `ready_to_finalize` is finalized by the server and becomes `completed`, an unsubmitted additional practice is declined (`completed`, `not_confirmed`), and `in_progress` and `practice_pending` become `expired`. A finalize after that answers 200 with the `completed` attempt; any other command answers 409 `state_conflict`.
- Insufficient bank is a distinct state in two places. Before the start, `GetMyAssessmentAvailability` shows `insufficient_bank` for a grade without a published bank or without enough families that this candidate has not seen, and `CreateMyAssessmentAttempt` answers 409 `state_conflict` without creating anything. During an attempt, the terminal state `insufficient_bank` ends it without a confirmed grade instead of repeating families.
- No new problem code is added, so TASK-157 gets 409 `state_conflict` plus the availability status instead of a `bank_unavailable` code. The `ProblemCode` enum is copied byte-for-byte into the ML contract (`test_contract_copies.py`), so a new code would also change the ML contract and its generated models. The availability read also tells the client why an attempt cannot start and, for `cooldown`, from when, which a fixed problem detail cannot carry.
- Availability shows the limits of each grade before the start: `time_limit_seconds`, `max_sessions`, `max_items`, and `practice_required`, null when unknown.
- Counting against the retry rules (3 attempts per 180 days, the 30-day same-grade interval): an attempt that ends `not_determined` with the reason `expired` or `practice_incomplete` is the candidate's attempt and counts. `insufficient_bank` and `sandbox_unavailable` are platform faults: they never count and start no interval. After a failure, including the first test, a lower grade can be tested at once.
Items and answers:
- An item has an `id` (the instance), `sequence`, a plain-text `prompt`, and `content` (`ItemContent`) in one of the formats `choice`, `number`, `string`, `order`, `find_error`, `configuration`, and `practice`. It never contains an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check, and seed items look like scored ones. `multiple`, `max_selections`, and `max_length` are properties of the format or the task family and never derived from the key. The variant is fixed when first served, so a reload, a retry, or a resumed session returns the same instance.
- 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.
- 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.
Commands, retries, and versions:
- Create, answer, and finalize require Idempotency-Key with the 24-hour replay described above, so a repeated command returns the same outcome. Answers and finalize also carry `expected_version`, the attempt `version` the client read. Creation has no version to compare and relies on the key; the single active attempt per specialization is enforced by the state.
- Each item accepts one answer. Sending the stored answer again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Equality is defined per format: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice. A different answer for an answered item answers 409 `state_conflict` with the current version; with a stale version the version check comes first and answers 412.
- Exception: a practice whose latest verdict is `failed` is outside the repeat rule. A submission with the same or a different solution and the current version queues it again and advances the version.
- Finalizing a `completed` attempt answers 200 with that attempt, so the result is computed once. A retry of the finalize that offered an additional practice, sent with a new key, carries the old version and answers 412, so it never declines the offer by accident.
- A stale `expected_version` answers 412 `version_conflict`, not 409. This deviates from the wording of the TASK-155 test step and of TASK-152, which say 409. It keeps the repository rule above and the questionnaire precedent: `version_conflict` is 412 for If-Match and for a body `expected_version` alike, because the client action is the same, to read the resource again. 409 `state_conflict` is kept for a command that the attempt state does not allow at the current version: the item is not current or has another answer, the attempt is terminal or past its limits, a practice verdict is pending, or the attempt is not ready to finalize. The two codes therefore lead to different client actions.
- A premature finalize answers 409 `state_conflict` without listing the unfinished items, because `Problem` allows no extension fields. The client reads them from the attempt: `state`, `progress`, `current_item`, and `practices`.
- Order of checks for a command: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), the Idempotency-Key (422, 409 `idempotency_in_progress`, replay), the attempt (404, after any due transition), the repeat of a stored answer or of finalize on a completed attempt (200), the version (412), the state (409 `state_conflict`), then domain rules (400 with pointers such as `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 `state_conflict` are stored under the key and replayed, while 400, including domain rules, 412, 429, and 5xx are not. Create and answers are rate-limited (429 with `Retry-After`), which also limits sandbox load. `TestAssessmentSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server.
Result:
- `GetMyAssessmentResult` answers for a terminal attempt and 409 `state_conflict` for an active one, including `additional_practice_pending`. `outcome` is `confirmed`, `not_confirmed`, or `not_determined` with `not_determined_reason` (`expired`, `practice_incomplete`, `insufficient_bank`, `sandbox_unavailable`). A result never lowers a confirmed grade: `previous_confirmed_grade` stays in force when the attempt confirmed nothing.
- `calibration_status` and `limitations` describe the method. Fields that the method does not compute are null, never zero: `demo_basic` has null `uncertainty` and `strength`, and `adaptive` has null `basic_score`. `uncertainty` holds `theta`, `standard_error`, `interval_95`, and `p_grade`. `practices` lists the verdicts by kind. `durations` is a separate label and never enters the decision.
- `next_steps` come from the server: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (the command is planned), and `take_higher_grade`. A first confirmation is not a promotion, so `take_higher_grade` after it has a null `available_at`; after a promotion the next one waits for the 90-day promotion interval.
- The result never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals.
Planned, additive: a short approach description of up to 1500 characters next to the practice, which never decides the grade (PRD FR05); the debug run operation of the practice; the notice and storage of the anti-cheat signals (time, focus changes, pastes, parallel sessions), which lead to a review and an appeal, never to a public label and never to the employer (PRD FR05).
### Generator checks
`testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core.
@@ -190,4 +264,11 @@ Known generator limitations:
- Orval Zod schemas ignore `uniqueItems` and do not reject unknown fields of `additionalProperties: false` objects; the server stays authoritative for both.
- Orval clears `src/shared/api/endpoints/` and `src/shared/api/schemas/` before generation (`clean: true`), because a schema used by several tags moves from a tag directory to the schema root.
#### Format unions
- Format unions such as `ItemContent` and `AssessmentAnswer` are `oneOf` without a `discriminator` object. Redocly resolves `discriminator.mapping` values as references, and `scripts/merge-schemas.py` rewrites only `$ref`, so a mapping in a split schema file cannot resolve in the merged `components/schemas.yml`. Every variant fixes `format` with a one-value enum; ogen discriminates by that value and by the fields unique to a variant and rejects a body that matches several variants, and Orval generates a Zod union.
- Orval names the constants of an inline property `<Schema><Property>`, so a property name that repeats another schema name collides in `index.ts` (TS2308). The union of item formats is therefore `ItemContent`, not `AssessmentItemContent`, next to the `AssessmentItem.content` property.
Generated Zod is not strict. A body that mixes the fields of two formats or carries an extra `score` or `seed` is accepted after unknown keys are silently stripped, and `uniqueItems` is not checked; only the server rejects such bodies. `frontend/src/shared/api/assessment-contract.test.ts` pins the accepted formats and that no answer or item DTO has a score, key, seed, or correctness field.
See the [development guide](../docs/en/DEVELOPMENT.md).
+82 -1
View File
@@ -14,7 +14,7 @@
## Соглашения контракта
`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение бизнес-операций; объявленная операция `RegisterAccount` требует Idempotency-Key, но ни одна операция пока не хранит ключи.
`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение бизнес-операций; объявленная операция `RegisterAccount` и команды оценки требуют Idempotency-Key, но ни одна операция пока не хранит ключи.
### Ошибки
@@ -163,6 +163,80 @@ ML-сервис отвечает на ошибки той же схемой `Pro
- PUT заменяет анкету целиком, и Idempotency-Key ему не нужен. Тело, равное сохраненному состоянию, ничего не меняет, сохраняет версию и дает 200 даже со старым `expected_version`, поэтому повтор после потерянного ответа не падает с 412.
- Порядок проверок при сохранении: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), доменные правила (400), версия (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер.
### Оценка
Тег `assessment` описывает попытки оценки текущего кандидата (FR04 и FR05 в PRD): доступность, старт и возобновление, ответы вместе с кодовой практикой, завершение и результат. Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`).
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
| `GET /api/v1/me/assessment-availability` | `GetMyAssessmentAvailability` | сессия | 200 `AssessmentAvailability`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` |
| `POST /api/v1/me/assessment-attempts` | `CreateMyAssessmentAttempt` | сессия и CSRF, Idempotency-Key | 201 `AssessmentAttempt`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 409 `state_conflict` или `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
| `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}/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}/finalize` | `FinalizeMyAssessmentAttempt` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422 |
| `GET /api/v1/me/assessment-attempts/{attempt_id}/result` | `GetMyAssessmentResult` | сессия | 200 `AssessmentResult`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found`, 409 `state_conflict` |
Каждая операция также объявляет problem-ответ `default`.
Доступ:
- Кандидат берется только из сессии; ни одна операция не принимает идентификатор кандидата. Аккаунт работодателя получает 403 `forbidden`. Попытка другого кандидата дает 404 `not_found`, как и неизвестный идентификатор, поэтому идентификаторы попыток нельзя перебирать.
- Ни одна операция не дает работодателю ответы, историю попыток или античит-сигналы. Работодатель будет видеть только текущую категорию через отдельную проекцию.
Режимы и версии:
- `mode` - это `demo_basic` или `adaptive`. Сервер выбирает его по опубликованному банку категории; клиент режим не передает. `demo_basic` оценивает фиксированную форму проверенных демо-заданий по их ключам относительно проходного балла версионированной базовой политики, не вычисляет оценку способности и решает за один шаг: дополнительную практику он не предлагает. `adaptive` - адаптивный тест из FR04.
- Создание фиксирует `versions`: `policy_version` (номер версии политики `product`), `bank_version` и `algorithm_version`. Попытка и ее результат хранят их, поэтому результат воспроизводится по сохраненным ответам и этим версиям, а более поздняя версия его не переписывает.
- `version` попытки растет ровно на единицу с каждым зафиксированным изменением, включая серверные переходы: вердикт, начало сессии, истечение, автоматическое завершение. Переход, примененный при чтении попытки, фиксируется до ответа и тоже увеличивает версию.
Жизненный цикл попытки и команды, которые принимает каждое состояние:
| Состояние | Значение | Принимает |
| --- | --- | --- |
| `in_progress` | Идут ответы на задания; `current_item` - задание, на которое нужно ответить | ответ на `current_item` |
| `practice_pending` | Задания пройдены; у основной практики нет готового вердикта (не отправлена, `pending` или `failed`) | решение практики, пока она `not_started` или `failed` |
| `additional_practice_pending` | Только adaptive: завершение нашло вероятность в полосе ниже подтверждения и предложило одну дополнительную практику в той же попытке | решение дополнительной практики, пока она `not_started` или `failed`; завершение в тех же статусах отклоняет предложение |
| `ready_to_finalize` | Все обязательные части выполнены | завершение |
| `completed` | Решение принято; результат доступен | только повтор завершения |
| `expired` | Лимит времени или сессий истек раньше, чем кандидат закончил; результат не подтверждает грейд | ничего |
| `insufficient_bank` | Банк не смог обеспечить покрытие в пределах лимита; результат не подтверждает грейд | ничего |
- Дополнительная практика (FR04 в PRD): при 0.50 <= P_G < 0.80 в демо-политике первое завершение adaptive-попытки ничего не решает. Оно добавляет в `practices` практику вида `additional`, переводит попытку в `additional_practice_pending` и возвращает попытку. Практика продолжает ту же попытку, сохраняет ее лимиты времени и сессий и не расходует новую попытку. Следующее завершение после ее вердикта принимает решение; если P_G остается ниже 0.80, итог `not_confirmed`. Завершение без отправки практики отклоняет предложение с тем же итогом. `practices` - список с полем `kind`, а не еще одно nullable-поле, поэтому новые виды практики добавляются без ломающих изменений.
- Поэтому завершение всегда отвечает `AssessmentAttempt`, а не результатом и не `oneOf` из двух схем. Когда состояние `completed`, клиент читает `GetMyAssessmentResult`. Один тип ответа делает сгенерированные клиенты однозначными и оставляет место для незавершающих решений без ломающих изменений.
- Лимиты: `expires_at` и `sessions` (`used`, `max`, `idle_timeout_seconds`; null, если политика не задает лимит сессий) берутся из версии политики; FR04 в PRD допускает две сессии в пределах 72 часов. Создание начинает сессию 1. Чтение или команда по активной попытке после `idle_timeout_seconds` без них начинает следующую сессию; сессия сверх `max` не начинается, и попытка становится `expired`. Чтение терминальной попытки или результата сессию не начинает.
- При достижении лимитов практика в статусе `pending` сначала оценивается. Затем сервер сам завершает `ready_to_finalize` и переводит в `completed`, неотправленная дополнительная практика считается отклоненной (`completed`, `not_confirmed`), а `in_progress` и `practice_pending` становятся `expired`. Завершение после этого дает 200 с попыткой в `completed`; любая другая команда дает 409 `state_conflict`.
- Недостаточный банк - отдельное состояние в двух местах. До старта `GetMyAssessmentAvailability` показывает `insufficient_bank` для грейда без опубликованного банка или без достаточного числа семейств, которых кандидат еще не видел, а `CreateMyAssessmentAttempt` отвечает 409 `state_conflict` и ничего не создает. Во время попытки терминальное состояние `insufficient_bank` завершает ее без подтвержденного грейда вместо повтора семейств.
- Новый код проблемы не добавлен, поэтому TASK-157 получает 409 `state_conflict` и статус доступности вместо кода `bank_unavailable`. Перечисление `ProblemCode` побайтно скопировано в ML-контракт (`test_contract_copies.py`), поэтому новый код изменил бы и ML-контракт, и его сгенерированные модели. Чтение доступности к тому же объясняет клиенту, почему попытка не может начаться, и для `cooldown` - с какого момента; фиксированный detail проблемы этого передать не может.
- Доступность показывает лимиты каждого грейда до старта: `time_limit_seconds`, `max_sessions`, `max_items` и `practice_required`; null, если значение неизвестно.
- Учет в правилах повтора (3 попытки за 180 дней, 30 дней до повтора того же грейда): попытка с итогом `not_determined` по причине `expired` или `practice_incomplete` - попытка кандидата и учитывается. `insufficient_bank` и `sandbox_unavailable` - сбои платформы: они не учитываются и не запускают интервал. После неудачи, включая первый тест, меньший грейд можно проверить сразу.
Задания и ответы:
- У задания есть `id` (экземпляр), `sequence`, `prompt` простым текстом и `content` (`ItemContent`) в одном из форматов `choice`, `number`, `string`, `order`, `find_error`, `configuration` и `practice`. Оно никогда не содержит ключ ответа, правильный вариант, балл, идентификатор семейства или варианта, seed или скрытую проверку, а посевные задания выглядят так же, как оцениваемые. `multiple`, `max_selections` и `max_length` - свойства формата или семейства заданий и никогда не выводятся из ключа. Вариант фиксируется при первой выдаче, поэтому перезагрузка, повтор запроса и возобновление сессии возвращают тот же экземпляр.
- Ответ (`AssessmentAnswer`) имеет те же семь форматов и несет только ответ. Неизвестные поля вроде `score`, `duration` или `seed` дают 400. Сервер сам записывает время и оценивает ответ по ключу экземпляра задания; время не входит в решение о грейде. Ответы API никогда не сообщают, был ли ответ правильным.
- Решение практики исполняется в песочнице асинхронно на трех группах скрытых проверок; клиент опрашивает попытку, пока оно `pending`. Вердикт показывает только балл 0-3 и прохождение каждой группы. Любой исход, вызванный самим решением (ошибка компиляции или выполнения, лимит времени или памяти), - это `finished` с непройденными группами. `failed` (`sandbox_busy` или `sandbox_error`) означает только, что инфраструктура не смогла исполнить решение; он ничего не расходует. Так `failed` не становится оракулом для скрытых проверок и не дает бесконечных повторов. После `finished` другое решение не принимается.
- Если к истечению лимита последняя отправка все еще `failed`, результат - `not_determined` с причиной `sandbox_unavailable`. Неотправленная практика дает `practice_incomplete`.
- Попытка бывает без практики только в `demo_basic`, пока кодовая практика выключена до проверки изоляции песочницы; результат тогда содержит ограничение `practice_not_included`.
Команды, повторы и версии:
- Создание, ответ и завершение требуют Idempotency-Key с 24-часовым повтором, описанным выше, поэтому повтор команды возвращает тот же исход. Ответ и завершение также передают `expected_version` - прочитанную клиентом `version` попытки. У создания нет версии для сравнения, оно опирается на ключ; единственную активную попытку по специализации обеспечивает состояние.
- Каждое задание принимает один ответ. Повторная отправка сохраненного ответа, даже с новым ключом или старым `expected_version`, ничего не сохраняет, не меняет версию и дает 200 с текущей попыткой. Равенство определено для каждого формата: множества для `option_ids` и `line_numbers`, точная последовательность для `element_ids`, числовое равенство для `number`, совпадение текста без нормализации для `text` и `config`, тот же язык и совпадающий исходный код для практики. Другой ответ на уже отвеченное задание дает 409 `state_conflict` при текущей версии; при устаревшей версии ее проверка идет раньше и дает 412.
- Исключение: практика, последний вердикт которой `failed`, не подпадает под правило повтора. Отправка того же или другого решения с текущей версией снова ставит его в очередь и увеличивает версию.
- Завершение попытки в `completed` дает 200 с этой попыткой, поэтому результат вычисляется один раз. Повтор завершения, которое предложило дополнительную практику, с новым ключом несет старую версию и получает 412, поэтому он не может случайно отклонить предложение.
- Устаревший `expected_version` дает 412 `version_conflict`, а не 409. Это отступление от формулировки шага проверки TASK-155 и TASK-152, где указан 409. Так сохраняется правило репозитория выше и прецедент анкеты: `version_conflict` - это 412 и для If-Match, и для `expected_version` в теле, потому что действие клиента одно - прочитать ресурс снова. 409 `state_conflict` оставлен для команды, которую состояние попытки не допускает при текущей версии: задание не текущее или уже имеет другой ответ, попытка терминальная или вышла за лимиты, вердикт практики еще не готов или попытка не готова к завершению. Поэтому два кода ведут к разным действиям клиента.
- Преждевременное завершение дает 409 `state_conflict` без перечня незавершенных заданий, потому что `Problem` не допускает дополнительных полей. Клиент берет их из попытки: `state`, `progress`, `current_item` и `practices`.
- Порядок проверок команды: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), Idempotency-Key (422, 409 `idempotency_in_progress`, повтор), попытка (404, после всех назревших переходов), повтор сохраненного ответа или завершения завершенной попытки (200), версия (412), состояние (409 `state_conflict`), затем доменные правила (400 с pointer вроде `/answer/option_ids/0`). По соглашению об Idempotency-Key 404 и 409 `state_conflict` сохраняются под ключом и повторяются, а 400 (включая доменные правила), 412, 429 и 5xx - нет. Создание и ответы ограничены по частоте (429 с `Retry-After`), что ограничивает и нагрузку на песочницу. `TestAssessmentSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер.
Результат:
- `GetMyAssessmentResult` отвечает для терминальной попытки и дает 409 `state_conflict` для активной, включая `additional_practice_pending`. `outcome` - это `confirmed`, `not_confirmed` или `not_determined` с `not_determined_reason` (`expired`, `practice_incomplete`, `insufficient_bank`, `sandbox_unavailable`). Результат никогда не понижает подтвержденный грейд: если попытка ничего не подтвердила, действует `previous_confirmed_grade`.
- `calibration_status` и `limitations` описывают метод. Поля, которые метод не вычисляет, равны null, а не нулю: у `demo_basic` null в `uncertainty` и `strength`, у `adaptive` - null в `basic_score`. `uncertainty` содержит `theta`, `standard_error`, `interval_95` и `p_grade`. `practices` перечисляет вердикты по видам. `durations` - отдельная метка, которая не входит в решение.
- `next_steps` приходят с сервера: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (команда запланирована) и `take_higher_grade`. Первое подтверждение - не повышение, поэтому `take_higher_grade` после него имеет null в `available_at`; после повышения следующее ждет 90-дневный интервал повышения.
- Результат никогда не содержит ответы, правильность отдельных заданий, ключи, seed, скрытые проверки или античит-сигналы.
Запланировано, добавляется без ломающих изменений: краткое описание подхода до 1500 знаков рядом с практикой, которое не определяет грейд (FR05 в PRD); операция отладочных запусков практики; уведомление о собираемых античит-сигналах (время, переключение фокуса, вставки, параллельные сессии) и их хранение; сигналы ведут к перепроверке и апелляции, а не к публичному ярлыку, и работодателю не показываются (FR05 в PRD).
### Проверки генераторов
`testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core.
@@ -190,4 +264,11 @@ ML-сервис отвечает на ошибки той же схемой `Pro
- Zod-схемы Orval игнорируют `uniqueItems` и не отклоняют неизвестные поля объектов с `additionalProperties: false`; в обоих случаях решает сервер.
- Orval очищает `src/shared/api/endpoints/` и `src/shared/api/schemas/` перед генерацией (`clean: true`), потому что схема, используемая несколькими тегами, переезжает из каталога тега в корень схем.
#### Объединения форматов
- Объединения форматов, например `ItemContent` и `AssessmentAnswer`, - это `oneOf` без объекта `discriminator`. Redocly разрешает значения `discriminator.mapping` как ссылки, а `scripts/merge-schemas.py` переписывает только `$ref`, поэтому mapping из отдельного файла схем не разрешается в объединенном `components/schemas.yml`. Каждый вариант фиксирует `format` перечислением из одного значения; ogen различает варианты по этому значению и по полям, уникальным для варианта, и отклоняет тело, подходящее под несколько вариантов, а Orval генерирует Zod-объединение.
- Orval называет константы встроенного свойства `<Schema><Property>`, поэтому имя свойства, повторяющее имя другой схемы, дает конфликт в `index.ts` (TS2308). Поэтому объединение форматов задания называется `ItemContent`, а не `AssessmentItemContent`, рядом со свойством `AssessmentItem.content`.
Сгенерированный Zod не строгий. Тело, смешивающее поля двух форматов или содержащее лишние `score` или `seed`, принимается после молчаливого удаления неизвестных ключей, а `uniqueItems` не проверяется; такие тела отклоняет только сервер. `frontend/src/shared/api/assessment-contract.test.ts` закрепляет принимаемые форматы и отсутствие в DTO ответа и задания полей балла, ключа, seed или правильности.
Подробнее: [разработка](../docs/ru/DEVELOPMENT.md).
+916
View File
@@ -425,3 +425,919 @@ QuestionnaireRepeatedSpecialization:
pointer: /specializations/1/specialization
code: invalid
message: The value does not match the contract.
AssessmentAvailability:
summary: Backend open in demo_basic, Network Engineer blocked
description: >-
Illustrative values. Backend junior and middle can start in the
demo_basic mode, with their limits shown before the start; intern and
senior have no sufficient bank. Network Engineer junior waits for its
same-grade retry interval after an unconfirmed attempt.
value:
specializations:
- specialization: backend
confirmed_grade: null
active_attempt_id: null
grades:
- grade: intern
status: insufficient_bank
mode: null
available_at: null
time_limit_seconds: null
max_sessions: null
max_items: null
practice_required: null
- grade: junior
status: available
mode: demo_basic
available_at: null
time_limit_seconds: 259200
max_sessions: 2
max_items: 12
practice_required: false
- grade: middle
status: available
mode: demo_basic
available_at: null
time_limit_seconds: 259200
max_sessions: 2
max_items: 12
practice_required: false
- grade: senior
status: insufficient_bank
mode: null
available_at: null
time_limit_seconds: null
max_sessions: null
max_items: null
practice_required: null
- specialization: network_engineer
confirmed_grade: null
active_attempt_id: null
grades:
- grade: intern
status: insufficient_bank
mode: null
available_at: null
time_limit_seconds: null
max_sessions: null
max_items: null
practice_required: null
- grade: junior
status: cooldown
mode: demo_basic
available_at: "2026-11-12T00:00:00Z"
time_limit_seconds: 259200
max_sessions: 2
max_items: 10
practice_required: false
- grade: middle
status: available
mode: demo_basic
available_at: null
time_limit_seconds: 259200
max_sessions: 2
max_items: 10
practice_required: false
- grade: senior
status: insufficient_bank
mode: null
available_at: null
time_limit_seconds: null
max_sessions: null
max_items: null
practice_required: null
AssessmentAttemptCreateBackendJunior:
summary: Start Backend junior with Go tasks
value:
specialization: backend
target_grade: junior
task_language: go
AssessmentAttemptCreated:
summary: New demo_basic attempt with its first item
description: >-
The server chose demo_basic from the published bank and fixed the policy,
bank, and algorithm versions; creation started session 1. A retry of
this create with the same Idempotency-Key and body within 24 hours
replays exactly this 201 response and creates nothing; read the attempt
for its current state. The attempt has no practice, because code
practice stays disabled until the sandbox isolation is verified.
value:
id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b
version: 1
specialization: backend
target_grade: junior
task_language: go
mode: demo_basic
state: in_progress
versions:
policy_version: 1
bank_version: backend-demo.2026-10.1
algorithm_version: basic-raw-score.1
started_at: "2026-10-08T10:00:00Z"
expires_at: "2026-10-11T10:00:00Z"
sessions:
used: 1
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 0
max_items: 12
current_item:
id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01
sequence: 1
prompt: "Какой HTTP-статус вернуть, если запрос валиден, но ресурс находится в состоянии, не допускающем операцию?"
content:
format: choice
multiple: false
options:
- id: k7
text: "400"
- id: p2
text: "404"
- id: x9
text: "409"
- id: c4
text: "500"
practices: []
AssessmentAnswerAccepted:
summary: Answer to item 1 stored; item 2 follows
description: >-
The answer of AssessmentChoiceAnswer was stored and the version advanced
from 1 to 2. The response does not say whether the answer was correct.
A retry with the same Idempotency-Key replays exactly this response.
Sending the same answer to item 1 again, even with a new key or the
older expected_version 1, stores nothing and returns 200 with the
current attempt. AssessmentOrderAnswer answers item 2 next.
value:
id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b
version: 2
specialization: backend
target_grade: junior
task_language: go
mode: demo_basic
state: in_progress
versions:
policy_version: 1
bank_version: backend-demo.2026-10.1
algorithm_version: basic-raw-score.1
started_at: "2026-10-08T10:00:00Z"
expires_at: "2026-10-11T10:00:00Z"
sessions:
used: 1
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 1
max_items: 12
current_item:
id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02
sequence: 2
prompt: "Упорядочите шаги обработки запроса в обработчике HTTP."
content:
format: order
elements:
- id: d3
text: Записать ответ
- id: a7
text: Проверить сессию
- id: c2
text: Выполнить операцию
- id: b1
text: Разобрать и проверить тело
practices: []
AssessmentAttemptCompleted:
summary: demo_basic attempt finalized; read the result next
value:
id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b
version: 14
specialization: backend
target_grade: junior
task_language: go
mode: demo_basic
state: completed
versions:
policy_version: 1
bank_version: backend-demo.2026-10.1
algorithm_version: basic-raw-score.1
started_at: "2026-10-08T10:00:00Z"
expires_at: "2026-10-11T10:00:00Z"
sessions:
used: 1
max: 2
idle_timeout_seconds: 1800
finished_at: "2026-10-08T10:24:00Z"
progress:
answered_items: 12
max_items: 12
current_item: null
practices: []
AssessmentAttemptResumed:
summary: Adaptive attempt resumed on its sixth item in session 2
description: >-
A reload or a new session returns the same item instance with the same
lines; nothing tells whether the five earlier answers were correct, and
seed items look like scored ones. The retest started from the previous
ability estimate of the specialization.
value:
id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
version: 7
specialization: backend
target_grade: middle
task_language: python
mode: adaptive
state: in_progress
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
started_at: "2026-11-20T09:00:00Z"
expires_at: "2026-11-23T09:00:00Z"
sessions:
used: 2
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 5
max_items: 25
current_item:
id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c06
sequence: 6
prompt: "Найдите строку, из-за которой соединения с базой данных не возвращаются в пул."
content:
format: find_error
syntax: python
max_selections: 1
lines:
- number: 1
text: "def load_user(pool, user_id):"
- number: 2
text: " conn = pool.acquire()"
- number: 3
text: " row = conn.fetchrow(QUERY, user_id)"
- number: 4
text: " if row is None:"
- number: 5
text: " raise NotFound(user_id)"
- number: 6
text: " pool.release(conn)"
- number: 7
text: " return row"
practices:
- kind: main
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
status: not_started
submitted_at: null
verdict: null
failure_reason: null
AssessmentAttemptPracticePending:
summary: Item part finished, main practice not submitted
description: >-
The adaptive stop rule ended the item part after 14 items, but no grade
is decided until the main practice has a finished verdict. The current
item is the practice; hidden checks and seeds are not part of it.
value:
id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
version: 16
specialization: backend
target_grade: middle
task_language: python
mode: adaptive
state: practice_pending
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
started_at: "2026-11-20T09:00:00Z"
expires_at: "2026-11-23T09:00:00Z"
sessions:
used: 2
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 14
max_items: 25
current_item:
id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
sequence: 15
prompt: "Реализуйте функцию merge_intervals: на вход список пар [start, end], на выход объединенные пересекающиеся интервалы, отсортированные по началу."
content:
format: practice
languages: [python]
max_source_length: 20000
public_examples:
- input: "[[1,3],[2,6],[8,10]]"
expected_output: "[[1,6],[8,10]]"
practices:
- kind: main
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
status: not_started
submitted_at: null
verdict: null
failure_reason: null
AssessmentAttemptPracticeVerdictPending:
summary: Practice submitted, verdict pending in the sandbox
value:
id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
version: 17
specialization: backend
target_grade: middle
task_language: python
mode: adaptive
state: practice_pending
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
started_at: "2026-11-20T09:00:00Z"
expires_at: "2026-11-23T09:00:00Z"
sessions:
used: 2
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 14
max_items: 25
current_item: null
practices:
- kind: main
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
status: pending
submitted_at: "2026-11-20T10:05:00Z"
verdict: null
failure_reason: null
AssessmentAttemptSandboxFailed:
summary: Sandbox queue was full; the practice can be submitted again
description: >-
The failure does not depend on the solution and consumes nothing. The
practice item is current again; a resubmission, with the same or a
different solution, queues it again and advances the version.
value:
id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
version: 18
specialization: backend
target_grade: middle
task_language: python
mode: adaptive
state: practice_pending
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
started_at: "2026-11-20T09:00:00Z"
expires_at: "2026-11-23T09:00:00Z"
sessions:
used: 2
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 14
max_items: 25
current_item:
id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
sequence: 15
prompt: "Реализуйте функцию merge_intervals: на вход список пар [start, end], на выход объединенные пересекающиеся интервалы, отсортированные по началу."
content:
format: practice
languages: [python]
max_source_length: 20000
public_examples:
- input: "[[1,3],[2,6],[8,10]]"
expected_output: "[[1,6],[8,10]]"
practices:
- kind: main
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
status: failed
submitted_at: "2026-11-20T10:05:00Z"
verdict: null
failure_reason: sandbox_busy
AssessmentAttemptReadyToFinalize:
summary: Main practice verdict finished, ready to finalize
value:
id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
version: 20
specialization: backend
target_grade: middle
task_language: python
mode: adaptive
state: ready_to_finalize
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
started_at: "2026-11-20T09:00:00Z"
expires_at: "2026-11-23T09:00:00Z"
sessions:
used: 2
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 14
max_items: 25
current_item: null
practices:
- kind: main
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
status: finished
submitted_at: "2026-11-20T10:09:00Z"
verdict:
score: 2
max_score: 3
groups:
- group: 1
passed: true
- group: 2
passed: true
- group: 3
passed: false
failure_reason: null
AssessmentAttemptAdditionalPracticePending:
summary: Finalize offered an additional practice in the same attempt
description: >-
The probability of reaching middle was in the band below confirmation,
so finalize decided nothing yet: it appended an additional practice and
returned the attempt instead of a result. The attempt keeps its time and
session limits and spends no new attempt. Submitting the additional
practice leads back to ready_to_finalize; finalizing now declines it
and gives not_confirmed. A retry of that finalize with a new key and
the old expected_version 20 answers 412 and cannot decline by accident.
value:
id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
version: 21
specialization: backend
target_grade: middle
task_language: python
mode: adaptive
state: additional_practice_pending
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
started_at: "2026-11-20T09:00:00Z"
expires_at: "2026-11-23T09:00:00Z"
sessions:
used: 2
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 14
max_items: 25
current_item:
id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8ca0
sequence: 16
prompt: "Реализуйте LRU-кеш с операциями get и put за O(1)."
content:
format: practice
languages: [python]
max_source_length: 20000
public_examples:
- input: "put(1,1); put(2,2); get(1); put(3,3); get(2)"
expected_output: "1, -1"
practices:
- kind: main
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
status: finished
submitted_at: "2026-11-20T10:09:00Z"
verdict:
score: 2
max_score: 3
groups:
- group: 1
passed: true
- group: 2
passed: true
- group: 3
passed: false
failure_reason: null
- kind: additional
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8ca0
status: not_started
submitted_at: null
verdict: null
failure_reason: null
AssessmentAttemptInsufficientBank:
summary: Attempt ended because the bank could not cover the blueprint
description: >-
The bank ran out of unseen families for a required domain within the
item limit. The attempt ended without a confirmed grade instead of
repeating a family; its result has outcome not_determined, and it does
not count against the retry rules.
value:
id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d
version: 10
specialization: network_engineer
target_grade: middle
task_language: null
mode: adaptive
state: insufficient_bank
versions:
policy_version: 2
bank_version: network.2026-11.1
algorithm_version: irt-1pl-eap.1
started_at: "2026-11-21T12:00:00Z"
expires_at: "2026-11-24T12:00:00Z"
sessions:
used: 1
max: 2
idle_timeout_seconds: 1800
finished_at: "2026-11-21T12:31:00Z"
progress:
answered_items: 8
max_items: 25
current_item: null
practices:
- kind: main
item_id: 01928f7c-6666-7a2b-8c3d-4e5f6a7b8c99
status: not_started
submitted_at: null
verdict: null
failure_reason: null
AssessmentChoiceAnswer:
summary: Answer item 1 of version 1
value:
expected_version: 1
item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01
answer:
format: choice
option_ids: [x9]
AssessmentOrderAnswer:
summary: Answer item 2 with every element once
value:
expected_version: 2
item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02
answer:
format: order
element_ids: [a7, b1, c2, d3]
AssessmentNumberAnswer:
summary: Number answer
value:
expected_version: 3
item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d03
answer:
format: number
number: 254
AssessmentStringAnswer:
summary: String answer
value:
expected_version: 4
item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d04
answer:
format: string
text: Retry-After
AssessmentFindErrorAnswer:
summary: Find-error answer for the resumed item
value:
expected_version: 7
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c06
answer:
format: find_error
line_numbers: [5]
AssessmentConfigurationAnswer:
summary: Configuration answer
value:
expected_version: 7
item_id: 01928f7c-6666-7a2b-8c3d-4e5f6a7b8c07
answer:
format: configuration
config: |-
interface GigabitEthernet0/1
ip access-group BLOCK_TELNET in
AssessmentPracticeAnswer:
summary: Main practice solution
description: >-
Sent with expected_version 16 for the first submission. After a failed
verdict the client sends it again with the current version, such as 18
in AssessmentAttemptSandboxFailed; the same source then queues again.
value:
expected_version: 16
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
answer:
format: practice
language: python
source_code: |-
def merge_intervals(intervals):
result = []
for start, end in sorted(intervals):
if result and start <= result[-1][1]:
result[-1][1] = max(result[-1][1], end)
else:
result.append([start, end])
return result
AssessmentFinalization:
summary: Finalize version 20
value:
expected_version: 20
AssessmentDemoBasicResult:
summary: demo_basic result with a confirmed grade and no uncertainty
description: >-
demo_basic computes no ability estimate, so `uncertainty` and `strength`
are null rather than zero, and no percentile is shown. The pass mark
comes from basic grading policy version 1, and the limitations name the
uncalibrated thresholds, the demo bank, and the missing practice. A
first confirmation is not a promotion, so the higher grade can be
tested at once. The result never changes; a repeated finalize returns
the completed attempt, and this read returns the same result.
value:
attempt_id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b
specialization: backend
target_grade: junior
task_language: go
mode: demo_basic
versions:
policy_version: 1
bank_version: backend-demo.2026-10.1
algorithm_version: basic-raw-score.1
outcome: confirmed
not_determined_reason: null
confirmed_grade: junior
previous_confirmed_grade: null
strength: null
calibration_status: uncalibrated
limitations:
[uncalibrated_thresholds, demo_bank, practice_not_included, unproctored]
uncertainty: null
basic_score:
points: 9
max_points: 12
pass_points: 8
practices: []
gaps: []
durations:
items_seconds: 1260
practice_seconds: null
next_steps:
- action: take_higher_grade
grade: middle
available_at: null
decided_at: "2026-10-08T10:24:00Z"
AssessmentAdaptiveResult:
summary: Adaptive promotion confirmed with medium strength
description: >-
Illustrative values, continuing AssessmentAttemptAdditionalPracticePending.
The additional practice raised P_G to 0.84, in the medium band of the
policy version, so the grade is confirmed with medium strength. The
candidate already had junior, so this is a
promotion, and the next one waits for the promotion interval. The
thresholds are uncalibrated until the pilot.
value:
attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
specialization: backend
target_grade: middle
task_language: python
mode: adaptive
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
outcome: confirmed
not_determined_reason: null
confirmed_grade: middle
previous_confirmed_grade: junior
strength: medium
calibration_status: uncalibrated
limitations: [uncalibrated_thresholds, unproctored]
uncertainty:
theta: 0.62
standard_error: 0.24
interval_95:
low: 0.15
high: 1.09
p_grade: 0.84
basic_score: null
practices:
- kind: main
verdict:
score: 2
max_score: 3
groups:
- group: 1
passed: true
- group: 2
passed: true
- group: 3
passed: false
- kind: additional
verdict:
score: 3
max_score: 3
groups:
- group: 1
passed: true
- group: 2
passed: true
- group: 3
passed: true
gaps:
- domain: concurrency
title: Конкурентность
durations:
items_seconds: 1980
practice_seconds: 1500
next_steps:
- action: take_higher_grade
grade: senior
available_at: "2027-02-18T10:30:00Z"
decided_at: "2026-11-20T10:30:00Z"
AssessmentNotConfirmedResult:
summary: Adaptive attempt not confirmed after the additional practice
description: >-
P_G stayed below 0.80 after the additional practice, so middle is not
confirmed, and the candidate keeps no confirmed grade. After a failure,
including the first test, junior can be tested at once; accepting junior
on the evidence of this attempt is offered; middle opens again after the
same-grade retry interval.
value:
attempt_id: 01928f7d-7777-7a2b-8c3d-4e5f6a7b8c9d
specialization: backend
target_grade: middle
task_language: go
mode: adaptive
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
outcome: not_confirmed
not_determined_reason: null
confirmed_grade: null
previous_confirmed_grade: null
strength: null
calibration_status: uncalibrated
limitations: [uncalibrated_thresholds, unproctored]
uncertainty:
theta: 0.21
standard_error: 0.25
interval_95:
low: -0.28
high: 0.70
p_grade: 0.62
basic_score: null
practices:
- kind: main
verdict:
score: 1
max_score: 3
groups:
- group: 1
passed: true
- group: 2
passed: false
- group: 3
passed: false
- kind: additional
verdict:
score: 1
max_score: 3
groups:
- group: 1
passed: true
- group: 2
passed: false
- group: 3
passed: false
gaps:
- domain: databases
title: Базы данных
durations:
items_seconds: 2100
practice_seconds: 1800
next_steps:
- action: take_lower_grade
grade: junior
available_at: null
- action: accept_lower_grade
grade: junior
available_at: null
- action: retake_same_grade
grade: middle
available_at: "2026-12-22T11:00:00Z"
decided_at: "2026-11-22T11:00:00Z"
AssessmentInsufficientBankResult:
summary: Attempt without a decision because the bank was insufficient
value:
attempt_id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d
specialization: network_engineer
target_grade: middle
task_language: null
mode: adaptive
versions:
policy_version: 2
bank_version: network.2026-11.1
algorithm_version: irt-1pl-eap.1
outcome: not_determined
not_determined_reason: insufficient_bank
confirmed_grade: null
previous_confirmed_grade: junior
strength: null
calibration_status: uncalibrated
limitations: [uncalibrated_thresholds, unproctored]
uncertainty: null
basic_score: null
practices: []
gaps: []
durations:
items_seconds: 1860
practice_seconds: null
next_steps: []
decided_at: "2026-11-21T12:31:00Z"
AssessmentSpecializationNotInQuestionnaire:
summary: The specialization is not in the questionnaire
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 9f0a1b2c-3d4e-4f5a-8b6c-7d8e9f0a1b2c
errors:
- in: body
pointer: /specialization
code: invalid
message: The value does not match the contract.
AssessmentAnswerUnknownOption:
summary: The selected option does not belong to the item
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 0a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d
errors:
- in: body
pointer: /answer/option_ids/0
code: invalid
message: The value does not match the contract.
AssessmentAnswerUnknownField:
summary: The client sent its own score
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 1b2c3d4e-5f6a-4b7c-8d8e-9f0a1b2c3d4e
errors:
- in: body
pointer: ""
code: invalid
message: The value does not match the contract.
AssessmentItemNotCurrent:
summary: The answered item is not the current item, or it already has another answer
value:
type: urn:lincodex:problem:state_conflict
title: Resource state conflict
status: 409
code: state_conflict
detail: The resource is in a state that does not allow this operation.
trace_id: 2c3d4e5f-6a7b-4c8d-9e9f-0a1b2c3d4e5f
AssessmentFinalizeNotReady:
summary: Premature finalize; the problem does not list the unfinished parts
description: >-
Problem has no extension fields. The client reads what remains from the
attempt: `state`, `progress`, `current_item`, and `practices`.
value:
type: urn:lincodex:problem:state_conflict
title: Resource state conflict
status: 409
code: state_conflict
detail: The resource is in a state that does not allow this operation.
trace_id: 6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9e
AssessmentAttemptNotAvailable:
summary: No attempt can start for the category now
value:
type: urn:lincodex:problem:state_conflict
title: Resource state conflict
status: 409
code: state_conflict
detail: The resource is in a state that does not allow this operation.
trace_id: 3d4e5f6a-7b8c-4d9e-8f0a-1b2c3d4e5f6a
AssessmentResultNotReady:
summary: The attempt has no result yet
value:
type: urn:lincodex:problem:state_conflict
title: Resource state conflict
status: 409
code: state_conflict
detail: The resource is in a state that does not allow this operation.
trace_id: 4e5f6a7b-8c9d-4e0f-9a1b-2c3d4e5f6a7b
AssessmentStaleVersion:
summary: The command carried a stale expected_version
description: >-
Another tab or device changed the attempt after the client read version
1. Nothing was stored; the client reads the attempt again and continues
from its current item. The repository answers a stale version with 412,
not 409.
value:
type: urn:lincodex:problem:version_conflict
title: Resource version conflict
status: 412
code: version_conflict
detail: The resource changed after it was read. Read it again before retrying.
trace_id: 5f6a7b8c-9d0e-4f1a-8b2c-3d4e5f6a7b8c
+12
View File
@@ -56,3 +56,15 @@ PageCursor:
minLength: 1
maxLength: 512
pattern: "^[A-Za-z0-9_-]+$"
AssessmentAttemptId:
name: attempt_id
in: path
required: true
description: >-
Identifier of an assessment attempt of the current candidate. An attempt
of another candidate and an unknown identifier both answer 404
not_found, so identifiers cannot be enumerated.
schema:
type: string
format: uuid
example: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b
+113
View File
@@ -261,3 +261,116 @@ QuestionnaireVersionConflict:
examples:
version_conflict:
$ref: ./examples.yml#/VersionConflict
AssessmentAttemptCreateValidationFailed:
description: >-
The body does not match the contract or violates an assessment rule: an
unknown specialization, grade, or task language, an unknown field such
as mode or seed, a specialization that is not in the questionnaire, or
a task language that the published bank does not offer; code
validation_failed with body pointers. Nothing was created, and the
outcome is not stored under the Idempotency-Key.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
specialization_not_in_questionnaire:
$ref: ./examples.yml#/AssessmentSpecializationNotInQuestionnaire
AssessmentAnswerValidationFailed:
description: >-
The body does not match the contract or the answer does not fit the
item: a format other than the item format, an option, element, or line
that the item does not have, an order that is not a permutation of every
element, more selections than the item allows, a text longer than the
item allows, a language that the practice does not offer, or an unknown
field such as score or duration; code validation_failed with body
pointers. When the decoder does not record the path of a nested field,
the pointer is the whole body. Nothing was stored, and the outcome is
not stored under the Idempotency-Key.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
unknown_option:
$ref: ./examples.yml#/AssessmentAnswerUnknownOption
score_sent_by_client:
$ref: ./examples.yml#/AssessmentAnswerUnknownField
AssessmentCommandConflict:
description: >-
The attempt state does not allow the answer at the current version, code
state_conflict: the attempt is terminal or past its limits, the item is
not the current item, the item already has a different answer, or the
practice has a pending or finished verdict and the submission differs.
Or a request with the same Idempotency-Key is still running, code
idempotency_in_progress. Nothing was changed in either case; read the
attempt to see its state.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
state_conflict:
$ref: ./examples.yml#/AssessmentItemNotCurrent
idempotency_in_progress:
$ref: ./examples.yml#/IdempotencyInProgress
AssessmentFinalizeConflict:
description: >-
The attempt state does not allow finalize at the current version, code
state_conflict: items or the main practice are unfinished, a practice
verdict is pending, or the attempt ended as expired or insufficient_bank.
The problem does not list the unfinished parts, because Problem allows
no extension fields; the attempt shows them in `state`, `progress`,
`current_item`, and `practices`. Or a request with the same
Idempotency-Key is still running, code idempotency_in_progress. Nothing
was changed in either case.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
state_conflict:
$ref: ./examples.yml#/AssessmentFinalizeNotReady
idempotency_in_progress:
$ref: ./examples.yml#/IdempotencyInProgress
AssessmentCreateConflict:
description: >-
No attempt can start for the category now, code state_conflict: the
specialization already has an active attempt, a retry or promotion
interval or the attempt limit blocks the grade, or the bank is
insufficient. GetMyAssessmentAvailability tells which, with the date
when a blocked attempt opens. Or a request with the same Idempotency-Key
is still running, code idempotency_in_progress. Nothing was created in
either case.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
state_conflict:
$ref: ./examples.yml#/AssessmentAttemptNotAvailable
idempotency_in_progress:
$ref: ./examples.yml#/IdempotencyInProgress
AssessmentResultNotReady:
description: >-
The attempt is still active, so it has no result yet; code
state_conflict. The attempt state tells what remains to be done.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
state_conflict:
$ref: ./examples.yml#/AssessmentResultNotReady
AssessmentVersionConflict:
description: >-
`expected_version` is not the current attempt version; code
version_conflict. Nothing was changed, and the outcome is not stored
under the Idempotency-Key; read the attempt again before retrying.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
version_conflict:
$ref: ./examples.yml#/AssessmentStaleVersion
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+147
View File
@@ -21,6 +21,11 @@ tags:
Data of the current candidate, such as the questionnaire with the
chosen specializations and self-assessed grades. Confirmed grades and
categories come only from assessment results.
- name: assessment
description: >-
Assessment attempts of the current candidate: availability, start and
resume, answers and the code practice, finalization, and the result.
Answers, keys, and attempt history are visible only to the candidate.
# Operations require a session unless they declare `security: []`, so a new
# operation that omits security is protected by default.
security:
@@ -46,6 +51,18 @@ paths:
$ref: ./routes/catalog_specializations.yml
/api/v1/me/questionnaire:
$ref: ./routes/candidate_questionnaire.yml
/api/v1/me/assessment-availability:
$ref: ./routes/candidate_assessment_availability.yml
/api/v1/me/assessment-attempts:
$ref: ./routes/candidate_assessment_attempts.yml
/api/v1/me/assessment-attempts/{attempt_id}:
$ref: ./routes/candidate_assessment_attempt.yml
/api/v1/me/assessment-attempts/{attempt_id}/answers:
$ref: ./routes/candidate_assessment_attempt_answers.yml
/api/v1/me/assessment-attempts/{attempt_id}/finalize:
$ref: ./routes/candidate_assessment_attempt_finalize.yml
/api/v1/me/assessment-attempts/{attempt_id}/result:
$ref: ./routes/candidate_assessment_attempt_result.yml
components:
schemas:
Problem:
@@ -134,6 +151,120 @@ components:
$ref: ./components/schemas.yml#/CandidateQuestionnaire
CandidateQuestionnaireUpdate:
$ref: ./components/schemas.yml#/CandidateQuestionnaireUpdate
AssessmentMode:
$ref: ./components/schemas.yml#/AssessmentMode
AssessmentAttemptVersion:
$ref: ./components/schemas.yml#/AssessmentAttemptVersion
AssessmentAttemptState:
$ref: ./components/schemas.yml#/AssessmentAttemptState
AssessmentVersionLabel:
$ref: ./components/schemas.yml#/AssessmentVersionLabel
AssessmentVersions:
$ref: ./components/schemas.yml#/AssessmentVersions
AssessmentSessions:
$ref: ./components/schemas.yml#/AssessmentSessions
AssessmentAttemptCreate:
$ref: ./components/schemas.yml#/AssessmentAttemptCreate
AssessmentItemId:
$ref: ./components/schemas.yml#/AssessmentItemId
AssessmentOptionId:
$ref: ./components/schemas.yml#/AssessmentOptionId
AssessmentOption:
$ref: ./components/schemas.yml#/AssessmentOption
ChoiceItemContent:
$ref: ./components/schemas.yml#/ChoiceItemContent
NumberItemContent:
$ref: ./components/schemas.yml#/NumberItemContent
StringItemContent:
$ref: ./components/schemas.yml#/StringItemContent
OrderItemContent:
$ref: ./components/schemas.yml#/OrderItemContent
CodeLine:
$ref: ./components/schemas.yml#/CodeLine
FindErrorItemContent:
$ref: ./components/schemas.yml#/FindErrorItemContent
ConfigurationItemContent:
$ref: ./components/schemas.yml#/ConfigurationItemContent
PracticeExample:
$ref: ./components/schemas.yml#/PracticeExample
PracticeItemContent:
$ref: ./components/schemas.yml#/PracticeItemContent
ItemContent:
$ref: ./components/schemas.yml#/ItemContent
AssessmentItem:
$ref: ./components/schemas.yml#/AssessmentItem
AssessmentProgress:
$ref: ./components/schemas.yml#/AssessmentProgress
PracticeKind:
$ref: ./components/schemas.yml#/PracticeKind
PracticeStatus:
$ref: ./components/schemas.yml#/PracticeStatus
PracticeFailureReason:
$ref: ./components/schemas.yml#/PracticeFailureReason
PracticeGroupResult:
$ref: ./components/schemas.yml#/PracticeGroupResult
PracticeVerdict:
$ref: ./components/schemas.yml#/PracticeVerdict
AssessmentPractice:
$ref: ./components/schemas.yml#/AssessmentPractice
AssessmentAttempt:
$ref: ./components/schemas.yml#/AssessmentAttempt
ChoiceAnswer:
$ref: ./components/schemas.yml#/ChoiceAnswer
NumberAnswer:
$ref: ./components/schemas.yml#/NumberAnswer
StringAnswer:
$ref: ./components/schemas.yml#/StringAnswer
OrderAnswer:
$ref: ./components/schemas.yml#/OrderAnswer
FindErrorAnswer:
$ref: ./components/schemas.yml#/FindErrorAnswer
ConfigurationAnswer:
$ref: ./components/schemas.yml#/ConfigurationAnswer
PracticeAnswer:
$ref: ./components/schemas.yml#/PracticeAnswer
AssessmentAnswer:
$ref: ./components/schemas.yml#/AssessmentAnswer
AssessmentAnswerSubmission:
$ref: ./components/schemas.yml#/AssessmentAnswerSubmission
AssessmentFinalization:
$ref: ./components/schemas.yml#/AssessmentFinalization
AssessmentOutcome:
$ref: ./components/schemas.yml#/AssessmentOutcome
AssessmentNotDeterminedReason:
$ref: ./components/schemas.yml#/AssessmentNotDeterminedReason
AssessmentStrength:
$ref: ./components/schemas.yml#/AssessmentStrength
CalibrationStatus:
$ref: ./components/schemas.yml#/CalibrationStatus
AssessmentLimitation:
$ref: ./components/schemas.yml#/AssessmentLimitation
AssessmentInterval:
$ref: ./components/schemas.yml#/AssessmentInterval
AssessmentUncertainty:
$ref: ./components/schemas.yml#/AssessmentUncertainty
BasicScore:
$ref: ./components/schemas.yml#/BasicScore
AssessmentGap:
$ref: ./components/schemas.yml#/AssessmentGap
AssessmentDurations:
$ref: ./components/schemas.yml#/AssessmentDurations
AssessmentPracticeResult:
$ref: ./components/schemas.yml#/AssessmentPracticeResult
AssessmentNextAction:
$ref: ./components/schemas.yml#/AssessmentNextAction
AssessmentNextStep:
$ref: ./components/schemas.yml#/AssessmentNextStep
AssessmentResult:
$ref: ./components/schemas.yml#/AssessmentResult
AssessmentGradeAvailabilityStatus:
$ref: ./components/schemas.yml#/AssessmentGradeAvailabilityStatus
AssessmentGradeAvailability:
$ref: ./components/schemas.yml#/AssessmentGradeAvailability
AssessmentSpecializationAvailability:
$ref: ./components/schemas.yml#/AssessmentSpecializationAvailability
AssessmentAvailability:
$ref: ./components/schemas.yml#/AssessmentAvailability
parameters:
IdempotencyKey:
$ref: ./components/parameters.yml#/IdempotencyKey
@@ -143,6 +274,8 @@ components:
$ref: ./components/parameters.yml#/PageLimit
PageCursor:
$ref: ./components/parameters.yml#/PageCursor
AssessmentAttemptId:
$ref: ./components/parameters.yml#/AssessmentAttemptId
headers:
ETag:
$ref: ./components/headers.yml#/ETag
@@ -197,6 +330,20 @@ components:
$ref: ./components/responses.yml#/QuestionnaireValidationFailed
QuestionnaireVersionConflict:
$ref: ./components/responses.yml#/QuestionnaireVersionConflict
AssessmentAttemptCreateValidationFailed:
$ref: ./components/responses.yml#/AssessmentAttemptCreateValidationFailed
AssessmentAnswerValidationFailed:
$ref: ./components/responses.yml#/AssessmentAnswerValidationFailed
AssessmentCommandConflict:
$ref: ./components/responses.yml#/AssessmentCommandConflict
AssessmentFinalizeConflict:
$ref: ./components/responses.yml#/AssessmentFinalizeConflict
AssessmentCreateConflict:
$ref: ./components/responses.yml#/AssessmentCreateConflict
AssessmentResultNotReady:
$ref: ./components/responses.yml#/AssessmentResultNotReady
AssessmentVersionConflict:
$ref: ./components/responses.yml#/AssessmentVersionConflict
securitySchemes:
sessionCookie:
type: apiKey
@@ -0,0 +1,50 @@
get:
operationId: GetMyAssessmentAttempt
summary: Read or resume an assessment attempt of the current candidate.
description: |-
Requires the session cookie of a candidate account. Returns the attempt with its state, fixed versions, time and session limits, progress, the item to answer now, and the practices. A reload, a retried request, or a new session returns the same item instance with the same text and option order; a lost connection never creates a new attempt. The response never says whether an earlier answer was correct and never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals.
Reading an active attempt counts as activity: after the previous session ended it starts the next session, and when that would exceed the session limit it starts none and the attempt becomes `expired`. Before it answers, the server commits any transition that is due, with a new version: past `expires_at`, `ready_to_finalize` becomes `completed`, an unsubmitted additional practice is declined and the attempt becomes `completed`, and the other active states become `expired`; a practice still `pending` is graded first. The client polls this operation while a practice is `pending`. Reading a terminal attempt changes nothing.
The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account answers 403 forbidden; no operation gives an employer the answers or the attempt history.
security:
- sessionCookie: []
tags:
- assessment
parameters:
- $ref: ../components/parameters.yml#/AssessmentAttemptId
responses:
"200":
description: The attempt.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentAttempt
examples:
adaptive_resumed:
$ref: ../components/examples.yml#/AssessmentAttemptResumed
practice_pending:
$ref: ../components/examples.yml#/AssessmentAttemptPracticePending
practice_verdict_pending:
$ref: ../components/examples.yml#/AssessmentAttemptPracticeVerdictPending
sandbox_failed:
$ref: ../components/examples.yml#/AssessmentAttemptSandboxFailed
ready_to_finalize:
$ref: ../components/examples.yml#/AssessmentAttemptReadyToFinalize
additional_practice_pending:
$ref: ../components/examples.yml#/AssessmentAttemptAdditionalPracticePending
completed:
$ref: ../components/examples.yml#/AssessmentAttemptCompleted
insufficient_bank:
$ref: ../components/examples.yml#/AssessmentAttemptInsufficientBank
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
"404":
$ref: ../components/responses.yml#/NotFound
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,83 @@
post:
operationId: SubmitMyAssessmentAnswer
summary: Answer the current item or submit a practice of an assessment attempt.
description: |-
Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or `practice`. It never carries a score, a duration, or a correctness flag; the server records the times itself and scores the answer with the key of the fixed item instance. Time never enters the ability estimate or the grade decision.
The response is the attempt with the next item to answer. It never says whether the answer was correct. Items are answered in order and each answer is final.
Practice: an answer with format `practice` submits the solution of the main or the additional practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the public examples are unlimited apart from the sandbox rate limit and never show hidden group results; they are planned as a separate operation.
Repeats and conflicts, per item:
- A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
- Sending the answer already stored for the item again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice.
- A different answer for an item that already has one answers 409 state_conflict when `expected_version` is current; with a stale version the version check comes first and answers 412.
- Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A submission with the same or a different solution, with the current `expected_version`, queues it again and advances the version.
Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing; the client reads the attempt again. 412 is the repository status for a stale version, also used by SaveMyQuestionnaire; 409 state_conflict is kept for commands that the attempt state does not allow at the current version.
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found for an unknown attempt or one of another candidate; the server first commits any due transition such as expiry, and the request counts as activity for the session limit), the repeat of the stored answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the item is not current, the item has a different answer, or the practice verdict is pending or finished), then the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- assessment
parameters:
- $ref: ../components/parameters.yml#/AssessmentAttemptId
- $ref: ../components/parameters.yml#/IdempotencyKey
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentAnswerSubmission
examples:
choice:
$ref: ../components/examples.yml#/AssessmentChoiceAnswer
order:
$ref: ../components/examples.yml#/AssessmentOrderAnswer
number:
$ref: ../components/examples.yml#/AssessmentNumberAnswer
string:
$ref: ../components/examples.yml#/AssessmentStringAnswer
find_error:
$ref: ../components/examples.yml#/AssessmentFindErrorAnswer
configuration:
$ref: ../components/examples.yml#/AssessmentConfigurationAnswer
practice:
$ref: ../components/examples.yml#/AssessmentPracticeAnswer
responses:
"200":
description: >-
The answer was stored, or this exact answer was already stored, and
the response is the attempt with the next item.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentAttempt
examples:
accepted:
$ref: ../components/examples.yml#/AssessmentAnswerAccepted
practice_submitted:
$ref: ../components/examples.yml#/AssessmentAttemptPracticeVerdictPending
"400":
$ref: ../components/responses.yml#/AssessmentAnswerValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"409":
$ref: ../components/responses.yml#/AssessmentCommandConflict
"412":
$ref: ../components/responses.yml#/AssessmentVersionConflict
"422":
$ref: ../components/responses.yml#/UnprocessableContent
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,67 @@
post:
operationId: FinalizeMyAssessmentAttempt
summary: Ask for the grade decision of an assessment attempt.
description: |-
Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. Finalize always answers with the attempt, never with the result: the decision may continue the attempt, and one response type keeps that unambiguous for every generated client. When the returned state is `completed`, the client reads the result with GetMyAssessmentResult.
Allowed in `ready_to_finalize`, where every required part is done, and in `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server decides from the stored answers with the policy, bank, and algorithm versions fixed at creation:
- `demo_basic` compares the raw score with the pass mark of the recorded basic grading policy and completes the attempt. It never offers an additional practice.
- `adaptive` applies the probability bands of the recorded policy. Confirmation or rejection completes the attempt. A probability in the band below confirmation (0.50 to below 0.80 in the demo policy) on the first finalize, while time and sessions remain, completes nothing: the server appends an `additional` practice, moves the attempt to `additional_practice_pending`, and answers 200 with it. The additional practice continues the same attempt, keeps its limits, and spends no new attempt. The next finalize, after its verdict, decides with the added evidence; a probability still below confirmation gives `not_confirmed`. An attempt offers at most one additional practice.
- Finalize in `additional_practice_pending` declines the offer and gives `not_confirmed` with the current evidence. A retry of the first finalize with a new key cannot decline by accident: it carries the version from before the offer and answers 412.
A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, the server finalizes `ready_to_finalize` itself, without offering an additional practice, so a finalize after that also answers 200 with the `completed` attempt.
An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found, after any due transition), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict). 404 and 409 state_conflict are stored under the key; 400 and 412 are not.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- assessment
parameters:
- $ref: ../components/parameters.yml#/AssessmentAttemptId
- $ref: ../components/parameters.yml#/IdempotencyKey
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentFinalization
examples:
finalize:
$ref: ../components/examples.yml#/AssessmentFinalization
responses:
"200":
description: >-
The attempt after the decision: `completed`, with the result available
from GetMyAssessmentResult, or `additional_practice_pending` when an
adaptive attempt offers an additional practice.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentAttempt
examples:
demo_basic_completed:
$ref: ../components/examples.yml#/AssessmentAttemptCompleted
additional_practice_offered:
$ref: ../components/examples.yml#/AssessmentAttemptAdditionalPracticePending
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"409":
$ref: ../components/responses.yml#/AssessmentFinalizeConflict
"412":
$ref: ../components/responses.yml#/AssessmentVersionConflict
"422":
$ref: ../components/responses.yml#/UnprocessableContent
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,44 @@
get:
operationId: GetMyAssessmentResult
summary: Read the result of an assessment attempt of the current candidate.
description: |-
Requires the session cookie of a candidate account. Returns the immutable result of a terminal attempt: `completed`, `expired`, or `insufficient_bank`. It records the mode, the policy, bank, and algorithm versions, the decision, the previously confirmed grade, the calibration status and limitations of the method, the uncertainty where the method computes it, the practice verdicts, the weak domains, the working time as a separate label, and the next steps that the server allows. A later policy, bank, or algorithm version never changes it.
Fields that the method does not compute are null and never zero: a `demo_basic` result has null `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals.
An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active and has no result yet. The server first commits any due transition, so an attempt past its limits is read as terminal. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; employers see only the current category through a separate projection, never this result or the attempt history.
security:
- sessionCookie: []
tags:
- assessment
parameters:
- $ref: ../components/parameters.yml#/AssessmentAttemptId
responses:
"200":
description: The result.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentResult
examples:
demo_basic:
$ref: ../components/examples.yml#/AssessmentDemoBasicResult
adaptive_confirmed:
$ref: ../components/examples.yml#/AssessmentAdaptiveResult
adaptive_not_confirmed:
$ref: ../components/examples.yml#/AssessmentNotConfirmedResult
insufficient_bank:
$ref: ../components/examples.yml#/AssessmentInsufficientBankResult
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
"404":
$ref: ../components/responses.yml#/NotFound
"409":
$ref: ../components/responses.yml#/AssessmentResultNotReady
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,58 @@
post:
operationId: CreateMyAssessmentAttempt
summary: Start an assessment attempt for a category of the current candidate.
description: |-
Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the category, a specialization of the questionnaire and a target grade, and the task language. The server picks the mode from the published bank, `demo_basic` or `adaptive`, and fixes the policy, bank, and algorithm versions, the time and session limits, and the item variants in one transaction; the client never sends a mode, a seed, or a version. Creation starts session 1. The self-assessed grade only chooses where the test starts and adds no points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the measurement over.
A specialization has at most one active attempt. A new attempt cannot start while one is active, during a retry or promotion interval or past the attempt limit of the policy, or when the bank is insufficient; each answers 409 state_conflict and creates nothing, not even a placeholder attempt. GetMyAssessmentAvailability tells which case applies and when a blocked attempt opens. After a failure, including the first test, a lower grade can be tested at once. An attempt that ends as `expired` or with the reason `practice_incomplete` counts toward the attempt limit and starts the same-grade retry interval; one that ends as `insufficient_bank` or with the reason `sandbox_unavailable` counts toward neither.
The limits are server-side: `expires_at` and `sessions` come from the policy version, the client clock never extends them, and after them the attempt accepts no command. Within them the attempt is also bounded by the item limit of the policy.
Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 state_conflict response and creates nothing, so a lost response never creates a second attempt. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer, for example `/specialization` for a specialization that is not in the questionnaire or `/task_language` for a language that the bank does not offer), then availability (409 state_conflict). The rate limit can answer 429 with Retry-After before any of them; it is not stored.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- assessment
parameters:
- $ref: ../components/parameters.yml#/IdempotencyKey
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentAttemptCreate
examples:
backend_junior_go:
$ref: ../components/examples.yml#/AssessmentAttemptCreateBackendJunior
responses:
"201":
description: >-
The attempt was created, or a retry with the same Idempotency-Key
replayed its creation.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentAttempt
examples:
demo_basic_created:
$ref: ../components/examples.yml#/AssessmentAttemptCreated
"400":
$ref: ../components/responses.yml#/AssessmentAttemptCreateValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"409":
$ref: ../components/responses.yml#/AssessmentCreateConflict
"422":
$ref: ../components/responses.yml#/UnprocessableContent
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,32 @@
get:
operationId: GetMyAssessmentAvailability
summary: Read which assessment attempts the current candidate can start.
description: |-
Requires the session cookie of a candidate account; the candidate comes from the session. For each specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every grade whether an attempt can start now, in which mode, and with which limits: the time limit, the session limit, the item limit, and whether a code practice is required. The client shows them before the start, together with the method and the signals that are collected, and resumes an active attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt.
`insufficient_bank` is the state of a category whose bank is not published or has too few families that this candidate has not seen; the server limits attempts instead of repeating families. `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with that date and offer support. Specializations and their retry intervals are independent. Attempts that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations and never cause a `cooldown`.
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
security:
- sessionCookie: []
tags:
- assessment
responses:
"200":
description: Assessment availability of the current candidate.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentAvailability
examples:
backend_and_network_engineer:
$ref: ../components/examples.yml#/AssessmentAvailability
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
default:
$ref: ../components/responses.yml#/Problem