feat: add assessment, privacy and support flows

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 08:08:25 +03:00
1 parent ee3738ee73
commit e4f24fa202
339 files changed
+56454 -1126

No files matched your search

@@ -0,0 +1,231 @@
package assessment
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const submitAnswerOperation = "assessment_attempt.answer"
// SubmitAttemptAnswerCommand is one candidate answer to the current frozen
// item. The answer is private and must not be logged.
type SubmitAttemptAnswerCommand struct {
ActorID uuid.UUID
AttemptID domain.AssessmentAttemptID
ItemID uuid.UUID
ExpectedVersion int64
IdempotencyKey string
Answer json.RawMessage
}
type canonicalAttemptAnswerBody struct {
AttemptID string `json:"attempt_id"`
ItemID string `json:"item_id"`
ExpectedVersion int64 `json:"expected_version"`
Answer json.RawMessage `json:"answer"`
}
// SubmitAnswer persists the current answer and an immutable public response in
// one transaction. Raw answer data never enters the idempotency table.
func (service *AttemptService) SubmitAnswer(
ctx context.Context,
command SubmitAttemptAnswerCommand,
) (outbound.AssessmentAttemptCommandResult, error) {
const location = "AttemptService.SubmitAnswer"
if command.ActorID == uuid.Nil {
return outbound.AssessmentAttemptCommandResult{}, ErrAttemptForbidden
}
if command.AttemptID.IsZero() || command.ItemID == uuid.Nil || command.ExpectedVersion < 1 {
return outbound.AssessmentAttemptCommandResult{}, attemptFieldError("/expected_version", "must be a positive version and identify one item")
}
canonicalAnswer, err := domain.CanonicalAssessmentAnswer(command.Answer)
if err != nil {
return outbound.AssessmentAttemptCommandResult{}, attemptFieldError("/answer", "must match a supported answer format")
}
body, err := json.Marshal(canonicalAttemptAnswerBody{
AttemptID: command.AttemptID.String(), ItemID: command.ItemID.String(), ExpectedVersion: command.ExpectedVersion,
Answer: canonicalAnswer,
})
if err != nil || len(body) > maxAttemptCanonicalBodyBytes {
return outbound.AssessmentAttemptCommandResult{}, ErrInvalidAttemptRequest
}
keyTime, err := assessmentIdempotencyTime(service.clock())
if err != nil {
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - validate application time: %w", location, err)
}
request, err := service.prepareAttemptIdempotency(submitAnswerOperation, command.IdempotencyKey, command.ActorID, body, keyTime)
if err != nil {
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - prepare idempotency: %w", location, err)
}
var result outbound.AssessmentAttemptCommandResult
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil {
return err
}
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return fmt.Errorf("%s - reserve idempotency: %w", location, err)
}
repository := unit.AssessmentAttempts()
if !created {
return replayAttemptAnswer(ctx, repository, request, stored, &result)
}
if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil {
return fmt.Errorf("%s - remove expired answer response: %w", location, err)
}
return service.submitNewAnswer(ctx, unit, repository, request.scope, command, &result)
})
if err != nil {
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
func replayAttemptAnswer(
ctx context.Context,
repository outbound.AssessmentAttemptRepository,
request attemptIdempotencyRequest,
stored outbound.IdempotencyRecord,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "assessment.replayAttemptAnswer"
if stored.Fingerprint != request.record.Fingerprint {
return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused)
}
outcome, err := repository.GetAnswerOutcome(ctx, request.scope)
if err != nil {
return fmt.Errorf("%s - read immutable answer response: %w", location, err)
}
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome, Replayed: true}
return nil
}
func (service *AttemptService) submitNewAnswer(
ctx context.Context,
unit outbound.UnitOfWork,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
command SubmitAttemptAnswerCommand,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "AttemptService.submitNewAnswer"
current, err := lockAttemptForAnswer(ctx, unit, repository, command.ActorID, command.AttemptID)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return storeAttemptCommandProblem(ctx, repository, scope, "answer", 404, result)
}
if err != nil {
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
}
if !attemptHasItem(current, command.ItemID) {
return attemptFieldError("/item_id", "does not identify an item in this attempt")
}
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err)
}
databaseTime = databaseTime.UTC().Truncate(time.Microsecond)
return service.persistSubmittedAnswer(ctx, repository, scope, command, current, databaseTime, result)
}
func lockAttemptForAnswer(
ctx context.Context,
unit outbound.UnitOfWork,
repository outbound.AssessmentAttemptRepository,
actorID uuid.UUID,
attemptID domain.AssessmentAttemptID,
) (domain.AssessmentAttempt, error) {
const location = "AttemptService.lockAttemptForAnswer"
kind, err := repository.GetKindForCandidate(ctx, actorID, attemptID)
if err != nil {
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound
}
return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
}
if err := lockSessionConsent(ctx, unit, actorID, kind); err != nil {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - authorize answer: %w", location, err)
}
current, err := repository.GetForCandidateForUpdate(ctx, actorID, attemptID)
if err != nil {
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound
}
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
}
if current.Kind() != kind {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt)
}
return current, nil
}
func (service *AttemptService) persistSubmittedAnswer(
ctx context.Context,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
command SubmitAttemptAnswerCommand,
current domain.AssessmentAttempt,
databaseTime time.Time,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "AttemptService.persistSubmittedAnswer"
updated, changed, submitErr := current.SubmitAnswer(command.ExpectedVersion, command.ItemID, command.Answer, databaseTime)
if submitErr != nil && errors.Is(submitErr, domain.ErrAssessmentAttemptNotActive) && command.ExpectedVersion == current.Version() {
expired, expiredChanged, expireErr := current.ExpireIfDue(databaseTime)
if expireErr != nil {
return fmt.Errorf("%s - apply due deadline transition: %w", location, expireErr)
}
if expiredChanged {
if err := repository.SaveTransition(ctx, current, expired); err != nil {
return fmt.Errorf("%s - persist due deadline transition: %w", location, err)
}
return storeAttemptCommandProblem(ctx, repository, scope, "answer", 409, result)
}
}
if submitErr != nil {
if errors.Is(submitErr, domain.ErrAssessmentAttemptNotActive) {
return storeAttemptCommandProblem(ctx, repository, scope, "answer", 409, result)
}
return mapAttemptAnswerError(submitErr)
}
if changed {
if err := repository.SaveAnswer(ctx, current, updated, command.ItemID); err != nil {
return fmt.Errorf("%s - persist answer and attempt transition: %w", location, err)
}
}
outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: updated.PublicSnapshot()}
if err := repository.SaveAnswerOutcome(ctx, scope, outcome); err != nil {
return fmt.Errorf("%s - store immutable answer response: %w", location, err)
}
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome}
return nil
}
func attemptHasItem(attempt domain.AssessmentAttempt, itemID uuid.UUID) bool {
for _, item := range attempt.Snapshot().Items {
if item.ID == itemID {
return true
}
}
return false
}
func mapAttemptAnswerError(err error) error {
switch {
case errors.Is(err, domain.ErrAssessmentAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict):
return fmt.Errorf("AttemptService.SubmitAnswer - check expected version: %w", ErrAttemptVersionConflict)
case errors.Is(err, domain.ErrAssessmentAttemptNotActive):
return fmt.Errorf("AttemptService.SubmitAnswer - check answer state: %w", ErrAttemptStateConflict)
case errors.Is(err, domain.ErrInvalidAssessmentAttempt):
return attemptFieldError("/answer", "does not match the current item")
default:
return err
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,517 @@
package assessment
import (
"context"
"errors"
"fmt"
"slices"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var ErrAssessmentAvailabilityNotImplemented = errors.New("assessment availability is not implemented for the effective policy")
type AvailabilityStatus string
const (
AvailabilityStatusAvailable AvailabilityStatus = "available"
AvailabilityStatusActiveAttempt AvailabilityStatus = "active_attempt"
AvailabilityStatusCooldown AvailabilityStatus = "cooldown"
AvailabilityStatusInsufficientBank AvailabilityStatus = "insufficient_bank"
)
type AssessmentAvailability struct {
Specializations []SpecializationAvailability
}
type SpecializationAvailability struct {
Specialization domain.SpecializationCode
ConfirmedGrade *domain.GradeCode
ActiveAttemptID *domain.AssessmentAttemptID
Grades []GradeAvailability
}
type GradeAvailability struct {
Grade domain.GradeCode
Status AvailabilityStatus
Mode *domain.AssessmentRealMode
AvailableAt *time.Time
TimeLimitSeconds *int32
MaxSessions *int32
MaxItems *int32
PracticeRequired *bool
}
// GetMyAssessmentAvailability is a read-only candidate preflight. All
// repositories run under one repeatable-read snapshot so policy, bank,
// questionnaire, attempts, and disclosed families agree on one database view.
func (service *AttemptService) GetMyAssessmentAvailability(
ctx context.Context,
userID uuid.UUID,
) (AssessmentAvailability, error) {
const location = "AttemptService.GetMyAssessmentAvailability"
var availability AssessmentAvailability
err := service.snapshotExecutor.WithinReadOnlySnapshot(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireAttemptCandidate(ctx, unit, userID, location); err != nil {
return err
}
now, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return fmt.Errorf("%s - read snapshot database time: %w", location, err)
}
now = now.UTC().Truncate(time.Microsecond)
assessmentPolicy, err := readAvailabilityPolicy(ctx, unit, now)
if err != nil {
return fmt.Errorf("%s - read effective assessment policy: %w", location, err)
}
questionnaire, err := unit.CandidateQuestionnaires().Get(ctx, userID)
if err != nil {
return fmt.Errorf("%s - read candidate questionnaire: %w", location, err)
}
availability, err = buildAssessmentAvailability(ctx, unit, userID, now, assessmentPolicy, questionnaire)
if err != nil {
return fmt.Errorf("%s - build assessment availability: %w", location, err)
}
return nil
})
if err != nil {
return AssessmentAvailability{}, fmt.Errorf("%s - read snapshot: %w", location, err)
}
return availability, nil
}
func readAvailabilityPolicy(
ctx context.Context,
unit outbound.UnitOfWork,
now time.Time,
) (domain.AssessmentPolicy, error) {
const location = "assessment.readAvailabilityPolicy"
version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, now)
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
return domain.AssessmentPolicy{}, fmt.Errorf("%s - no effective assessment policy: %w", location, ErrAssessmentAvailabilityNotImplemented)
}
if err != nil {
return domain.AssessmentPolicy{}, err
}
policy := version.Policy().Assessment
if policy.Attempt == nil || policy.Attempt.RealMode != domain.AssessmentRealModeDemoBasic {
return domain.AssessmentPolicy{}, fmt.Errorf("%s - effective real assessment mode is not implemented: %w", location, ErrAssessmentAvailabilityNotImplemented)
}
return policy, nil
}
type assessmentAvailabilityReads struct {
selections []outbound.AssessmentAvailabilitySelection
active map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary
rootHistory map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary
quota outbound.AssessmentRootQuotaSnapshot
seen map[domain.AssessmentFamilyKey]struct{}
}
func buildAssessmentAvailability(
ctx context.Context,
unit outbound.UnitOfWork,
userID uuid.UUID,
now time.Time,
policy domain.AssessmentPolicy,
questionnaire domain.CandidateQuestionnaire,
) (AssessmentAvailability, error) {
reads, err := readAssessmentAvailability(ctx, unit, userID, now, policy, questionnaire)
if err != nil {
return AssessmentAvailability{}, err
}
seconds, err := assessmentLimitSeconds(policy.Attempt.Lifetime.Duration())
if err != nil {
return AssessmentAvailability{}, err
}
itemCount := policy.StopRule.MaxScoredItems + policy.StopRule.SeedItems
result := AssessmentAvailability{Specializations: make([]SpecializationAvailability, 0, len(questionnaire.Specializations()))}
for _, answer := range questionnaire.Specializations() {
result.Specializations = append(result.Specializations, buildSpecializationAvailability(
answer, reads, policy, now, seconds, itemCount,
))
}
return result, nil
}
func assessmentLimitSeconds(duration time.Duration) (int32, error) {
seconds := duration / time.Second
if seconds <= 0 || seconds > time.Duration(1<<31-1) {
return 0, fmt.Errorf("assessment availability limit exceeds supported seconds: %w", domain.ErrInvalidPolicy)
}
return int32(seconds), nil
}
func readAssessmentAvailability(
ctx context.Context,
unit outbound.UnitOfWork,
userID uuid.UUID,
now time.Time,
policy domain.AssessmentPolicy,
questionnaire domain.CandidateQuestionnaire,
) (assessmentAvailabilityReads, error) {
const location = "assessment.readAssessmentAvailability"
selections, err := unit.AssessmentBank().ListCurrentAssessmentAvailabilitySelections(ctx, now)
if err != nil {
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read bank: %w", location, err)
}
reads := assessmentAvailabilityReads{selections: selections}
reads.active, err = readActiveAvailabilityAttempts(ctx, unit, userID, now, questionnaire)
if err != nil {
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read active attempts: %w", location, err)
}
window := policy.AttemptWindow.Duration()
reads.quota, err = unit.AssessmentAttempts().GetRootQuotaSnapshot(
ctx, userID, now.Add(-window), now, window, policy.MaxAttemptsPerWindow,
)
if err != nil {
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read root quota: %w", location, err)
}
reads.rootHistory, err = readAvailabilityRootHistory(ctx, unit, userID, now, policy, questionnaire)
if err != nil {
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read root retry history: %w", location, err)
}
keys, err := unit.AssessmentAttempts().ListDisclosedFamilyKeys(ctx, userID, now.Add(-365*24*time.Hour))
if err != nil {
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read disclosed families: %w", location, err)
}
reads.seen = make(map[domain.AssessmentFamilyKey]struct{}, len(keys))
for _, key := range keys {
reads.seen[key] = struct{}{}
}
return reads, nil
}
func readActiveAvailabilityAttempts(
ctx context.Context,
unit outbound.UnitOfWork,
userID uuid.UUID,
now time.Time,
questionnaire domain.CandidateQuestionnaire,
) (map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary, error) {
activeBySpecialization := make(map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary)
for _, answer := range questionnaire.Specializations() {
active, found, err := unit.AssessmentAttempts().GetAvailabilityActiveAttempt(ctx, userID, answer.Specialization)
if err != nil {
return nil, err
}
if found && active.ExpiresAt.After(now) {
activeBySpecialization[answer.Specialization] = active
}
}
return activeBySpecialization, nil
}
func readAvailabilityRootHistory(
ctx context.Context,
unit outbound.UnitOfWork,
userID uuid.UUID,
now time.Time,
policy domain.AssessmentPolicy,
questionnaire domain.CandidateQuestionnaire,
) (map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary, error) {
horizon := max(policy.AttemptWindow.Duration(), policy.SameGradeRetryAfter.Duration(),
policy.PromotionMinInterval.Duration()) + policy.Attempt.ChainDeadline.Duration()
history := make(map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary)
for _, answer := range questionnaire.Specializations() {
rows, err := unit.AssessmentAttempts().ListAvailabilityRootSummaries(
ctx, userID, answer.Specialization, now.Add(-horizon),
)
if err != nil {
return nil, err
}
history[answer.Specialization] = rows
}
return history, nil
}
func buildSpecializationAvailability(
answer domain.QuestionnaireSpecialization,
reads assessmentAvailabilityReads,
policy domain.AssessmentPolicy,
now time.Time,
seconds, itemCount int32,
) SpecializationAvailability {
active, hasActive := reads.active[answer.Specialization]
result := SpecializationAvailability{
Specialization: answer.Specialization,
Grades: make([]GradeAvailability, 0, len(availabilityGrades)),
}
if hasActive {
id := active.ID
result.ActiveAttemptID = &id
}
for _, grade := range availabilityGrades {
result.Grades = append(result.Grades, buildGradeAvailability(
answer, grade, reads, policy, now, seconds, itemCount, hasActive,
))
}
return result
}
func buildGradeAvailability(
answer domain.QuestionnaireSpecialization,
grade domain.GradeCode,
reads assessmentAvailabilityReads,
policy domain.AssessmentPolicy,
now time.Time,
seconds, itemCount int32,
hasActive bool,
) GradeAvailability {
result := GradeAvailability{Grade: grade}
if hasActive {
result.Status = AvailabilityStatusActiveAttempt
} else if !hasSufficientUnseenBank(answer, grade, reads.selections, reads.seen, itemCount) {
result.Status = AvailabilityStatusInsufficientBank
return result
} else if availableAt := rootCooldownUntil(reads.rootHistory[answer.Specialization], grade, policy, reads.quota, now); availableAt != nil {
result.Status = AvailabilityStatusCooldown
result.AvailableAt = availableAt
} else {
result.Status = AvailabilityStatusAvailable
}
mode := policy.Attempt.RealMode
result.setLimits(mode, seconds, policy.Attempt.MaxSessions, itemCount, false)
return result
}
var availabilityGrades = [...]domain.GradeCode{
domain.GradeIntern, domain.GradeJunior, domain.GradeMiddle, domain.GradeSenior,
}
func (grade *GradeAvailability) setLimits(
mode domain.AssessmentRealMode,
seconds, maxSessions, maxItems int32,
practiceRequired bool,
) {
grade.Mode = &mode
grade.TimeLimitSeconds = &seconds
grade.MaxSessions = &maxSessions
grade.MaxItems = &maxItems
grade.PracticeRequired = &practiceRequired
}
func hasSufficientUnseenBank(
answer domain.QuestionnaireSpecialization,
grade domain.GradeCode,
selections []outbound.AssessmentAvailabilitySelection,
seen map[domain.AssessmentFamilyKey]struct{},
minimum int32,
) bool {
catalogLanguages := availabilityLanguages(answer.Specialization, selections)
if len(catalogLanguages) > 0 && len(answer.TaskLanguages) == 0 {
return false
}
languages := answer.TaskLanguages
if len(catalogLanguages) == 0 {
if len(languages) > 0 {
return false
}
languages = []domain.TaskLanguageCode{""}
}
for _, language := range languages {
if len(catalogLanguages) > 0 && !slices.Contains(catalogLanguages, language) {
continue
}
selection, found := uniqueAvailabilitySelection(selections, answer.Specialization, grade, language)
if !found {
continue
}
unseen := int32(0)
for _, key := range selection.FamilyKeys {
if _, exists := seen[key]; !exists {
unseen++
}
}
if unseen >= minimum {
return true
}
}
return false
}
func availabilityLanguages(
specialization domain.SpecializationCode,
selections []outbound.AssessmentAvailabilitySelection,
) []domain.TaskLanguageCode {
var languages []domain.TaskLanguageCode
for _, selection := range selections {
if selection.Specialization != specialization {
continue
}
for _, language := range selection.TaskLanguages {
if !slices.Contains(languages, language) {
languages = append(languages, language)
}
}
}
return languages
}
func uniqueAvailabilitySelection(
selections []outbound.AssessmentAvailabilitySelection,
specialization domain.SpecializationCode,
grade domain.GradeCode,
language domain.TaskLanguageCode,
) (outbound.AssessmentAvailabilitySelection, bool) {
var match outbound.AssessmentAvailabilitySelection
count := 0
for _, selection := range selections {
if selection.Specialization != specialization || selection.Grade != grade {
continue
}
if language == "" && len(selection.TaskLanguages) == 0 || slices.Contains(selection.TaskLanguages, language) {
match = selection
count++
}
}
return match, count == 1
}
func rootCooldownUntil(
roots []outbound.AssessmentRootAvailabilitySummary,
target domain.GradeCode,
policy domain.AssessmentPolicy,
quota outbound.AssessmentRootQuotaSnapshot,
now time.Time,
) *time.Time {
latest, latestSameGrade := latestAvailabilityRoots(roots, target)
var blockedUntil time.Time
blockedUntil = sameGradeAvailabilityCooldown(blockedUntil, latestSameGrade, policy, now)
blockedUntil = latestRootAvailabilityCooldown(blockedUntil, latest, target, policy, now)
if quota.Count >= policy.MaxAttemptsPerWindow && quota.AvailableAt != nil {
blockedUntil = laterAvailability(blockedUntil, *quota.AvailableAt, now)
}
if blockedUntil.IsZero() {
return nil
}
availableAt := blockedUntil.UTC().Truncate(time.Microsecond)
return &availableAt
}
func latestAvailabilityRoots(
roots []outbound.AssessmentRootAvailabilitySummary,
target domain.GradeCode,
) (*outbound.AssessmentRootAvailabilitySummary, *outbound.AssessmentRootAvailabilitySummary) {
var latest *outbound.AssessmentRootAvailabilitySummary
var latestSameGrade *outbound.AssessmentRootAvailabilitySummary
for index := range roots {
root := &roots[index]
if latest == nil || root.RootCreatedAt.After(latest.RootCreatedAt) {
latest = root
}
if root.RootTargetGrade == target &&
(latestSameGrade == nil || root.RootCreatedAt.After(latestSameGrade.RootCreatedAt)) {
latestSameGrade = root
}
}
return latest, latestSameGrade
}
func sameGradeAvailabilityCooldown(
blockedUntil time.Time,
latestSameGrade *outbound.AssessmentRootAvailabilitySummary,
policy domain.AssessmentPolicy,
now time.Time,
) time.Time {
if latestSameGrade != nil {
updatedAt := effectiveAvailabilityUpdatedAt(latestSameGrade.RootState, latestSameGrade.RootUpdatedAt, latestSameGrade.RootExpiresAt, now)
blockedUntil = laterAvailability(blockedUntil, updatedAt.Add(policy.SameGradeRetryAfter.Duration()), now)
}
return blockedUntil
}
func latestRootAvailabilityCooldown(
blockedUntil time.Time,
latest *outbound.AssessmentRootAvailabilitySummary,
target domain.GradeCode,
policy domain.AssessmentPolicy,
now time.Time,
) time.Time {
if latest != nil {
lastUpdatedAt := effectiveAvailabilityUpdatedAt(latest.LatestState, latest.LatestUpdatedAt, latest.LatestExpiresAt, now)
platformFailure := latest.LatestState == domain.AssessmentAttemptStateInsufficientBank ||
isPlatformAttemptFailure(latest.LatestPlatformError)
if !platformFailure &&
availabilityCorrectionWindowOpen(latest, now) {
blockedUntil = laterAvailability(blockedUntil, latest.LatestChainDeadline, now)
}
if !platformFailure && gradeRank(target) > gradeRank(latest.LatestTargetGrade) {
blockedUntil = laterAvailability(blockedUntil, lastUpdatedAt.Add(policy.PromotionMinInterval.Duration()), now)
}
}
return blockedUntil
}
func effectiveAvailabilityUpdatedAt(
state domain.AssessmentAttemptState,
updatedAt, expiresAt, now time.Time,
) time.Time {
if isAssessmentAttemptActiveState(state) && !expiresAt.After(now) {
// A read-only preflight may notice expiry after the deadline. Use the
// attempt's fixed deadline as the transition time so polling cannot
// extend the retry interval.
return expiresAt
}
return updatedAt
}
func availabilityCorrectionWindowOpen(root *outbound.AssessmentRootAvailabilitySummary, now time.Time) bool {
if !root.LatestChainDeadline.After(root.RootCreatedAt) || !now.Before(root.LatestChainDeadline) {
return false
}
if root.LatestState == domain.AssessmentAttemptStateInsufficientBank ||
isPlatformAttemptFailure(root.LatestPlatformError) {
return false
}
switch root.LatestState {
case domain.AssessmentAttemptStateInProgress,
domain.AssessmentAttemptStatePracticePending,
domain.AssessmentAttemptStateAdditionalPracticePending,
domain.AssessmentAttemptStateReadyToFinalize:
// The GET does not write the expiry transition. An expired active
// attempt still holds its correction chain until the immutable chain
// deadline, matching the POST path that records expiry at expires_at.
return !root.LatestExpiresAt.After(now) && root.LatestOutcome == ""
case domain.AssessmentAttemptStateInsufficientBank:
return false
case domain.AssessmentAttemptStateExpired:
return root.LatestOutcome == ""
case domain.AssessmentAttemptStateCompleted:
return root.LatestOutcome == domain.AssessmentAttemptOutcomeNotConfirmed ||
root.LatestOutcome == domain.AssessmentAttemptOutcomeNotDetermined
default:
return false
}
}
func isAssessmentAttemptActiveState(state domain.AssessmentAttemptState) bool {
switch state {
case domain.AssessmentAttemptStateInProgress, domain.AssessmentAttemptStatePracticePending,
domain.AssessmentAttemptStateAdditionalPracticePending, domain.AssessmentAttemptStateReadyToFinalize:
return true
case domain.AssessmentAttemptStateCompleted, domain.AssessmentAttemptStateExpired,
domain.AssessmentAttemptStateInsufficientBank:
return false
default:
return false
}
}
func isPlatformAttemptFailure(reason string) bool {
return reason == "insufficient_bank" || reason == "sandbox_unavailable"
}
func laterAvailability(current, candidate, now time.Time) time.Time {
if !candidate.After(now) {
return current
}
if current.IsZero() || candidate.After(current) {
return candidate
}
return current
}
@@ -0,0 +1,100 @@
package assessment
import (
"testing"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestExpiredActiveAttemptCooldownDoesNotMoveWithAvailabilityReads(t *testing.T) {
createdAt := time.Date(2026, time.January, 1, 12, 0, 0, 0, time.UTC)
expiresAt := createdAt.Add(24 * time.Hour)
chainDeadline := createdAt.Add(72 * time.Hour)
root := outbound.AssessmentRootAvailabilitySummary{
RootTargetGrade: domain.GradeJunior,
RootCreatedAt: createdAt,
RootUpdatedAt: createdAt.Add(12 * time.Hour),
RootExpiresAt: expiresAt,
RootState: domain.AssessmentAttemptStateInProgress,
RootChainDeadline: chainDeadline,
LatestTargetGrade: domain.GradeJunior,
LatestUpdatedAt: createdAt.Add(12 * time.Hour),
LatestExpiresAt: expiresAt,
LatestState: domain.AssessmentAttemptStateInProgress,
LatestChainDeadline: chainDeadline,
}
policy := domain.AssessmentPolicy{SameGradeRetryAfter: 7}
firstReadAt := expiresAt.Add(time.Hour)
secondReadAt := firstReadAt.Add(6 * time.Hour)
want := expiresAt.Add(7 * 24 * time.Hour)
for _, now := range []time.Time{firstReadAt, secondReadAt} {
got := rootCooldownUntil([]outbound.AssessmentRootAvailabilitySummary{root}, domain.GradeJunior, policy,
outbound.AssessmentRootQuotaSnapshot{}, now)
if got == nil || !got.Equal(want) {
t.Fatalf("rootCooldownUntil(%s) = %v, want fixed expiry-based deadline %s", now, got, want)
}
}
if got := rootCooldownUntil([]outbound.AssessmentRootAvailabilitySummary{root}, domain.GradeJunior, policy,
outbound.AssessmentRootQuotaSnapshot{}, want); got != nil {
t.Fatalf("rootCooldownUntil(after deadline) = %s, want no cooldown", got)
}
}
func TestExpiredActiveAttemptUsesNaturalExpiryForRetryTimestamp(t *testing.T) {
updatedAt := time.Date(2026, time.January, 2, 10, 0, 0, 0, time.UTC)
expiresAt := updatedAt.Add(-time.Hour)
now := updatedAt.Add(30 * time.Minute)
if got := effectiveAvailabilityUpdatedAt(domain.AssessmentAttemptStateInProgress, updatedAt, expiresAt, now); !got.Equal(expiresAt) {
t.Fatalf("effectiveAvailabilityUpdatedAt() = %s, want original expiry %s", got, expiresAt)
}
root := &outbound.AssessmentRootAvailabilitySummary{
RootCreatedAt: expiresAt.Add(-24 * time.Hour),
LatestState: domain.AssessmentAttemptStateInProgress,
LatestOutcome: "",
LatestExpiresAt: expiresAt,
LatestChainDeadline: expiresAt.Add(48 * time.Hour),
}
if !availabilityCorrectionWindowOpen(root, now) {
t.Fatal("expired active attempt should hold the correction chain until its fixed deadline")
}
if availabilityCorrectionWindowOpen(root, root.LatestChainDeadline) {
t.Fatal("correction chain should close at its fixed deadline")
}
}
func TestPlatformFailureDoesNotAddPromotionCooldown(t *testing.T) {
now := time.Date(2026, time.January, 4, 12, 0, 0, 0, time.UTC)
updatedAt := now.Add(-time.Hour)
policy := domain.AssessmentPolicy{PromotionMinInterval: 90}
tests := []struct {
name string
state domain.AssessmentAttemptState
reason string
}{
{name: "sandbox failure result", state: domain.AssessmentAttemptStateCompleted, reason: "sandbox_unavailable"},
{name: "insufficient bank state", state: domain.AssessmentAttemptStateInsufficientBank},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
root := outbound.AssessmentRootAvailabilitySummary{
RootTargetGrade: domain.GradeJunior,
RootCreatedAt: now.Add(-48 * time.Hour),
RootUpdatedAt: now.Add(-48 * time.Hour),
RootState: domain.AssessmentAttemptStateCompleted,
LatestTargetGrade: domain.GradeMiddle,
LatestUpdatedAt: updatedAt,
LatestExpiresAt: updatedAt.Add(-time.Hour),
LatestState: test.state,
LatestPlatformError: test.reason,
}
if got := rootCooldownUntil([]outbound.AssessmentRootAvailabilitySummary{root}, domain.GradeSenior,
policy, outbound.AssessmentRootQuotaSnapshot{}, now); got != nil {
t.Fatalf("rootCooldownUntil() = %s, want no platform-failure cooldown", got)
}
})
}
}
@@ -0,0 +1,404 @@
package assessment
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const finalizeAttemptOperation = "assessment_attempt.finalize"
type FinalizeAssessmentAttemptCommand struct {
ActorID uuid.UUID
AttemptID domain.AssessmentAttemptID
ExpectedVersion int64
IdempotencyKey string
}
type canonicalAttemptFinalizeBody struct {
AttemptID string `json:"attempt_id"`
ExpectedVersion int64 `json:"expected_version"`
}
// AssessmentAttemptResult contains only the candidate-visible result data.
type AssessmentAttemptResult struct {
Attempt domain.AssessmentAttemptPublicSnapshot
Outcome domain.AssessmentAttemptOutcome
NotDeterminedReason string
BasicScore *domain.AssessmentBasicScore
Limitations []string
Summary string
DecidedAt time.Time
}
// FinalizeAttempt stores a pinned-policy decision and its idempotent response
// in the same transaction as the attempt transition.
func (service *AttemptService) FinalizeAttempt(
ctx context.Context,
command FinalizeAssessmentAttemptCommand,
) (outbound.AssessmentAttemptCommandResult, error) {
const location = "AttemptService.FinalizeAttempt"
if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || command.ExpectedVersion < 1 {
return outbound.AssessmentAttemptCommandResult{}, ErrInvalidAttemptRequest
}
body, err := json.Marshal(canonicalAttemptFinalizeBody{
AttemptID: command.AttemptID.String(), ExpectedVersion: command.ExpectedVersion,
})
if err != nil || len(body) > maxAttemptCanonicalBodyBytes {
return outbound.AssessmentAttemptCommandResult{}, ErrInvalidAttemptRequest
}
keyTime, err := assessmentIdempotencyTime(service.clock())
if err != nil {
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - validate application time: %w", location, err)
}
request, err := service.prepareAttemptIdempotency(finalizeAttemptOperation, command.IdempotencyKey, command.ActorID, body, keyTime)
if err != nil {
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - prepare idempotency: %w", location, err)
}
var result outbound.AssessmentAttemptCommandResult
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil {
return err
}
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return fmt.Errorf("%s - reserve idempotency: %w", location, err)
}
repository := unit.AssessmentAttempts()
if !created {
return replayAttemptFinalize(ctx, repository, request, stored, &result)
}
if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil {
return fmt.Errorf("%s - remove expired finalize response: %w", location, err)
}
return service.finalizeNewAttempt(ctx, unit, repository, request.scope, command, &result)
})
if err != nil {
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
func replayAttemptFinalize(
ctx context.Context,
repository outbound.AssessmentAttemptRepository,
request attemptIdempotencyRequest,
stored outbound.IdempotencyRecord,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "assessment.replayAttemptFinalize"
if stored.Fingerprint != request.record.Fingerprint {
return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused)
}
outcome, err := repository.GetFinalizeOutcome(ctx, request.scope)
if err != nil {
return fmt.Errorf("%s - read immutable finalize response: %w", location, err)
}
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome, Replayed: true}
return nil
}
func (service *AttemptService) finalizeNewAttempt(
ctx context.Context,
unit outbound.UnitOfWork,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
command FinalizeAssessmentAttemptCommand,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "AttemptService.finalizeNewAttempt"
current, err := lockAttemptForFinalize(ctx, unit, repository, command)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return storeAttemptCommandProblem(ctx, repository, scope, "finalize", 404, result)
}
if err != nil {
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
}
if current.State() != domain.AssessmentAttemptStateCompleted && command.ExpectedVersion != current.Version() {
return fmt.Errorf("%s - check expected version: %w", location, ErrAttemptVersionConflict)
}
if current.State() == domain.AssessmentAttemptStateCompleted {
return storeCompletedFinalize(ctx, repository, scope, command, current, result)
}
return service.finalizeActiveAttempt(ctx, unit, repository, scope, command, current, result)
}
func lockAttemptForFinalize(
ctx context.Context,
unit outbound.UnitOfWork,
repository outbound.AssessmentAttemptRepository,
command FinalizeAssessmentAttemptCommand,
) (domain.AssessmentAttempt, error) {
const location = "AttemptService.lockAttemptForFinalize"
kind, err := repository.GetKindForCandidate(ctx, command.ActorID, command.AttemptID)
if err != nil {
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound
}
return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
}
if err := lockSessionConsent(ctx, unit, command.ActorID, kind); err != nil {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - authorize finalization: %w", location, err)
}
current, err := repository.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID)
if err != nil {
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound
}
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
}
if current.Kind() != kind {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt)
}
return current, nil
}
func storeCompletedFinalize(
ctx context.Context,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
command FinalizeAssessmentAttemptCommand,
current domain.AssessmentAttempt,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "AttemptService.storeCompletedFinalize"
if _, err := repository.GetResult(ctx, command.ActorID, command.AttemptID); err != nil {
return fmt.Errorf("%s - completed attempt has no immutable result: %w", location, err)
}
outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: current.PublicSnapshot()}
if err := repository.SaveFinalizeOutcome(ctx, scope, outcome); err != nil {
return fmt.Errorf("%s - store completed finalize response: %w", location, err)
}
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome}
return nil
}
func (service *AttemptService) finalizeActiveAttempt(
ctx context.Context,
unit outbound.UnitOfWork,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
command FinalizeAssessmentAttemptCommand,
current domain.AssessmentAttempt,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "AttemptService.finalizeActiveAttempt"
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err)
}
databaseTime = databaseTime.UTC().Truncate(time.Microsecond)
policyID := current.Snapshot().Versions.ProductPolicyVersionID
policy, err := unit.Policies().GetByID(ctx, policyID)
if err != nil {
return fmt.Errorf("%s - read pinned product policy: %w", location, err)
}
if current.State() == domain.AssessmentAttemptStateInProgress {
expired, changed, expireErr := current.ExpireIfDue(databaseTime)
if expireErr != nil {
return fmt.Errorf("%s - apply due attempt deadline: %w", location, expireErr)
}
if changed {
if err := repository.SaveTransition(ctx, current, expired); err != nil {
return fmt.Errorf("%s - persist due attempt deadline: %w", location, err)
}
return storeAttemptCommandProblem(ctx, repository, scope, "finalize", 409, result)
}
}
if pendingItemIDs := current.PendingItemIDs(); len(pendingItemIDs) > 0 {
return storeFinalizePendingItems(ctx, repository, scope, pendingItemIDs, result)
}
updated, changed, decision, finalizeErr := current.FinalizeDemo(
command.ExpectedVersion, policy.Policy().Assessment, databaseTime,
)
if finalizeErr != nil {
if errors.Is(finalizeErr, domain.ErrAssessmentAttemptVersionConflict) {
return fmt.Errorf("%s - check expected version: %w", location, ErrAttemptVersionConflict)
}
if errors.Is(finalizeErr, domain.ErrAssessmentAttemptNotActive) {
return storeAttemptCommandProblem(ctx, repository, scope, "finalize", 409, result)
}
return fmt.Errorf("%s - calculate pinned decision: %w", location, finalizeErr)
}
return persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, result)
}
func persistFinalizedAttempt(
ctx context.Context,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
command FinalizeAssessmentAttemptCommand,
current, updated domain.AssessmentAttempt,
changed bool,
decision domain.AssessmentAttemptDecision,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "AttemptService.persistFinalizedAttempt"
if changed {
if err := repository.SaveTransition(ctx, current, updated); err != nil {
return fmt.Errorf("%s - persist final decision: %w", location, err)
}
summary, limitations := assessmentFinalizedResultPresentation(updated.Kind())
storedResult, err := domain.NewAssessmentAttemptResultSnapshot(updated, decision, summary, limitations)
if err != nil {
return fmt.Errorf("%s - build immutable result snapshot: %w", location, err)
}
if err := repository.SaveResult(ctx, command.ActorID, storedResult); err != nil {
return fmt.Errorf("%s - persist immutable result snapshot: %w", location, err)
}
}
outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: updated.PublicSnapshot()}
if err := repository.SaveFinalizeOutcome(ctx, scope, outcome); err != nil {
return fmt.Errorf("%s - store immutable finalize response: %w", location, err)
}
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome}
return nil
}
func assessmentFinalizedResultPresentation(kind domain.AssessmentAttemptKind) (string, []string) {
if kind == domain.AssessmentAttemptKindDemoExpress {
return "This training run is educational only. It does not assess or confirm a grade.", []string{"demonstration_only"}
}
return "", []string{"uncalibrated_thresholds", "demo_bank", "practice_not_included", "unproctored"}
}
// GetMyResult returns an immutable completed result or a terminal no-result projection.
func (service *AttemptService) GetMyResult(
ctx context.Context,
userID uuid.UUID,
attemptID domain.AssessmentAttemptID,
) (AssessmentAttemptResult, error) {
const location = "AttemptService.GetMyResult"
if userID == uuid.Nil || attemptID.IsZero() {
return AssessmentAttemptResult{}, fmt.Errorf("%s - candidate and attempt IDs are required: %w", location, ErrAttemptForbidden)
}
var result AssessmentAttemptResult
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireAttemptCandidate(ctx, unit, userID, location); err != nil {
return err
}
var readErr error
result, readErr = service.readAttemptResult(ctx, unit, userID, attemptID)
return readErr
})
if err != nil {
return AssessmentAttemptResult{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
func (service *AttemptService) readAttemptResult(
ctx context.Context,
unit outbound.UnitOfWork,
userID uuid.UUID,
attemptID domain.AssessmentAttemptID,
) (AssessmentAttemptResult, error) {
const location = "AttemptService.readAttemptResult"
attempt, err := unit.AssessmentAttempts().GetForCandidate(ctx, userID, attemptID)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return AssessmentAttemptResult{}, fmt.Errorf("%s - read owner-scoped attempt: %w", location, ErrAttemptNotFound)
}
if err != nil {
return AssessmentAttemptResult{}, fmt.Errorf("%s - read owner-scoped attempt: %w", location, err)
}
snapshot := attempt.Snapshot()
if err := validateAttemptResultState(snapshot); err != nil {
return AssessmentAttemptResult{}, fmt.Errorf("%s - validate terminal attempt: %w", location, err)
}
if snapshot.State == domain.AssessmentAttemptStateCompleted {
return readCompletedAttemptResult(ctx, unit, userID, attemptID, attempt)
}
return terminalAttemptResult(attempt)
}
func validateAttemptResultState(snapshot domain.AssessmentAttemptSnapshot) error {
switch snapshot.State {
case domain.AssessmentAttemptStateCompleted, domain.AssessmentAttemptStateExpired,
domain.AssessmentAttemptStateInsufficientBank:
if snapshot.EndedAt.IsZero() {
return domain.ErrInvalidAssessmentAttempt
}
return nil
case domain.AssessmentAttemptStateInProgress, domain.AssessmentAttemptStatePracticePending,
domain.AssessmentAttemptStateAdditionalPracticePending, domain.AssessmentAttemptStateReadyToFinalize:
return ErrAttemptStateConflict
default:
return domain.ErrInvalidAssessmentAttempt
}
}
func readCompletedAttemptResult(
ctx context.Context,
unit outbound.UnitOfWork,
userID uuid.UUID,
attemptID domain.AssessmentAttemptID,
attempt domain.AssessmentAttempt,
) (AssessmentAttemptResult, error) {
const location = "AttemptService.readCompletedAttemptResult"
stored, err := unit.AssessmentAttempts().GetResult(ctx, userID, attemptID)
if err != nil {
return AssessmentAttemptResult{}, fmt.Errorf("%s - read immutable result: %w", location, err)
}
if !assessmentResultMatchesAttempt(stored, attempt) {
return AssessmentAttemptResult{}, fmt.Errorf("%s - immutable result does not match its attempt: %w", location, domain.ErrInvalidAssessmentAttempt)
}
return assessmentAttemptResultFromSnapshot(stored), nil
}
func terminalAttemptResult(attempt domain.AssessmentAttempt) (AssessmentAttemptResult, error) {
snapshot := attempt.Snapshot()
result := AssessmentAttemptResult{Attempt: attempt.PublicSnapshot(), DecidedAt: snapshot.EndedAt}
switch snapshot.Kind {
case domain.AssessmentAttemptKindDemoExpress:
result.Outcome = domain.AssessmentAttemptOutcomeDemonstration
result.Summary = "This training run ended before completion. It does not assess or confirm a grade."
case domain.AssessmentAttemptKindRoot, domain.AssessmentAttemptKindCorrective:
result.Limitations = []string{"uncalibrated_thresholds", "demo_bank", "practice_not_included", "unproctored"}
result.Outcome = domain.AssessmentAttemptOutcomeNotDetermined
if snapshot.State == domain.AssessmentAttemptStateExpired {
result.NotDeterminedReason = "expired"
} else {
result.NotDeterminedReason = "insufficient_bank"
}
default:
return AssessmentAttemptResult{}, fmt.Errorf("AttemptService.terminalAttemptResult - attempt kind is unsupported: %w", domain.ErrInvalidAssessmentAttempt)
}
return result, nil
}
func assessmentResultMatchesAttempt(
result domain.AssessmentAttemptResultSnapshot,
attempt domain.AssessmentAttempt,
) bool {
snapshot := attempt.Snapshot()
pins := result.Pins
public := attempt.PublicSnapshot()
return reflect.DeepEqual(result.Attempt, public) && result.Outcome == snapshot.Outcome &&
result.Attempt.FinishedAt != nil && snapshot.EndedAt.Equal(*result.Attempt.FinishedAt) &&
pins.ProductPolicyVersionID == snapshot.Versions.ProductPolicyVersionID &&
pins.ProductPolicyVersion == snapshot.Versions.ProductPolicyVersion &&
pins.GradingPolicyVersionID == snapshot.Versions.GradingPolicyVersionID &&
pins.OpeningID == snapshot.Versions.OpeningID && pins.OpeningManifestHash == snapshot.Versions.OpeningManifestHash &&
pins.TrainingBindingID == snapshot.Versions.TrainingBindingID &&
pins.TrainingManifestHash == snapshot.Versions.TrainingManifestHash &&
pins.BankVersion == snapshot.Versions.BankVersion && pins.AlgorithmVersion == snapshot.Versions.AlgorithmVersion
}
func assessmentAttemptResultFromSnapshot(
snapshot domain.AssessmentAttemptResultSnapshot,
) AssessmentAttemptResult {
return AssessmentAttemptResult{
Attempt: snapshot.Attempt, Outcome: snapshot.Outcome,
NotDeterminedReason: snapshot.NotDeterminedReason,
BasicScore: snapshot.BasicScore, Limitations: append([]string{}, snapshot.Limitations...),
Summary: snapshot.Summary, DecidedAt: snapshot.DecidedAt,
}
}
@@ -0,0 +1,380 @@
package assessment
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
assessmentSignalOperation = "assessment_attempt.signals"
assessmentSignalRateWindow = time.Minute
assessmentSignalMaxReceipts = int64(30)
assessmentSignalMaxEvents = int64(10000)
assessmentSignalTimestampSkew = 5 * time.Minute
assessmentSignalMaximumBodySize = 32 << 10
assessmentSignalMaximumEvents = 50
)
var (
ErrAttemptSignalForbidden = errors.New("assessment signals are forbidden")
ErrAttemptSignalConsentRequired = errors.New("assessment signals require current C3 consent")
ErrAttemptSignalStateConflict = errors.New("assessment attempt cannot accept signals")
ErrAttemptSignalRateLimited = errors.New("assessment signal receipt rate limit exceeded")
ErrInvalidAttemptSignalRequest = errors.New("invalid assessment signal request")
)
// SignalRateLimitError carries the first time a new receipt can be retried.
// Its message contains no candidate, attempt, or event data.
type SignalRateLimitError struct {
RetryAt time.Time
}
func (limitError *SignalRateLimitError) Error() string {
return ErrAttemptSignalRateLimited.Error()
}
func (limitError *SignalRateLimitError) Unwrap() error {
return ErrAttemptSignalRateLimited
}
// SignalService stores bounded client-reported event metadata for real
// assessment attempts. The signals do not participate in grading.
type SignalService struct {
transactor outbound.Transactor
keyring Keyring
clock func() time.Time
}
func NewSignalService(transactor outbound.Transactor, keyring Keyring, clock func() time.Time) (*SignalService, error) {
if transactor == nil || keyring == nil || clock == nil {
return nil, errors.New("assessment.NewSignalService - every dependency must be set")
}
return &SignalService{transactor: transactor, keyring: keyring, clock: clock}, nil
}
type RecordSignalsCommand struct {
ActorID uuid.UUID
AttemptID domain.AssessmentAttemptID
IdempotencyKey string
Events []domain.AssessmentSignalEvent
}
type canonicalSignalRequest struct {
AttemptID string `json:"attempt_id"`
Events []canonicalSignalEvent `json:"events"`
}
type canonicalSignalEvent struct {
Kind domain.AssessmentSignalKind `json:"kind"`
ItemInstanceID uuid.UUID `json:"item_instance_id"`
OccurredAt time.Time `json:"occurred_at"`
DurationMS *int32 `json:"duration_ms,omitempty"`
SizeBytes *int32 `json:"size_bytes,omitempty"`
}
type signalIdempotencyRequest struct {
scope outbound.AssessmentAttemptIdempotencyScope
record outbound.IdempotencyRecord
}
// RecordSignals stores all events in a batch or stores none. A replay returns
// the original receipt without rechecking or repeating storage effects.
func (service *SignalService) RecordSignals(
ctx context.Context,
command RecordSignalsCommand,
) (domain.AssessmentSignalReceipt, error) {
const location = "SignalService.RecordSignals"
canonicalEvents, body, err := canonicalSignalBody(command)
if err != nil {
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - validate request: %w", location, err)
}
now, err := assessmentIdempotencyTime(service.clock())
if err != nil {
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - validate application time: %w", location, err)
}
request, err := service.prepareSignalIdempotency(command, body, now)
if err != nil {
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - prepare idempotency: %w", location, err)
}
var receipt domain.AssessmentSignalReceipt
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil {
return err
}
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return fmt.Errorf("%s - reserve idempotency: %w", location, err)
}
repository := unit.AssessmentSignals()
if !created {
if stored.Fingerprint != request.record.Fingerprint {
return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused)
}
if err := requireReplayableSignalAttempt(ctx, unit, command); err != nil {
return fmt.Errorf("%s - verify owner-scoped attempt before replay: %w", location, err)
}
receipt, err = repository.GetOutcome(ctx, request.scope)
if err != nil {
if errors.Is(err, outbound.ErrAssessmentSignalOutcomeNotFound) {
if attemptErr := requireReplayableSignalAttempt(ctx, unit, command); attemptErr != nil {
return fmt.Errorf("%s - verify attempt after missing receipt: %w", location, attemptErr)
}
}
return fmt.Errorf("%s - read immutable receipt: %w", location, err)
}
return nil
}
if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil {
return fmt.Errorf("%s - remove expired receipt: %w", location, err)
}
return service.recordNewSignals(ctx, unit, repository, command, canonicalEvents, request.scope, &receipt)
})
if err != nil {
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return receipt, nil
}
func requireReplayableSignalAttempt(ctx context.Context, unit outbound.UnitOfWork, command RecordSignalsCommand) error {
const location = "SignalService.requireReplayableSignalAttempt"
kind, err := unit.AssessmentAttempts().GetKindForCandidate(ctx, command.ActorID, command.AttemptID)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return fmt.Errorf("%s - owner-scoped attempt is missing: %w", location, ErrAttemptNotFound)
}
if err != nil {
return fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
}
if kind != domain.AssessmentAttemptKindRoot && kind != domain.AssessmentAttemptKindCorrective {
return fmt.Errorf("%s - training attempts do not have signal receipts: %w", location, ErrAttemptSignalStateConflict)
}
return nil
}
func (service *SignalService) recordNewSignals(
ctx context.Context,
unit outbound.UnitOfWork,
repository outbound.AssessmentSignalRepository,
command RecordSignalsCommand,
events []domain.AssessmentSignalEvent,
scope outbound.AssessmentAttemptIdempotencyScope,
receipt *domain.AssessmentSignalReceipt,
) error {
const location = "SignalService.recordNewSignals"
attempt, err := lockAttemptForSignals(ctx, unit, command)
if err != nil {
return fmt.Errorf("%s - lock attempt and C3 consent: %w", location, err)
}
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err)
}
databaseTime = databaseTime.UTC().Truncate(time.Microsecond)
if !attempt.IsActive() || !databaseTime.Before(attempt.ExpiresAt()) {
return fmt.Errorf("%s - attempt is terminal or expired: %w", location, ErrAttemptSignalStateConflict)
}
if err := validateSignalItemsAndTimes(attempt, events, databaseTime); err != nil {
return fmt.Errorf("%s - validate item binding and timestamp: %w", location, err)
}
if err := checkSignalReceiptRate(ctx, repository, attempt.ID(), databaseTime); err != nil {
return fmt.Errorf("%s - check receipt rate: %w", location, err)
}
status, acceptedCount, err := service.persistSignalBatch(ctx, repository, attempt.ID(), events, databaseTime)
if err != nil {
return fmt.Errorf("%s - persist bounded event batch: %w", location, err)
}
newReceipt, err := domain.NewAssessmentSignalReceipt(status, acceptedCount, databaseTime)
if err != nil {
return fmt.Errorf("%s - build receipt: %w", location, err)
}
if err := repository.SaveOutcome(ctx, scope, attempt.ID(), newReceipt); err != nil {
return fmt.Errorf("%s - store immutable receipt: %w", location, err)
}
*receipt = newReceipt
return nil
}
func lockAttemptForSignals(
ctx context.Context,
unit outbound.UnitOfWork,
command RecordSignalsCommand,
) (domain.AssessmentAttempt, error) {
const location = "SignalService.lockAttemptForSignals"
attempts := unit.AssessmentAttempts()
kind, err := attempts.GetKindForCandidate(ctx, command.ActorID, command.AttemptID)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, ErrAttemptNotFound)
}
if err != nil {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
}
if kind != domain.AssessmentAttemptKindRoot && kind != domain.AssessmentAttemptKindCorrective {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - training attempts do not accept signals: %w", location, ErrAttemptSignalStateConflict)
}
if _, err := unit.ConsentLedger().LockCurrentForUse(ctx, command.ActorID, domain.ConsentPurposeAutoCategorization); err != nil {
if errors.Is(err, outbound.ErrConsentNotFound) {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - require current C3 consent: %w", location, ErrAttemptSignalConsentRequired)
}
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock current C3 consent: %w", location, err)
}
attempt, err := attempts.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, ErrAttemptNotFound)
}
if err != nil {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
}
if attempt.Kind() != kind {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt)
}
return attempt, nil
}
func checkSignalReceiptRate(
ctx context.Context,
repository outbound.AssessmentSignalRepository,
attemptID domain.AssessmentAttemptID,
databaseTime time.Time,
) error {
const location = "SignalService.checkSignalReceiptRate"
count, oldest, err := repository.CountRecentOutcomes(ctx, attemptID, databaseTime.Add(-assessmentSignalRateWindow))
if err != nil {
return fmt.Errorf("%s - count recent receipts: %w", location, err)
}
if count < assessmentSignalMaxReceipts {
return nil
}
retryAt := oldest.Add(assessmentSignalRateWindow).UTC().Truncate(time.Microsecond)
if !retryAt.After(databaseTime) {
retryAt = databaseTime.Add(time.Second).Truncate(time.Second)
}
return fmt.Errorf("%s - wait for the next receipt window: %w", location, &SignalRateLimitError{RetryAt: retryAt})
}
func (service *SignalService) persistSignalBatch(
ctx context.Context,
repository outbound.AssessmentSignalRepository,
attemptID domain.AssessmentAttemptID,
events []domain.AssessmentSignalEvent,
databaseTime time.Time,
) (domain.AssessmentSignalReceiptStatus, int32, error) {
const location = "SignalService.persistSignalBatch"
acceptedCount, err := assessmentSignalEventCount(len(events))
if err != nil {
return "", 0, fmt.Errorf("%s - event count is invalid: %w", location, err)
}
storedCount, err := repository.CountAttemptEvents(ctx, attemptID)
if err != nil {
return "", 0, fmt.Errorf("%s - count stored events: %w", location, err)
}
if storedCount+int64(len(events)) > assessmentSignalMaxEvents {
return domain.AssessmentSignalReceiptSaturated, 0, nil
}
batchID, err := uuid.NewV7()
if err != nil {
return "", 0, fmt.Errorf("%s - generate batch ID: %w", location, err)
}
batch, err := domain.NewAssessmentSignalBatch(batchID, attemptID, databaseTime, events)
if err != nil {
return "", 0, fmt.Errorf("%s - build event batch: %w", location, err)
}
if err := repository.SaveBatch(ctx, batch); err != nil {
return "", 0, fmt.Errorf("%s - store event batch: %w", location, err)
}
return domain.AssessmentSignalReceiptAccepted, acceptedCount, nil
}
func assessmentSignalEventCount(count int) (int32, error) {
if count < 1 || count > assessmentSignalMaximumEvents {
return 0, ErrInvalidAttemptSignalRequest
}
return int32(count), nil
}
func (service *SignalService) prepareSignalIdempotency(
command RecordSignalsCommand,
body []byte,
now time.Time,
) (signalIdempotencyRequest, error) {
if !validAttemptIdempotencyKey(command.IdempotencyKey) {
return signalIdempotencyRequest{}, ErrInvalidAttemptKey
}
expiresAt := now.Add(outbound.IdempotencyRetention)
if !expiresAt.After(now) || expiresAt.Year() > 9999 {
return signalIdempotencyRequest{}, ErrInvalidAttemptSignalRequest
}
scopeBytes := service.keyring.IdempotencyScope(assessmentSignalOperation, command.IdempotencyKey, command.ActorID.String())
return signalIdempotencyRequest{
scope: outbound.AssessmentAttemptIdempotencyScope(scopeBytes),
record: outbound.IdempotencyRecord{
Scope: scopeBytes, Fingerprint: service.keyring.Fingerprint(body), CreatedAt: now, ExpiresAt: expiresAt,
},
}, nil
}
func canonicalSignalBody(command RecordSignalsCommand) ([]domain.AssessmentSignalEvent, []byte, error) {
if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || len(command.Events) == 0 || len(command.Events) > assessmentSignalMaximumEvents {
return nil, nil, ErrInvalidAttemptSignalRequest
}
canonical := canonicalSignalRequest{AttemptID: command.AttemptID.String(), Events: make([]canonicalSignalEvent, 0, len(command.Events))}
validated := make([]domain.AssessmentSignalEvent, 0, len(command.Events))
for _, event := range command.Events {
duration, hasDuration := event.DurationMS()
size, hasSize := event.SizeBytes()
input := domain.AssessmentSignalEventInput{
Kind: event.Kind(), ItemInstanceID: event.ItemInstanceID(), OccurredAt: event.OccurredAt(),
}
encodedEvent := canonicalSignalEvent{Kind: event.Kind(), ItemInstanceID: event.ItemInstanceID(), OccurredAt: event.OccurredAt()}
if hasDuration {
input.DurationMS = &duration
encodedEvent.DurationMS = &duration
}
if hasSize {
input.SizeBytes = &size
encodedEvent.SizeBytes = &size
}
checked, err := domain.NewAssessmentSignalEvent(input)
if err != nil {
return nil, nil, fmt.Errorf("%w", ErrInvalidAttemptSignalRequest)
}
validated = append(validated, checked)
canonical.Events = append(canonical.Events, encodedEvent)
}
body, err := json.Marshal(canonical)
if err != nil || len(body) == 0 || len(body) > assessmentSignalMaximumBodySize {
return nil, nil, ErrInvalidAttemptSignalRequest
}
return validated, body, nil
}
func validateSignalItemsAndTimes(
attempt domain.AssessmentAttempt,
events []domain.AssessmentSignalEvent,
databaseTime time.Time,
) error {
snapshot := attempt.Snapshot()
itemIDs := make(map[uuid.UUID]struct{}, len(snapshot.Items))
for _, item := range snapshot.Items {
itemIDs[item.ID] = struct{}{}
}
earliest := snapshot.CreatedAt.UTC().Add(-assessmentSignalTimestampSkew)
latest := databaseTime.Add(assessmentSignalTimestampSkew)
for _, event := range events {
if _, exists := itemIDs[event.ItemInstanceID()]; !exists {
return ErrInvalidAttemptSignalRequest
}
occurredAt := event.OccurredAt()
if occurredAt.Before(earliest) || occurredAt.After(latest) {
return ErrInvalidAttemptSignalRequest
}
}
return nil
}
@@ -0,0 +1,120 @@
package assessment
import (
"crypto/sha256"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
type signalKeyring struct{}
func (signalKeyring) IdempotencyScope(operation, key, principal string) [32]byte {
return sha256.Sum256([]byte(operation + ":" + key + ":" + principal))
}
func (signalKeyring) Fingerprint(body []byte) [32]byte {
return sha256.Sum256(body)
}
func TestCanonicalSignalBodyContainsOnlyBoundedAllowlistedFields(t *testing.T) {
attemptID, itemID := domain.AssessmentAttemptID(uuid.New()), uuid.New()
at := time.Date(2026, time.October, 7, 12, 0, 0, 987654321, time.FixedZone("offset", 3*60*60))
size := int32(128)
event, err := domain.NewAssessmentSignalEvent(domain.AssessmentSignalEventInput{
Kind: domain.AssessmentSignalPaste, ItemInstanceID: itemID, OccurredAt: at, SizeBytes: &size,
})
if err != nil {
t.Fatalf("NewAssessmentSignalEvent() error = %v", err)
}
validated, encoded, err := canonicalSignalBody(RecordSignalsCommand{
ActorID: uuid.New(), AttemptID: attemptID, Events: []domain.AssessmentSignalEvent{event},
})
if err != nil {
t.Fatalf("canonicalSignalBody() error = %v", err)
}
if len(validated) != 1 || int64(len(encoded)) > assessmentSignalMaximumBodySize {
t.Fatalf("canonical body has %d events and %d bytes", len(validated), len(encoded))
}
var document map[string]any
if err := json.Unmarshal(encoded, &document); err != nil {
t.Fatalf("json.Unmarshal() error = %v", err)
}
if document["attempt_id"] != attemptID.String() || len(document) != 2 {
t.Fatalf("canonical request keys/value = %+v", document)
}
events, ok := document["events"].([]any)
if !ok || len(events) != 1 {
t.Fatalf("canonical events = %#v", document["events"])
}
fields, ok := events[0].(map[string]any)
if !ok {
t.Fatalf("canonical event = %#v", events[0])
}
if fields["kind"] != "paste" || fields["item_instance_id"] != itemID.String() || fields["size_bytes"] != float64(size) {
t.Fatalf("canonical event fields = %+v", fields)
}
if _, ok := fields["occurred_at"].(string); !ok || len(fields) != 4 {
t.Fatalf("canonical event includes unexpected fields: %+v", fields)
}
for _, forbidden := range []string{"answer", "answer_text", "clipboard", "content", "organization_id", "score"} {
if strings.Contains(string(encoded), forbidden) {
t.Errorf("canonical request contains forbidden term %q", forbidden)
}
}
}
func TestSignalIdempotencyFingerprintBindsAttemptAndRejectsInvalidKeys(t *testing.T) {
actorID, itemID := uuid.New(), uuid.New()
at := time.Now().UTC().Truncate(time.Microsecond)
event, err := domain.NewAssessmentSignalEvent(domain.AssessmentSignalEventInput{
Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID, OccurredAt: at,
})
if err != nil {
t.Fatalf("NewAssessmentSignalEvent() error = %v", err)
}
service := &SignalService{keyring: signalKeyring{}}
command := RecordSignalsCommand{ActorID: actorID, AttemptID: domain.AssessmentAttemptID(uuid.New()), IdempotencyKey: "same-key", Events: []domain.AssessmentSignalEvent{event}}
_, firstBody, err := canonicalSignalBody(command)
if err != nil {
t.Fatalf("canonicalSignalBody(first) error = %v", err)
}
first, err := service.prepareSignalIdempotency(command, firstBody, at)
if err != nil {
t.Fatalf("prepareSignalIdempotency(first) error = %v", err)
}
command.AttemptID = domain.AssessmentAttemptID(uuid.New())
_, secondBody, err := canonicalSignalBody(command)
if err != nil {
t.Fatalf("canonicalSignalBody(second) error = %v", err)
}
second, err := service.prepareSignalIdempotency(command, secondBody, at)
if err != nil {
t.Fatalf("prepareSignalIdempotency(second) error = %v", err)
}
if first.scope != second.scope || first.record.Fingerprint == second.record.Fingerprint {
t.Fatal("same actor key should share its scope and reject a different attempt body")
}
for _, invalidKey := range []string{"", strings.Repeat("a", maxAttemptIdempotencyKeyBytes+1), "key with spaces"} {
command.IdempotencyKey = invalidKey
if _, err := service.prepareSignalIdempotency(command, secondBody, at); !errors.Is(err, ErrInvalidAttemptKey) {
t.Errorf("prepareSignalIdempotency(%q) error = %v, want ErrInvalidAttemptKey", invalidKey, err)
}
}
}
func TestCanonicalSignalBodyRejectsUnbuiltEvents(t *testing.T) {
_, _, err := canonicalSignalBody(RecordSignalsCommand{
ActorID: uuid.New(), AttemptID: domain.AssessmentAttemptID(uuid.New()),
Events: []domain.AssessmentSignalEvent{{}},
})
if err == nil {
t.Fatal("canonicalSignalBody() accepted a zero event")
}
}