56 KiB
API contracts
Русский | English
Shared OpenAPI contracts for Go, the frontend, and ML. Contract changes come first; consumers then generate their types, server code, and clients from them.
core/defines the main backend's public API.ml/defines the ML service's internal HTTP API.testdata/contains a specification for checking tool compatibility with OpenAPI 3.2.0.
Routes live in routes/ and schemas in components/. The openapi.bundle.yml files are built automatically. Generator configuration lives in backend/codegen/, frontend/codegen/, and ml/codegen/.
From the repository root, make -C api check checks contracts and make generate updates all generated code.
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, the assessment commands, and CreateOrganizationNeed require Idempotency-Key, but no operation stores keys yet.
Errors
Every error is an RFC 9457 problem with the application/problem+json media type and the Problem schema. Required fields are type (urn:lincodex:problem:<code>), title, status, and code; optional ones are detail, instance, trace_id (equal to the X-Request-ID response header), and errors. Clients branch on code. Titles and details are fixed per code and never contain internal error text, stack traces, credentials, contact data, or submitted values.
| Code | Status | Meaning |
|---|---|---|
validation_failed |
400 | Parameters or body do not match the contract, or the body violates a domain rule; errors lists the fields |
verification_token_invalid |
400 | The email verification token is unknown, already used, or replaced |
verification_token_expired |
400 | The email verification token is past its lifetime |
unauthenticated |
401 | No valid session |
invalid_credentials |
401 | Login failed; an unknown email and a wrong password are not distinguished |
forbidden |
403 | The caller may not perform the operation |
email_not_verified |
403 | Correct credentials, but the email is not verified |
csrf_check_failed |
403 | Missing or wrong X-CSRF-Token, or a disallowed Origin |
not_found |
404 | Unknown route, or an object that does not exist or is not visible |
method_not_allowed |
405 | Unsupported method; see Allow |
idempotency_in_progress |
409 | A request with the same Idempotency-Key is still running |
state_conflict |
409 | The operation is not allowed in the current state of the resource |
version_conflict |
412 | If-Match, or a body expected_version, does not match the current version |
payload_too_large |
413 | The body exceeds the operation limit |
unsupported_media_type |
415 | The request Content-Type is not accepted |
idempotency_key_reused |
422 | The Idempotency-Key was used with a different request |
precondition_required |
428 | The operation requires If-Match |
rate_limited |
429 | Too many requests; see Retry-After |
internal |
500 | Unexpected server error |
not_implemented |
501 | The operation is in the contract but not implemented |
Request validation uses 400 rather than 422. The generated ogen server reports malformed and schema-invalid parameters and bodies through the same decoding errors, and for parameters it does not separate syntax from schema violations; one status keeps client handling uniform. 422 then stays free for Idempotency-Key reuse, as the IETF Idempotency-Key header draft recommends. Domain rules on the body, such as salary_from <= salary_to, also answer 400 validation_failed with body pointers to the fields involved. Each errors item has in (body, query, path, header, cookie), pointer (JSON Pointer: /salary_from in the body, an empty string for the whole body, /limit for a parameter), code (required or invalid; clients tolerate new values), and a fixed message. When the decoder does not record the path of a nested body field, the pointer is the whole body. A body cut by an http.MaxBytesReader limit answers 413 payload_too_large.
state_conflict covers business state conflicts, such as accepting an invitation that was already withdrawn. idempotency_in_progress is reserved for concurrent retries; the reusable responses are StateConflict and IdempotencyInProgress.
Every operation declares default: $ref: ../components/responses.yml#/Problem; ogen then generates a single error type. An operation adds a specific response (for example PreconditionFailed) when clients need it in the generated types. In the Go API, unknown paths under /api, including paths outside /api/v1, answer 404 not_found, and a panic in an operation answers 500 internal; only the panic type and stack are logged.
Both verification token codes use 400 because the token is request content, not the target resource: 404 and 410 describe the URI, 409 a resource state, and 422 stays reserved for Idempotency-Key reuse. A malformed token fails schema validation and answers 400 validation_failed with the pointer /token. invalid_credentials and unauthenticated share 401 but mean a failed login and a missing session respectively. email_not_verified is returned only after the password matched, so it tells the verification state only to someone who already proved the password.
Retries and Idempotency-Key
A mutating command declares the IdempotencyKey parameter. The client generates a key (a UUID v4 is recommended) and sends it in the Idempotency-Key header without quotes: 1-255 characters A-Z a-z 0-9 . _ : -. The server scopes the key by caller and operation and fingerprints the request by method, path, and body.
An anonymous operation defines its key scope and fingerprint in its own description; for RegisterAccount see the Identity section below.
Stored for 24 hours and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 not_found or 409 state_conflict. A replay does not repeat the side effect.
Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for the request itself; 401 and 403; 409 idempotency_in_progress; 412 version_conflict and 428 precondition_required (nothing changed; read the resource again and retry); 422 idempotency_key_reused; 429; and every 5xx.
The server checks in this order:
- Authentication (401), request validation (400, 413, 415), and authorization (403). Nothing is recorded for the key.
- A stored or running request with the same key and a different fingerprint: 422
idempotency_key_reused. This check comes before the in-progress check. - A running request with the same key and fingerprint: 409
idempotency_in_progress; retry later. - A stored outcome with the same key and fingerprint: the outcome is replayed.
- If-Match (428, 412), then the command itself; a storable outcome is recorded.
Because the replay check comes before If-Match, a retry of a completed change replays its outcome instead of failing on the version that the change itself advanced. A missing or malformed key returns 400 validation_failed with the pointer /Idempotency-Key. After 24 hours the key may be accepted as new.
Versions: ETag and If-Match
A response with a versioned resource returns a strong ETag, for example "v7". An operation that changes such a resource says in its description that it requires If-Match with that value. A missing value returns 428 precondition_required; a value that does not equal the current ETag returns 412 version_conflict and changes nothing. The parameter is optional in the schema so that a missing header reaches the application, which answers 428. Weak tags, lists, and * fail validation with 400. The questionnaire carries its version as expected_version in the body instead; see Catalog and questionnaire below.
Pagination
Lists use cursor pagination: limit from 1 to 100 (20 by default) and an opaque cursor of up to 512 characters A-Z a-z 0-9 _ -. The response holds the items in a bounded array and page (PageInfo) with has_more and next_cursor, which is null on the last page. A malformed cursor returns 400 validation_failed.
Time and money
Timestamps use the Timestamp schema: string, format: date-time, UTC with the Z suffix (RFC 3339). Servers always emit UTC. ogen generates Timestamp as a named Go type over time.Time; call .UTC() where a value is converted to it. Money is an integer number of whole rubles (RubAmount, int64) with an explicit base: SalaryRange requires salary_from, salary_to, currency (RUB), period (month), and tax_basis (net or gross); see Needs below. Invitations are expected to reuse SalaryRange.
ML service errors
The ML service answers its errors with the same Problem schema. Its ProblemCode enum keeps the public identity codes so both contracts share one shape, but the service never returns them. FastAPI request validation answers 400 validation_failed. An HTTP exception raised inside the service maps by status: 400, 401, 403, 404, 405, 409 (state_conflict), 412, 413, 415, 428, 429, and 501 to their codes, 422 to 400 validation_failed, any other 4xx to 400 validation_failed, and any other 5xx to 500 internal. An unhandled exception answers 500 internal inside the application, so Starlette does not re-raise it to uvicorn; only its type is logged. The service also routes the uvicorn loggers through its JSON log format, which keeps only the exception type of a record and never its text or traceback.
Identity: sessions, cookie, and CSRF
The identity tag covers registration, email verification, login, logout, and the current account. The operations are in the contract; their business logic is not implemented yet. Until it is, public operations answer 501 not_implemented after request validation, and the backend's v1.DenyAllSecurity rejects every session, so operations that require one answer 401 unauthenticated. Values marked as planned come from configuration in TASK-053 to TASK-056.
| Method and path | operationId | Security | Success | Specific errors |
|---|---|---|---|---|
GET /api/v1/identity/consent-texts/{purpose} |
GetConsentText |
public | 200 ConsentText |
400 validation_failed |
POST /api/v1/identity/registrations |
RegisterAccount |
public, Idempotency-Key | 202 IdentityRequestAccepted |
400 validation_failed, 403 csrf_check_failed, 409 idempotency_in_progress, 422 idempotency_key_reused, 429 |
POST /api/v1/identity/email-verification-requests |
ResendEmailVerification |
public | 202 IdentityRequestAccepted |
400, 403 csrf_check_failed, 429 |
POST /api/v1/identity/email-verifications |
ConfirmEmail |
public | 200 EmailVerificationResult |
400 verification_token_expired, verification_token_invalid, or validation_failed; 403 csrf_check_failed; 429 |
POST /api/v1/identity/sessions |
Login |
public | 201 Session, Set-Cookie, Cache-Control: no-store |
400, 401 invalid_credentials, 403 email_not_verified or csrf_check_failed, 429 |
GET /api/v1/identity/sessions/current |
GetCurrentSession |
session | 200 Session, Cache-Control: no-store |
401 unauthenticated |
DELETE /api/v1/identity/sessions/current |
Logout |
session and CSRF | 204, Set-Cookie clears the cookie |
401 unauthenticated (also clears the cookie), 403 csrf_check_failed |
GET /api/v1/identity/me |
GetCurrentAccount |
session | 200 Account, Cache-Control: no-store |
401 unauthenticated |
Every operation also declares the default problem response.
Registration and verification:
- Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email, and login answers 401
invalid_credentialsfor both an unknown email and a wrong password. - Before the server looks up the email, it validates the whole registration body (password bounds after NFKC normalization, the password blocklist, the C1 version) and computes the Argon2id hash on every branch, so neither a 400 nor the response time depends on whether the account exists.
- Registering an unverified email again replaces the password hash, the scenario, the onboarding step, and the C1 record, advances the registration version, invalidates every earlier verification token, and sends a new one. A pre-registration with someone else's password therefore does not survive the owner's own registration. For a verified email nothing changes; the server may send a rate-limited "you already have an account" notice.
- Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration never confirms the newer credentials. Resend issues a token for the current version, invalidates the earlier ones, and changes nothing else. Planned values: tokens live 24 hours; an account that stays unverified is deleted with its consent record and tokens 7 days after its last registration. These lifetimes come from the versioned product policy (demo version 1 of the
productfamily), not from configuration; see ARCHITECTURE.md. - Registration requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email; the fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The body, the password, and plain hashes of either are never stored, and the secret keeps the fingerprint from serving as an offline password check.
- The verification link is
<frontend origin>/verify-email#token=<token>. The page removes the fragment withhistory.replaceStateand posts the token only after an explicit user action, so the token stays out of server logs and Referer headers and a link scanner does not consume it. Verification does not start a session. - An expired token answers
verification_token_expired; an unknown, used, replaced, or superseded token answersverification_token_invalid. The client offers a new link and sign-in for both. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token.
Consent C1 and the account:
GetConsentText(c1)returns the current C1 text, itstext_version, andpublished_at. Registration sends that version inconsent_c1; the server records it with the hash of the same stored text. A version that is no longer current answers 400validation_failedwith the pointer/consent_c1/text_version, and the client reads the text again. A dedicated code would trigger the same client action, and the field pointer already identifies it, so no new code is added.- Unknown body fields are rejected, so no other consent, including C4, can be part of registration.
- Passwords are normalized to NFKC and must have 15-128 Unicode code points, without composition rules. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length.
- The account has a
scenario(candidateoremployer) and a savedonboarding_stepthat the server advances; after login the client returns the user to that step. Candidate steps arecandidate_consents,candidate_profile,candidate_questionnaire,candidate_assessment, andcompleted; the employer hasemployer_companyandcompleted. DTOs never contain password hashes, token hashes, or session identifiers.
Sessions and CSRF:
- The
sessionCookiescheme is the cookie__Host-lincodex_sessionwithPath=/; Secure; HttpOnly; SameSite=Strictand no Domain. The server keeps sessions in PostgreSQL and takes the caller only from the session. Only a verified account gets a session. Login revokes the session the request carried and issues a new identifier and CSRF token; logout revokes the session server-side. Planned timeouts: 24 hours idle and 7 days absolute; activity extends only the idle deadline. Both come from the versioned product policy, not from configuration. - The
sessionCsrfscheme is theX-CSRF-Tokenheader with the session-bound token fromSession.csrf_token. Every unsafe operation that requiressessionCookiemust also requiresessionCsrf;TestUnsafeSessionOperationsRequireCSRFTokenin the backend enforces it on the bundle. The client keeps the token in memory and restores it withGetCurrentSessionafter a reload or after 403csrf_check_failed. - Every unsafe request, including the public ones, must carry an
Originfrom the configured allowlist, otherwise 403csrf_check_failed(planned, TASK-056; see the development guide). Public identity operations are rate-limited (429 withRetry-After). - Responses with a session or account carry
Cache-Control: no-store. - The root
securityrequiressessionCookie, so an operation that does not declaresecurity: []is protected by default.
How the generated server (ogen v1.24.0) evaluates the schemes, and the mapping planned for TASK-056, are documented on v1.DenyAllSecurity and pinned by TestGeneratedServerSecurityOrder:
- It calls
HandleSessionCookiebeforeHandleSessionCsrfand passes the context returned by a successful call on. An absent value (no cookie, emptyX-CSRF-Token) does not call the handler, and a handler that returnsogenerrors.ErrSkipServerSecuritycounts as unsatisfied; both continue with the next scheme, soHandleSessionCsrfalso runs without a cookie, with the original context. - Any other handler error stops evaluation and reaches
NewErroras aSecurityErrorwhoseSecurityisSessionCookieorSessionCsrf. An unsatisfied requirement reachesNewErroras aSecurityErrorwithErrSecurityRequirementIsNotSatisfiedand noSecurityfield. - Planned mapping:
HandleSessionCookieskips a missing or invalid session;HandleSessionCsrfskips when the context has no principal (401) and returns a typed error for a wrong token.NewErrormaps aSessionCsrferror and an unsatisfied requirement with a principal in the context to 403csrf_check_failed, and every other security failure to 401unauthenticated. A 401 fromLogoutalso clears the cookie.
Catalog and questionnaire
The catalog and candidate tags cover the specialization catalog and the candidate questionnaire (PRD FR03). The operations are in the contract; their business logic is not implemented yet, so the catalog answers 501 not_implemented and the questionnaire answers 401 unauthenticated until sessions exist (v1.DenyAllSecurity).
| Method and path | operationId | Security | Success | Specific errors |
|---|---|---|---|---|
GET /api/v1/specializations |
GetSpecializationCatalog |
public | 200 SpecializationCatalog |
none |
GET /api/v1/me/questionnaire |
GetMyQuestionnaire |
session | 200 CandidateQuestionnaire, Cache-Control: no-store |
401 unauthenticated, 403 forbidden |
PUT /api/v1/me/questionnaire |
SaveMyQuestionnaire |
session and CSRF | 200 CandidateQuestionnaire, Cache-Control: no-store |
400 validation_failed, 401, 403 csrf_check_failed or forbidden, 412 version_conflict |
Every operation also declares the default problem response.
Catalog:
- Five directions and nine specializations: Development (
backend,frontend,mobile), Infrastructure (network_engineer,devops_sre), Data (data_analyst,ds_ml), Security (information_security), Quality (qa). The MVP grade scale isintern,junior,middle,senior; Lead and Architect come after the MVP. The codes are enums, so adding a value is a contract change. Titles are Russian plain text. - A category is a specialization together with a confirmed grade. Task languages (
python,go) and stack tags are attributes of a chosen specialization and never form a category: Backend with Go is the categorybackend. Algorithms is a shared assessment module, not a specialization. - Each specialization has
test_availability:status(availableorin_development), thegradeswith a published task bank, and thetask_languagesthat bank offers. The MVP opens an assessment only for a category with a published bank. The server derives the values from the published banks, so they change without a contract change; the example in the contract is illustrative and says nothing about a deployed bank. - The catalog is public (
security: []): it is the same for every caller, contains no personal data, is shown before registration, and can be cached.
Questionnaire:
- The candidate comes from the session; an employer account answers 403
forbidden. A candidate without a saved questionnaire gets 200 withversion: 0, no specializations, and nullwork_contextandupdated_atrather than 404, so the first save reads the version the same way as later ones. - Each chosen specialization has
self_assessed_grade,task_languages,stack, andexperiencein months or null when not stated;work_contextholds only the acceptable work formats and no personal data. The questionnaire never contains a confirmed grade or a category, and unknown fields such asconfirmed_gradeanswer 400. The self-assessed grade is the expected grade that thecandidate_assessmentonboarding step offers first; it influences where the assessment starts but adds no points, and no self-assessed grade or stack tag such as "Senior" assigns a category. A real profile stays invisible to employers until an assessment confirms a category. - The schema allows one or two specializations on save and rejects an unknown specialization, grade, task language, or work format. JSON Schema
uniqueItemscannot compare array items by one field, so the server rejects a repeated specialization with 400 and the pointer/specializations/<index>/specialization. It also rejects a task language that the specialization's published bank does not offer, with the pointer of that language. A specialization whose test isin_developmentcan be chosen; no assessment starts for it. - Concurrency uses
expected_versionin the body instead of If-Match, because the generated client cannot read theETagheader yet. The first save sends 0. A stale value answers 412version_conflict, the same status and code as a failed If-Match, because the client does the same thing: it reads the questionnaire again.version_conflictkeeps its 412 status, sostate_conflict(409) is not used here. - 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).TestQuestionnaireSchemaValidationPrecedesImplementationchecks 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 404not_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:
modeisdemo_basicoradaptive. The server picks it from the published bank of the category; the client never sends it.demo_basicscores 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.adaptiveis the adaptive test of FR04.- Creation fixes
versions:policy_version(the number of theproductpolicy version),bank_version, andalgorithm_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
versionadvances 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
additionaltopractices, moves the attempt toadditional_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 givesnot_confirmed. Finalizing without submitting it declines the offer with the same outcome.practicesis a list with akindrather than one more nullable field, so later practice kinds stay additive. - Finalize therefore always answers with
AssessmentAttempt, never with a result or aoneOfof both. When the state iscompleted, the client readsGetMyAssessmentResult. One response type keeps generated clients unambiguous and leaves room for non-terminal decisions without a breaking change. - Limits:
expires_atandsessions(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 afteridle_timeout_secondswithout one starts the next session; one beyondmaxstarts none, and the attempt becomesexpired. Reading a terminal attempt or a result never starts a session. - At the limits: a practice already
pendingis graded first. Thenready_to_finalizeis finalized by the server and becomescompleted, an unsubmitted additional practice is declined (completed,not_confirmed), andin_progressandpractice_pendingbecomeexpired. A finalize after that answers 200 with thecompletedattempt; any other command answers 409state_conflict. - Insufficient bank is a distinct state in two places. Before the start,
GetMyAssessmentAvailabilityshowsinsufficient_bankfor a grade without a published bank or without enough families that this candidate has not seen, andCreateMyAssessmentAttemptanswers 409state_conflictwithout creating anything. During an attempt, the terminal stateinsufficient_bankends it without a confirmed grade instead of repeating families. - No new problem code is added, so TASK-157 gets 409
state_conflictplus the availability status instead of abank_unavailablecode. TheProblemCodeenum 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, forcooldown, 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, andpractice_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_determinedwith the reasonexpiredorpractice_incompleteis the candidate's attempt and counts.insufficient_bankandsandbox_unavailableare 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-textprompt, andcontent(ItemContent) in one of the formatschoice,number,string,order,find_error,configuration, andpractice. 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, andmax_lengthare 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 asscore,duration, orseedanswer 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) isfinishedwith groups not passed.failed(sandbox_busyorsandbox_error) means only that the infrastructure could not run it; it consumes nothing. This keepsfailedfrom acting as an oracle for hidden checks and from allowing endless retries. Afterfinishedno other solution is accepted. - If the latest submission is still
failedwhen the limit passes, the result isnot_determinedwith the reasonsandbox_unavailable. A practice never submitted givespractice_incomplete. - An attempt has no practice only in
demo_basicwhile code practice is disabled until the sandbox isolation is verified; the result then lists thepractice_not_includedlimitation.
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 attemptversionthe 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 foroption_idsandline_numbers, the exact sequence forelement_ids, numeric equality fornumber, identical text without normalization fortextandconfig, and the same language with identical source for a practice. A different answer for an answered item answers 409state_conflictwith the current version; with a stale version the version check comes first and answers 412. - Exception: a practice whose latest verdict is
failedis 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
completedattempt 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_versionanswers 412version_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_conflictis 412 for If-Match and for a bodyexpected_versionalike, because the client action is the same, to read the resource again. 409state_conflictis 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_conflictwithout listing the unfinished items, becauseProblemallows no extension fields. The client reads them from the attempt:state,progress,current_item, andpractices. - Order of checks for a command: session (401), CSRF and Origin (403), request validation (400), account scenario (403
forbidden), the Idempotency-Key (422, 409idempotency_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 (409state_conflict), then domain rules (400 with pointers such as/answer/option_ids/0). Following the Idempotency-Key convention, 404 and 409state_conflictare stored under the key and replayed, while 400, including domain rules, 412, 429, and 5xx are not. Create and answers are rate-limited (429 withRetry-After), which also limits sandbox load.TestAssessmentSchemaValidationPrecedesImplementationchecks the schema rejections through the generated server.
Result:
GetMyAssessmentResultanswers for a terminal attempt and 409state_conflictfor an active one, includingadditional_practice_pending.outcomeisconfirmed,not_confirmed, ornot_determinedwithnot_determined_reason(expired,practice_incomplete,insufficient_bank,sandbox_unavailable). A result never lowers a confirmed grade:previous_confirmed_gradestays in force when the attempt confirmed nothing.calibration_statusandlimitationsdescribe the method. Fields that the method does not compute are null, never zero:demo_basichas nulluncertaintyandstrength, andadaptivehas nullbasic_score.uncertaintyholdstheta,standard_error,interval_95, andp_grade.practiceslists the verdicts by kind.durationsis a separate label and never enters the decision.next_stepscome from the server:retake_same_grade,take_lower_grade,accept_lower_grade(the command is planned), andtake_higher_grade. A first confirmation is not a promotion, sotake_higher_gradeafter it has a nullavailable_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).
Needs
The need tag covers the hiring needs of an organization (PRD FR08, with the versions of FR10): requirements with their confirmation state and provenance, immutable versions, readiness, and category recommendations. 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/organizations/{org_id}/needs |
ListOrganizationNeeds |
session | 200 NeedList, Cache-Control: no-store |
400 validation_failed, 401, 403 forbidden, 404 not_found |
POST /api/v1/organizations/{org_id}/needs |
CreateOrganizationNeed |
session and CSRF, Idempotency-Key | 201 Need, Cache-Control: no-store |
400, 401, 403 csrf_check_failed or forbidden, 404, 409 idempotency_in_progress, 422 idempotency_key_reused, 429 |
GET /api/v1/organizations/{org_id}/needs/{need_id} |
GetOrganizationNeed |
session | 200 Need, Cache-Control: no-store |
400 validation_failed, 401, 403 forbidden, 404 not_found |
PATCH /api/v1/organizations/{org_id}/needs/{need_id} |
UpdateOrganizationNeed |
session and CSRF | 200 Need, Cache-Control: no-store |
400, 401, 403, 404, 412 version_conflict, 429 |
Every operation also declares the default problem response. A malformed org_id or need_id answers 400 with the path pointer.
Access:
org_idin the path is the only source of the organization, and the server checks it against the active membership of the session account; no request has an organization, membership, or role field. The organization contract (TASK-077) owns organizations and memberships and reuses the same path parameter,parameters.yml#/OrganizationId.- An account without an active membership in
org_id, an unknown organization, an unknown need, and a need of another organization all answer 404not_found, so identifiers cannot be probed. A candidate account answers 403forbidden, and so does a member whose role does not allow the operation. - In the MVP only the owner of the organization works with needs. The other roles of the PRD FR07 matrix (recruiter, hiring manager and technical expert for assigned needs) are planned and change no field of the contract.
Fields and provenance:
requirements(NeedRequirementSet) holdsspecialization,grade,required_skills,desired_skills,tasks,domain,work_formats,location, andsalary. A field in a response is{status, value, source}; a list item has its ownstatusandsource.statusisconfirmed(a member entered or confirmed the value),extracted(a suggestion that waits for confirmation), orunknown(no value). An unknown field has nullvalueandsource; the server never fills it with a default or a guess such as Senior, remote, or a zero salary. Only confirmed values feed readiness, recommendations, search, and invitations.sourcehasorigin(manual,extracted_from_text, or the plannedimported),quote(an exact excerpt of up to 300 characters, or null),extracted_in_version, andextraction_version. The quote is an excerpt of thesource_textofextracted_in_version, not necessarily of the current text: a confirmed value keeps its quote after the text changes. Confirming a suggestion keeps its provenance; changing the value makes itmanual.- A skill has
taxonomy_code. It is null for a skill that the platform taxonomy does not know: the name stays as given, no code is guessed, and recommendations count the skill as not covered. - With
source_text, the server extracts suggestions with deterministic rules and a dictionary before it answers, so needs work while ML is disabled. ML suggestions with quotes are planned as an asynchronous addition that creates a new version and never overwrites a confirmed value. - The text is stored as written and may contain requirements that discriminate by a protected characteristic; the extractor never turns them into a need field. The field for what a candidate must not have, with the Labor Code article 64 check, is deferred to TASK-182 and will be added without a breaking change.
Requests, confirmation, and changes:
- Every requirement field in a request is a decision
{value, status}(NeedSpecializationInput,NeedGradeInput,NeedDomainInput,NeedWorkFormatsInput,NeedLocationInput,NeedSalaryInput), and every list item is{name or text, status}.statusisconfirmedorextracted. A bare value fails validation, so confirmation is always explicit. confirmedwith the stored suggested value confirms it and keeps its provenance;confirmedwith another value sets a confirmed manual value.extractedkeeps a stored suggestion open and is allowed only with exactly the stored suggested value; any other value, or a field or item without a suggestion, answers 400 with the pointer of that status, such as/grade/statusor/required_skills/2/status. A client that sends back an unchanged form therefore confirms nothing by accident: it sends each suggestion withextractedor leaves the field out.- A need never requires a vacancy: only
titleis required, andvacancy_idis optional and nullable. Until vacancies exist in the contract, any vacancy identifier answers 400 with the pointer/vacancy_id. - On creation every decision must be
confirmed, because a new need has no stored suggestion. An absent field is extracted fromsource_textor stays unknown. A nullable field sent as null stays unknown, and a skill or task list sent empty stays empty; neither is extracted. An emptywork_formatsvalue failsminItems. UpdateOrganizationNeeduses explicit field replacement inapplication/json, not JSON Merge Patch (RFC 7396): a present field replaces that field as a whole, an absent field stays unchanged, a decision and a list are never merged, and a stored item left out of a sent list is deleted. Null removes a nullable field (it becomesunknown, orvacancy_idis unlinked); an empty skill or task list deletes every item; a list sent as null answers 400. ogen generates one optional, or optional and nullable, value per decision (OptNilNeedGradeInput,OptNilNeedSalaryInput).- A different
source_textextracts again. New suggestions replace only theextractedvalues and items of fields not named in the body; confirmed values are never overwritten, a suggested skill whose name is already in either skill list is skipped, and a suggestion that a member deleted is not proposed again for this need. - The server also rejects a repeated skill or task and a skill in both lists, with 400 and the pointer of the later item, such as
/required_skills/1/name.
Versions and concurrency:
versionstarts at 1 and advances by exactly one with each committed change, including server-side ones. Each version is an immutable snapshot. GET always returns the latest version.requirements_versionis the version in which the confirmed requirements were last changed. Confirming, changing, or removing a requirement sets it to the newversion; a change of the title, the vacancy link, the text, or suggestions only keeps it and invalidates neither the recommendations nor search results. Search runs, selection snapshots (FR10, TASK-193), and invitations refer to(need_id, requirements_version), and only a newrequirements_versioncalls for a new selection snapshot. Reading and comparing earlier versions are planned as separate operations that returnNeedRequirementSetfor a version; they add nothing toNeed.- A change carries
expected_version, the version the client read, in the body for the same reason as the questionnaire: the generated client cannot readETagyet. A stale value answers 412version_conflictand changes nothing; TASK-179 says 409, but the repository rule keeps 412 for If-Match and a body version alike. A body that changes nothing answers 200 with the current need even with an older version, so PATCH needs no Idempotency-Key. POST needs one with the 24-hour replay; only the 201 is stored.
Readiness:
readiness.missing_fieldslists each critical field without a confirmed value:specialization,grade,required_skills(at least one confirmed skill),work_formats,salary, andlocationwhen the confirmed formats includeofficeorhybrid. Each item hasreason(unknownorunconfirmed) and a specific Russianquestion.- An incomplete need is saved (201 or 200), not rejected.
Problemallows no extension fields, so the missing fields live in the resource, not in a problem. Each later operation, such as search or an invitation, states which readiness it requires.
Salary:
SalaryRange[A; B]hassalary_fromandsalary_to(RubAmount, whole rubles),currency(RUBonly),period(monthonly), andtax_basis(netorgross); every field is required. Requests send it assalary: {value, status}, so its pointers are under/salary/value.- The schema requires bounds that are positive multiples of 1000 up to 100000000 and rejects another currency, period, or basis, for example with
/salary/value/tax_basis. A missing field of the nested range has the whole-body pointer. - The server checks the cross-field rules of PRD FR13 in integer arithmetic:
A < Band a width(B - A) / ((A + B) / 2)from 10% to 40% inclusive, that is20 * (B - A) >= A + Band5 * (B - A) <= A + B. A violation, including equal bounds, answers 400 with the pointer/salary/value/salary_to.[95000; 105000](exactly 10%) and[80000; 120000](exactly 40%) are accepted. FR13 applies the same rules to the range of a need and of an invitation, anddocs/*/ARCHITECTURE.mdnow states them for invitations instead of0 < salary_from <= salary_to. - Limit against probing hidden minimums (FR13, planned in TASK-211): setting a confirmed range, on creation or on a change, counts against a counter shared by the whole organization, every member and every need, so a new need does not reset it. At most three range settings a day; over the limit the server answers 429 with Retry-After and changes nothing. After five settings within seven days the money component is
withheldfor seven days. Repeated range changes also feed the private risk signals of TASK-319.
Recommendations:
recommendationsis computed by the server from the confirmed requirements ofrequirements_versionwith a versioned policy (policy_version,algorithm_version,computed_at).statusiscomputed,pending, ornot_availablewithout a confirmed skill. The server may recompute them for the samerequirements_version, for a new policy or a changed pool of candidates, without a new need version;computed_atandpolicy_versionthen change.- Each category (
specializationandgrade) hasscore,skill_overlap(weighted share with weight 2 for required and 1 for desired skills, covered and uncovered skills),money, andsupplyas a band:fewer_than_5,from_5_to_29,30_or_more. The list order is the ranking. money.statusiscomputed,insufficient_data(fewer than five candidates with a comparable known minimum),no_salary, orwithheld; the last three use the neutral 0.5 and a null share.money.shareis rounded down to a quarter (0, 0.25, 0.5, 0.75, 1): each probe of a new upper bound then tells at most which quarter of the group accepts it, and in the smallest allowed group of five a single minimum often does not move the value, while the share still separates a range that most candidates accept from one that few accept.scoreis0.5 * Overlap + 0.3 * Money + 0.2 * Supply, rounded half up to two decimals, computed from the published components: the exact overlap, the quarter-rounded share or the neutral 0.5, andSupply = min(1, active / 30). It is null whensupplyisfewer_than_5. The ranking uses Supply only at band precision below five: every group of fewer than five candidates enters it with Supply 0, so neither the score nor the order reveals the exact size of a group below five, which FR08 forbids. For five or more candidates the exact Supply is used, so the TASK-183 fixture (Overlap 1, Money 0.5, 15 active candidates) givesscore0.75.- Deviation from the PRD formula and from TASK-183 and TASK-457: the money share in the score and ranking is the quarter-rounded share, not the exact one, and a category with fewer than five candidates has no score. Otherwise the score with the exact share would reveal the share that
money.sharerounds, and a score with the exact Supply of a small group would reveal its size. The breakdown that TASK-457 shows consists of the published components. - Requests cannot set a recommendation, its score, membership, or a candidate minimum: bodies have
additionalProperties: false, and unknown fields such asrec_score,members,candidate_minimum,version,requirements_version, orrecommendationsanswer 400 with the whole-body pointer.TestNeedSchemaValidationPrecedesImplementationchecks the schema rejections through the generated server,TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApartchecks the list decoding, andfrontend/src/shared/api/needs-contract.test.tspins the generated Zod limits, the explicit status of every decision, and the absence of these fields in the request types.
Planned, additive: reading and comparing versions, exclusions (TASK-182), the market range hint (P25-P75) of FR08, the check plan "vacancy -> tasks", a need status for archiving, list filters, and need assignments.
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.
make -C api check-toolchain lints the fixture and runs the three generators on it; it needs the backend Go toolchain, pnpm, and uv, so pass the same UV override as for make generate.
| Target | Generator | Exercised conventions |
|---|---|---|
make -C backend check-ogen-compat |
ogen | All of them: Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch, ETag. Its tests check validation errors, the retry scenario, the preconditions, and the 413 body limit against the backend problem mapping |
make -C frontend check-orval-compat |
Orval | Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch. The output is type-checked with the frontend compiler settings |
make -C ml check-pydantic-compat |
datamodel-code-generator | Problem, PageInfo, Timestamp, PageLimit, PageCursor. The models pass mypy --strict and a validation script |
Each target writes its output to a temporary directory and removes it.
Known generator limitations:
- Orval 8.40 writes no Zod schema for
components/responsesbut imports a<Name>Responsetype for each reference.frontend/codegen/orval.config.tstherefore inlines response references before generation. - Orval passes header parameters as a typed argument only with
headers: true. WithexactOptionalPropertyTypes, an optional header such asIf-MatchfitsRequestInitonly when Zod emits exact optional properties, so the configuration also setsoverride.zod.exactOptional. - Orval generates no type for response headers, and
apiRequestreturns only the body, so a generated client cannot readETagyet. The first operation with a versioned resource must expose it, for example through the response body or the mutator. - datamodel-code-generator 0.83.0 generates models only for schemas and query and path parameters; header parameters and response headers (Idempotency-Key, If-Match, ETag) produce no Python model.
- Orval does not generate
additionalOperationsmethods. - ogen writes the header name in its canonical Go form (
Etag); HTTP header names are case-insensitive. - ogen requires a
SecurityHandleras soon as the contract has security schemes and evaluates the schemes in the order of their generated type names, so renaming a scheme can change the order;TestGeneratedServerSecurityOrderfails if it does. Security failures reachNewErrorwithout a response header, so clearing the cookie on a 401 fromLogoutneeds handwritten code. - Orval does not expose security scheme values as typed arguments, so
X-CSRF-Tokenis not a generated parameter; the shared API client is planned to attach it to mutating requests. Orval also generates no type forSet-Cookie, which the browser handles. - Orval Zod schemas ignore
uniqueItemsand do not reject unknown fields ofadditionalProperties: falseobjects; the server stays authoritative for both. - ogen generates an optional nullable field as
OptNil<T>, which tells absent (IsSetfalse), null (IsNull), and a value apart. An optional array that is not nullable is a plain slice instead, where nil and[]mean different things: an absent field decodes to nil (unchanged) and[]to an empty non-nil slice (delete every item), and null fails decoding. AnUpdateOrganizationNeedhandler must therefore test lists with!= nil, never withlen;TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApartpins this. - Orval clears
src/shared/api/endpoints/andsrc/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
ItemContentandAssessmentAnswerareoneOfwithout adiscriminatorobject. Redocly resolvesdiscriminator.mappingvalues as references, andscripts/merge-schemas.pyrewrites only$ref, so a mapping in a split schema file cannot resolve in the mergedcomponents/schemas.yml. Every variant fixesformatwith 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 inindex.ts(TS2308). The union of item formats is thereforeItemContent, notAssessmentItemContent, next to theAssessmentItem.contentproperty, and the parts ofNeedareNeedRequirementSet,NeedReadinessReport, andNeedCategoryRecommendations, notNeedRequirements,NeedReadiness, andNeedRecommendations.
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.