feat(assessment): define corrective and training attempt contracts

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 10:36:16 +03:00
1 parent fade4e76e4
commit 20c03288d6
71 files changed
+14786 -1743

No files matched your search

@@ -785,27 +785,33 @@ func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w h
// handleCreateMyAssessmentAttemptRequest handles CreateMyAssessmentAttempt operation.
//
// 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.
// an allowed Origin, and an Idempotency-Key. The request is one of three disjoint shapes. A real
// assessment names a specialization, target grade, and task language; the server picks `demo_basic` or
// `adaptive` and fixes the policy, bank, and algorithm versions, limits, and item variants. A
// corrective real assessment also names `root_attempt_id`; the server verifies the lower-grade chain
// and reuses its fixed quota and deadline. The client never sends a real mode, a seed, a version, or a
// chain deadline. Explicit `demo_express` starts a separate interactive training run that lasts 3 to 5
// minutes, has no category or target grade, and creates no qualification evidence or percentile.
// Creation starts session 1. The self-assessed grade only chooses where a real 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.
// A specialization has at most one active real attempt. A new root attempt cannot start while one is
// active, during a retry or promotion interval, past the root quota, or when the bank is insufficient;
// each such preflight refusal answers 409 state_conflict and creates nothing or consumes no root slot.
// Starting a root attempt reserves one slot in the root quota. A corrective attempt must reference its
// root, target a strictly lower grade not already attempted in that chain, and remain inside the
// root's fixed quota and deadline (72 hours from the root start in the current policy). It gets its
// own item, practice, and session limits, but spends no additional root slot and cannot reset the
// chain deadline or any 30/90-day timer. After a failure, including the first test, a lower grade can
// be tested at once. An expired or incomplete attempt does not create a free new chain; an
// insufficient bank or sandbox failure does not grant another root slot. `demo_express` is outside
// real-assessment availability, quotas, retry intervals, and qualification history.
//
// 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.
// clock never extends them, and after them the attempt accepts no work command. For a corrective
// attempt, `expires_at` is no later than the root's immutable `chain_deadline`. Within these limits
// the attempt is also bounded by the item limit of its 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
@@ -988,7 +994,7 @@ func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEsca
mreq := middleware.Request{
Context: ctx,
OperationName: CreateMyAssessmentAttemptOperation,
OperationSummary: "Start an assessment attempt for a category of the current candidate.",
OperationSummary: "Start a real, corrective, or training assessment attempt.",
OperationID: "CreateMyAssessmentAttempt",
Body: request,
RawBody: rawBody,
@@ -1002,7 +1008,7 @@ func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEsca
}
type (
Request = *AssessmentAttemptCreate
Request = AssessmentAttemptCreate
Params = CreateMyAssessmentAttemptParams
Response = CreateMyAssessmentAttemptRes
)
@@ -2466,6 +2472,11 @@ func (s *Server) handleDeclineMyInvitationRequest(args [1]string, argsEscaped bo
// every generated client. When the returned state is `completed`, the client reads the result with
// GetMyAssessmentResult.
//
// Finalize is a work command and requires an active session. After `idle_timeout_seconds` of
// inactivity, the candidate first calls StartMyAssessmentAttemptSession with the latest
// `expected_version`; finalize never starts a session. GET attempt and result operations do not change
// state. A command or background transition may commit a due deadline outcome.
//
// 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:
@@ -2487,9 +2498,9 @@ func (s *Server) handleDeclineMyInvitationRequest(args [1]string, argsEscaped bo
// 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.
// once. When `expires_at` passes or the session limit is reached, a command or background transition
// finalizes `ready_to_finalize` without offering an additional practice. A finalize after this
// transition answers 200 with the stored `completed` attempt; a GET never commits it.
//
// 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
@@ -2498,8 +2509,9 @@ func (s *Server) handleDeclineMyInvitationRequest(args [1]string, argsEscaped bo
//
// 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 attempt (404 not_found; a due deadline transition may be committed, but this request never
// starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state
// (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under
// the key; 400 and 412 are not.
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/finalize
@@ -3408,24 +3420,25 @@ func (s *Server) handleGetHealthzRequest(args [0]string, argsEscaped bool, w htt
// handleGetMyAssessmentAttemptRequest handles GetMyAssessmentAttempt operation.
//
// 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.
// Requires the session cookie of a candidate account. Returns the stored attempt projection with its
// state, fixed versions, time and session limits, progress, the item to answer now, and the practices.
// This GET is read-only: it never starts or resumes a work session, consumes session quota, advances
// the version, or commits expiry or finalization. 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. After `idle_timeout_seconds`, the candidate explicitly starts or resumes work with
// StartMyAssessmentAttemptSession. 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.
// When the deadline passes, this read still returns the stored state and deadline. A command or
// background transition commits the due outcome; if the stored state is still active,
// GetMyAssessmentResult answers 409 until that transition is committed. The client polls this
// operation while a practice is `pending`, but polling alone never changes attempt state.
//
// 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.
// answers 403 forbidden; no operation gives an employer the answers, qualification evidence, or
// attempt history.
//
// GET /api/v1/me/assessment-attempts/{attempt_id}
func (s *Server) handleGetMyAssessmentAttemptRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
@@ -3563,7 +3576,7 @@ func (s *Server) handleGetMyAssessmentAttemptRequest(args [1]string, argsEscaped
mreq := middleware.Request{
Context: ctx,
OperationName: GetMyAssessmentAttemptOperation,
OperationSummary: "Read or resume an assessment attempt of the current candidate.",
OperationSummary: "Read an assessment attempt of the current candidate.",
OperationID: "GetMyAssessmentAttempt",
Body: nil,
RawBody: rawBody,
@@ -3826,21 +3839,25 @@ func (s *Server) handleGetMyAssessmentAvailabilityRequest(args [0]string, argsEs
// handleGetMyAssessmentResultRequest handles GetMyAssessmentResult operation.
//
// 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.
// attempt: `completed`, `expired`, or `insufficient_bank`. A real result records the mode, policy,
// bank, and algorithm versions, decision, previously confirmed grade, calibration status and
// limitations, uncertainty where the method computes it, practice verdicts, weak domains, working time
// as a separate label, and allowed next steps. A corrective result also carries the root attempt and
// its immutable chain deadline. A `demo_express` result is a short educational summary only: it has no
// category, percentile, confirmed grade, score, uncertainty, or qualification evidence. A later
// policy, bank, or algorithm version never changes a result.
//
// 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.
// and has no result yet. This GET is read-only and never commits a due transition. If a deadline has
// passed but the due transition is not yet stored by a command or background worker, the attempt
// remains active for this read and answers 409; wait for the transition and retry. 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.
//
// GET /api/v1/me/assessment-attempts/{attempt_id}/result
func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
@@ -10876,6 +10893,262 @@ func (s *Server) handleSetMySearchStatusRequest(args [0]string, argsEscaped bool
}
}
// handleStartMyAssessmentAttemptSessionRequest handles StartMyAssessmentAttemptSession operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an
// Idempotency-Key. The body carries the attempt version the candidate last read. The server checks
// ownership, idempotency, and `expected_version` atomically before starting a session; a stale version
// answers 412 and consumes no session. Repeating the same key and body within 24 hours replays the
// stored response.
//
// Creation starts session 1. After `idle_timeout_seconds` of inactivity, the candidate uses this
// command to start the next session. Calling it while a session is already active returns the current
// attempt without consuming another session or advancing its version. Starting a session advances the
// version once. The command cannot extend `expires_at` or `chain_deadline`.
//
// If the attempt deadline or session budget has passed, this command commits the due terminal
// transition and returns the resulting attempt. A pending practice submitted before the limit is
// graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never
// start a session or commit a due transition. A background transition may persist a due outcome
// independently; after that, this command returns the stored terminal attempt without changing it.
//
// 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. An employer account answers 403 forbidden; no
// operation gives an employer answers, qualification evidence, or attempt history.
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/sessions
func (s *Server) handleStartMyAssessmentAttemptSessionRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("StartMyAssessmentAttemptSession"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/sessions"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), StartMyAssessmentAttemptSessionOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: StartMyAssessmentAttemptSessionOperation,
ID: "StartMyAssessmentAttemptSession",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, StartMyAssessmentAttemptSessionOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, StartMyAssessmentAttemptSessionOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeStartMyAssessmentAttemptSessionParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
request, rawBody, close, err := s.decodeStartMyAssessmentAttemptSessionRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response StartMyAssessmentAttemptSessionRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: StartMyAssessmentAttemptSessionOperation,
OperationSummary: "Start or resume a work session for the current candidate's attempt.",
OperationID: "StartMyAssessmentAttemptSession",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "attempt_id",
In: "path",
}: params.AttemptID,
{
Name: "Idempotency-Key",
In: "header",
}: params.IdempotencyKey,
},
Raw: r,
}
type (
Request = *AssessmentAttemptSessionStart
Params = StartMyAssessmentAttemptSessionParams
Response = StartMyAssessmentAttemptSessionRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackStartMyAssessmentAttemptSessionParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.StartMyAssessmentAttemptSession(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.StartMyAssessmentAttemptSession(ctx, request, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeStartMyAssessmentAttemptSessionResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleSubmitMyAssessmentAnswerRequest handles SubmitMyAssessmentAnswer operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -10888,6 +11161,12 @@ func (s *Server) handleSetMySearchStatusRequest(args [0]string, argsEscaped bool
// 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.
//
// A work command requires an active session. After `idle_timeout_seconds` of inactivity, the candidate
// calls StartMyAssessmentAttemptSession to explicitly start or resume a session; this answer command
// never starts one or consumes session quota. Reading the attempt or result is always read-only. A
// command that finds a due deadline transition may commit it before returning; a command that finds an
// expired idle session answers 409 until the candidate explicitly starts the next session.
//
// 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.
@@ -10921,15 +11200,14 @@ func (s *Server) handleSetMySearchStatusRequest(args [0]string, argsEscaped bool
//
// 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.
// the attempt (404 not_found for an unknown attempt or one of another candidate; a due deadline
// transition may be committed, but this request never starts a work session), 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 work session ended, 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.
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/answers
func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {