chore: checkpoint assessment and inbox integration

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 17:47:30 +03:00
1 parent 88a31ba0d5
commit 5c52fd8b91
31 files changed
+4608 -181

No files matched your search

+23 -4
View File
@@ -59,10 +59,11 @@ func (fieldError *AttemptFieldError) Unwrap() error { return ErrInvalidAttemptRe
// AttemptService creates, reads, and resumes candidate-owned attempts.
type AttemptService struct {
transactor outbound.Transactor
snapshotExecutor outbound.ReadOnlySnapshotTransactor
keyring Keyring
clock func() time.Time
transactor outbound.Transactor
snapshotExecutor outbound.ReadOnlySnapshotTransactor
keyring Keyring
clock func() time.Time
categoryDecisions AssessmentCategoryDecisionService
}
// NewAttemptService fails at startup when a required dependency is missing.
@@ -77,9 +78,27 @@ func NewAttemptService(
}
return &AttemptService{
transactor: transactor, snapshotExecutor: snapshotExecutor, keyring: keyring, clock: clock,
categoryDecisions: NewAssessmentCategoryDecisionService(AssessmentCategoryDecisionSettings{}),
}, nil
}
// NewAttemptServiceWithCategorySettings keeps assignment fail-closed unless
// the caller explicitly enables the synthetic-demo gate.
func NewAttemptServiceWithCategorySettings(
transactor outbound.Transactor,
snapshotExecutor outbound.ReadOnlySnapshotTransactor,
keyring Keyring,
clock func() time.Time,
settings AssessmentCategoryDecisionSettings,
) (*AttemptService, error) {
service, err := NewAttemptService(transactor, snapshotExecutor, keyring, clock)
if err != nil {
return nil, err
}
service.categoryDecisions = NewAssessmentCategoryDecisionService(settings)
return service, nil
}
// CreateAttemptCommand is one of the three disjoint public request shapes.
// All values are private candidate data and must not be logged.
type CreateAttemptCommand struct {
@@ -0,0 +1,176 @@
package assessment
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
ErrAssessmentCategoryRepositoryRequired = errors.New("assessment category repository is required")
ErrAssessmentCategoryHistoryInvalid = errors.New("assessment result history is invalid")
)
// AssessmentCategoryDecisionSettings are explicit runtime gates. The zero
// value denies synthetic demo category assignment.
type AssessmentCategoryDecisionSettings struct {
SyntheticDemoAssignmentsEnabled bool
}
// AssessmentCategoryReviewPins identify one exact reviewed source. The
// repository must not substitute a current opening or a different manifest.
// AssessmentCategoryDecisionRepository is bound to the finalization
// transaction. Its category lock is acquired after the caller has obtained
// C3, candidate/specialization scope, and the attempt row lock, in that order.
// The caller persists the returned result and any current-category update in
// this same transaction; no separate category-history table is needed.
type AssessmentCategoryDecisionRepository interface {
LockCandidateCategory(ctx context.Context, candidateID uuid.UUID, specialization domain.SpecializationCode) error
GetCandidateCategory(
ctx context.Context,
candidateID uuid.UUID,
specialization domain.SpecializationCode,
) (domain.CandidateAssessmentCategory, bool, error)
GetSyntheticCategoryReview(
ctx context.Context,
openingID uuid.UUID,
category domain.AssessmentCategory,
openingManifestHash [32]byte,
productPolicyID domain.PolicyVersionID,
productPolicyVersion int32,
gradingPolicyID domain.PolicyVersionID,
) (domain.AssessmentSyntheticCategoryReview, bool, error)
}
// AssessmentCategoryDecisionPlan contains the immutable v2 result projection
// and the current-state write, if the confirmed grade advances. The caller
// must save both atomically with the completed attempt transition.
type AssessmentCategoryDecisionPlan struct {
Result domain.AssessmentAttemptResultHistoryEntry
Decision domain.AssessmentCategoryDecisionSnapshot
CurrentCategory *domain.CandidateAssessmentCategory
ReplaceCurrent bool
}
// AssessmentCategoryDecisionService applies the explicit synthetic-category
// gate and the reviewed, pinned domain decision. It performs reads and locking
// only; the enclosing finalization transaction persists the plan atomically.
type AssessmentCategoryDecisionService struct {
settings AssessmentCategoryDecisionSettings
}
func NewAssessmentCategoryDecisionService(
settings AssessmentCategoryDecisionSettings,
) AssessmentCategoryDecisionService {
return AssessmentCategoryDecisionService{settings: settings}
}
// PrepareFinalizedResult reads the exact current category and optional
// synthetic review after the caller's C3, candidate/specialization, and
// attempt locks. V1 remains the stored shape for express training results;
// real root/corrective results get a v2 category projection even when the
// feature gate is off, so the contemporaneous current grade is explicit.
func (service AssessmentCategoryDecisionService) PrepareFinalizedResult(
ctx context.Context,
repository AssessmentCategoryDecisionRepository,
attempt domain.AssessmentAttempt,
result domain.AssessmentAttemptResultSnapshot,
policy domain.PolicyVersion,
) (AssessmentCategoryDecisionPlan, error) {
const location = "AssessmentCategoryDecisionService.PrepareFinalizedResult"
if repository == nil {
return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - require repository: %w", location, ErrAssessmentCategoryRepositoryRequired)
}
input := domain.AssessmentCategoryDecisionInput{
Attempt: attempt, Result: result, Policy: policy,
SyntheticDemoCategoryAssignmentEnabled: service.settings.SyntheticDemoAssignmentsEnabled,
}
preflight, err := domain.DecideAssessmentCategory(input)
if err != nil {
return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - validate finalized result: %w", location, err)
}
if attempt.Kind() == domain.AssessmentAttemptKindDemoExpress {
return prepareTrainingCategoryResult(location, result, preflight)
}
return service.prepareRealFinalizedResult(ctx, location, repository, attempt, result, input)
}
func prepareTrainingCategoryResult(
location string,
result domain.AssessmentAttemptResultSnapshot,
decision domain.AssessmentCategoryDecision,
) (AssessmentCategoryDecisionPlan, error) {
legacy, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
if err != nil {
return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - build training result view: %w", location, err)
}
return AssessmentCategoryDecisionPlan{Result: legacy, Decision: decision.Snapshot()}, nil
}
func (service AssessmentCategoryDecisionService) prepareRealFinalizedResult(
ctx context.Context,
location string,
repository AssessmentCategoryDecisionRepository,
attempt domain.AssessmentAttempt,
result domain.AssessmentAttemptResultSnapshot,
input domain.AssessmentCategoryDecisionInput,
) (AssessmentCategoryDecisionPlan, error) {
track := attempt.Snapshot()
if track.Specialization == nil {
return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - finalized real attempt has no specialization: %w", location, domain.ErrInvalidAssessmentCategory)
}
if err := repository.LockCandidateCategory(ctx, track.UserID, *track.Specialization); err != nil {
return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - lock candidate category: %w", location, err)
}
current, found, err := repository.GetCandidateCategory(ctx, track.UserID, *track.Specialization)
if err != nil {
return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - read candidate category: %w", location, err)
}
var currentPointer *domain.CandidateAssessmentCategory
if found {
if current.IsZero() {
return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - repository returned an empty current category: %w", location, domain.ErrInvalidAssessmentCategory)
}
currentPointer = &current
}
if service.settings.SyntheticDemoAssignmentsEnabled {
review, reviewFound, err := repository.GetSyntheticCategoryReview(
ctx,
result.Pins.OpeningID,
track.BankCategory,
result.Pins.OpeningManifestHash,
result.Pins.ProductPolicyVersionID,
result.Pins.ProductPolicyVersion,
result.Pins.GradingPolicyVersionID,
)
if err != nil {
return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - read pinned synthetic review: %w", location, err)
}
if reviewFound {
input.Review = &review
}
}
input.Current = currentPointer
decision, err := domain.DecideAssessmentCategory(input)
if err != nil {
return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - decide category: %w", location, err)
}
decisionSnapshot := decision.Snapshot()
entry, err := domain.NewCategoryAssessmentAttemptResultHistoryEntry(result, decisionSnapshot)
if err != nil {
return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - build immutable result v2 projection: %w", location, err)
}
currentValue, hasCurrent := decision.CurrentCategory()
plan := AssessmentCategoryDecisionPlan{
Result: entry, Decision: decisionSnapshot, ReplaceCurrent: decision.ShouldUpdateCurrent(),
}
if hasCurrent {
plan.CurrentCategory = &currentValue
}
return plan, nil
}
@@ -0,0 +1,245 @@
package assessment
import (
"crypto/hmac"
"context"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
AssessmentResultHistoryDefaultLimit int32 = 20
AssessmentResultHistoryMaxLimit int32 = 50
assessmentResultHistoryMaxCursorBytes = 512
)
var ErrInvalidAssessmentResultHistoryRequest = errors.New("invalid assessment result history request")
// AssessmentResultHistoryRecord is one owner-scoped row returned by the
// existing immutable attempt-result store. CandidateID is private and never
// part of the public response.
type AssessmentResultHistoryRecord struct {
CandidateID uuid.UUID
Entry domain.AssessmentAttemptResultHistoryEntry
}
// AssessmentResultHistoryRepository reads the existing v1/v2 result records.
// Implementations must owner-scope the query and apply the supplied keyset.
type AssessmentResultHistoryRepository interface {
ListCandidateAssessmentResults(
ctx context.Context,
candidateID uuid.UUID,
cursor *outbound.AssessmentAttemptResultCursor,
limit int32,
) (outbound.AssessmentAttemptResultPage, error)
}
type AssessmentResultHistoryPage struct {
Entries []domain.AssessmentAttemptResultHistoryEntry
NextCursor string
}
type AssessmentResultHistoryService struct {
repository AssessmentResultHistoryRepository
keyring Keyring
}
func NewAssessmentResultHistoryService(repository AssessmentResultHistoryRepository, keyring Keyring) AssessmentResultHistoryService {
return AssessmentResultHistoryService{repository: repository, keyring: keyring}
}
// ListMine returns completed root and corrective results in descending
// decided_at, attempt_id order. It does not look up current category state:
// legacy v1 records remain category-unknown and v2 uses only its captured
// current-grade value.
func (service AssessmentResultHistoryService) ListMine(
ctx context.Context,
candidateID uuid.UUID,
cursor string,
limit int32,
) (AssessmentResultHistoryPage, error) {
const location = "AssessmentResultHistoryService.ListMine"
if invalidAssessmentResultHistoryRequest(service.repository, service.keyring, candidateID, cursor, limit) {
return AssessmentResultHistoryPage{}, fmt.Errorf("%s - validate request: %w", location, ErrInvalidAssessmentResultHistoryRequest)
}
if limit == 0 {
limit = AssessmentResultHistoryDefaultLimit
}
keyset, err := decodeAssessmentResultHistoryCursor(service.keyring, candidateID, cursor)
if err != nil {
return AssessmentResultHistoryPage{}, fmt.Errorf("%s - decode owner cursor: %w", location, ErrInvalidAssessmentResultHistoryRequest)
}
page, err := service.repository.ListCandidateAssessmentResults(ctx, candidateID, keyset, limit)
if err != nil {
return AssessmentResultHistoryPage{}, fmt.Errorf("%s - read immutable results: %w", location, err)
}
entries, err := restoreAssessmentResultHistoryPage(candidateID, limit, page)
if err != nil {
return AssessmentResultHistoryPage{}, fmt.Errorf("%s - validate repository page: %w", location, err)
}
var nextCursor string
if page.HasMore {
last := entries[len(entries)-1]
nextCursor, err = encodeAssessmentResultHistoryCursor(service.keyring, candidateID, outbound.AssessmentAttemptResultCursor{
DecidedAt: last.Result.DecidedAt, AttemptID: last.Result.Attempt.ID,
})
if err != nil {
return AssessmentResultHistoryPage{}, fmt.Errorf("%s - sign owner cursor: %w", location, err)
}
}
return AssessmentResultHistoryPage{Entries: entries, NextCursor: nextCursor}, nil
}
func invalidAssessmentResultHistoryRequest(
repository AssessmentResultHistoryRepository,
keyring Keyring,
candidateID uuid.UUID,
cursor string,
limit int32,
) bool {
return repository == nil || keyring == nil || candidateID == uuid.Nil || limit < 0 || limit > AssessmentResultHistoryMaxLimit ||
len(cursor) > assessmentResultHistoryMaxCursorBytes
}
const assessmentResultHistoryCursorOperation = "assessment.result-history.cursor.v1"
const assessmentResultHistoryCursorPayloadSize = 8 + 4 + 16
func encodeAssessmentResultHistoryCursor(
keyring Keyring,
candidateID uuid.UUID,
cursor outbound.AssessmentAttemptResultCursor,
) (string, error) {
if keyring == nil || candidateID == uuid.Nil || cursor.AttemptID.IsZero() || cursor.DecidedAt.IsZero() ||
cursor.DecidedAt.Nanosecond()%1000 != 0 {
return "", ErrInvalidAssessmentResultHistoryRequest
}
payload := make([]byte, assessmentResultHistoryCursorPayloadSize)
binary.BigEndian.PutUint64(payload[:8], uint64(cursor.DecidedAt.Unix()))
binary.BigEndian.PutUint32(payload[8:12], uint32(cursor.DecidedAt.Nanosecond()))
attemptID := cursor.AttemptID.UUID()
copy(payload[12:], attemptID[:])
encodedPayload := base64.RawURLEncoding.EncodeToString(payload)
mac := keyring.IdempotencyScope(assessmentResultHistoryCursorOperation, encodedPayload, candidateID.String())
return encodedPayload + "." + base64.RawURLEncoding.EncodeToString(mac[:]), nil
}
func decodeAssessmentResultHistoryCursor(
keyring Keyring,
candidateID uuid.UUID,
token string,
) (*outbound.AssessmentAttemptResultCursor, error) {
if token == "" {
return nil, nil
}
if keyring == nil || candidateID == uuid.Nil || len(token) > assessmentResultHistoryMaxCursorBytes {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
encodedPayload, encodedMAC, found := strings.Cut(token, ".")
if !found || encodedPayload == "" || encodedMAC == "" || strings.Contains(encodedMAC, ".") {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
payload, err := base64.RawURLEncoding.DecodeString(encodedPayload)
if err != nil || len(payload) != assessmentResultHistoryCursorPayloadSize ||
base64.RawURLEncoding.EncodeToString(payload) != encodedPayload {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
suppliedMAC, err := base64.RawURLEncoding.DecodeString(encodedMAC)
if err != nil || len(suppliedMAC) != outbound.IdempotencyDigestSize ||
base64.RawURLEncoding.EncodeToString(suppliedMAC) != encodedMAC {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
expectedMAC := keyring.IdempotencyScope(assessmentResultHistoryCursorOperation, encodedPayload, candidateID.String())
if !hmac.Equal(suppliedMAC, expectedMAC[:]) {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
seconds := int64(binary.BigEndian.Uint64(payload[:8]))
nanos := binary.BigEndian.Uint32(payload[8:12])
if nanos >= uint32(time.Second) || nanos%1000 != 0 {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
var attemptUUID uuid.UUID
copy(attemptUUID[:], payload[12:])
attemptID := domain.AssessmentAttemptID(attemptUUID)
if attemptID.IsZero() {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
decidedAt := time.Unix(seconds, int64(nanos)).UTC()
if decidedAt.Unix() != seconds || uint32(decidedAt.Nanosecond()) != nanos {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
return &outbound.AssessmentAttemptResultCursor{DecidedAt: decidedAt, AttemptID: attemptID}, nil
}
func restoreAssessmentResultHistoryPage(
candidateID uuid.UUID,
limit int32,
page outbound.AssessmentAttemptResultPage,
) ([]domain.AssessmentAttemptResultHistoryEntry, error) {
const location = "restoreAssessmentResultHistoryPage"
if len(page.Records) > int(limit) || page.HasMore && len(page.Records) == 0 {
return nil, fmt.Errorf("%s - repository page exceeds bounds: %w", location, ErrAssessmentCategoryHistoryInvalid)
}
entries := make([]domain.AssessmentAttemptResultHistoryEntry, 0, len(page.Records))
seen := make(map[domain.AssessmentAttemptID]struct{}, len(page.Records))
var previous *domain.AssessmentAttemptResultHistoryEntry
for _, record := range page.Records {
entry, err := restoreAssessmentResultHistoryRecord(candidateID, AssessmentResultHistoryRecord{
CandidateID: record.UserID, Entry: record.Entry,
})
if err != nil {
return nil, fmt.Errorf("%s - restore immutable result: %w", location, err)
}
attemptID := entry.Result.Attempt.ID
if _, exists := seen[attemptID]; exists || previous != nil && !historyEntryFollows(*previous, entry) {
return nil, fmt.Errorf("%s - repository ordering or uniqueness is invalid: %w", location, ErrAssessmentCategoryHistoryInvalid)
}
seen[attemptID] = struct{}{}
entries = append(entries, entry)
previous = &entries[len(entries)-1]
}
return entries, nil
}
func restoreAssessmentResultHistoryRecord(
candidateID uuid.UUID,
record AssessmentResultHistoryRecord,
) (domain.AssessmentAttemptResultHistoryEntry, error) {
if record.CandidateID != candidateID {
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("repository returned a foreign owner row: %w", ErrAssessmentCategoryHistoryInvalid)
}
entry, err := domain.RestoreAssessmentAttemptResultHistoryEntry(record.Entry)
if err != nil {
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("restore immutable result: %w", ErrAssessmentCategoryHistoryInvalid)
}
if !historyEntryIsEligible(entry) {
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("repository returned an ineligible result kind: %w", ErrAssessmentCategoryHistoryInvalid)
}
return entry, nil
}
func historyEntryIsEligible(entry domain.AssessmentAttemptResultHistoryEntry) bool {
return entry.Result.Attempt.State == domain.AssessmentAttemptStateCompleted &&
(entry.Result.Attempt.Kind == domain.AssessmentAttemptKindRoot ||
entry.Result.Attempt.Kind == domain.AssessmentAttemptKindCorrective)
}
func historyEntryFollows(previous, current domain.AssessmentAttemptResultHistoryEntry) bool {
previousAt, currentAt := previous.Result.DecidedAt, current.Result.DecidedAt
if currentAt.Before(previousAt) {
return true
}
if !currentAt.Equal(previousAt) {
return false
}
return current.Result.Attempt.ID.String() < previous.Result.Attempt.ID.String()
}
@@ -0,0 +1,168 @@
package assessment
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
func TestAssessmentResultHistoryReadsOwnerScopedV1WithoutInventingGrade(t *testing.T) {
ownerID := uuid.New()
policy := categoryServiceTestPolicy(t)
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
if err != nil {
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
}
repository := &assessmentResultHistoryRepositoryFake{page: AssessmentResultHistoryRepositoryPage{
Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: entry}}, NextCursor: "next-page-token",
}}
service := NewAssessmentResultHistoryService(repository)
page, err := service.ListMine(t.Context(), ownerID, "", 0)
if err != nil {
t.Fatalf("ListMine(default limit) error = %v", err)
}
if repository.ownerID != ownerID || repository.cursor != "" || repository.limit != AssessmentResultHistoryDefaultLimit {
t.Fatalf("repository request = owner %s cursor %q limit %d", repository.ownerID, repository.cursor, repository.limit)
}
if len(page.Entries) != 1 || page.NextCursor != "next-page-token" ||
page.Entries[0].SchemaVersion != domain.AssessmentAttemptResultHistorySchemaV1 ||
page.Entries[0].CategoryDecision != nil || page.Entries[0].CurrentConfirmedGrade != nil {
t.Fatalf("history page = %+v, want one legacy result with unknown category", page)
}
}
func TestAssessmentResultHistoryRejectsForeignOwnerAndExpressRows(t *testing.T) {
ownerID := uuid.New()
policy := categoryServiceTestPolicy(t)
attempt, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
if err != nil {
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
}
service := NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{{CandidateID: uuid.New(), Entry: entry}}},
})
if _, err := service.ListMine(t.Context(), ownerID, "", 10); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
t.Fatalf("ListMine(foreign owner) error = %v, want invalid history", err)
}
express, expressResult := completedExpressCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
expressEntry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(expressResult)
if err != nil {
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry(express) error = %v", err)
}
service = NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: expressEntry}}},
})
if _, err := service.ListMine(t.Context(), ownerID, "", 10); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
t.Fatalf("ListMine(express row) error = %v, want invalid history", err)
}
if express.Kind() != domain.AssessmentAttemptKindDemoExpress || attempt.Kind() != domain.AssessmentAttemptKindRoot {
t.Fatal("fixture attempt kinds changed unexpectedly")
}
}
func TestAssessmentResultHistoryRejectsInvalidBoundsAndDuplicateResults(t *testing.T) {
ownerID := uuid.New()
policy := categoryServiceTestPolicy(t)
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
if err != nil {
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
}
repository := &assessmentResultHistoryRepositoryFake{page: AssessmentResultHistoryRepositoryPage{
Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: entry}},
}}
service := NewAssessmentResultHistoryService(repository)
if _, err := service.ListMine(t.Context(), ownerID, strings.Repeat("x", assessmentResultHistoryMaxCursorBytes+1), 1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
t.Fatalf("ListMine(oversized cursor) error = %v, want invalid request", err)
}
if _, err := service.ListMine(t.Context(), ownerID, "", AssessmentResultHistoryMaxLimit+1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
t.Fatalf("ListMine(oversized limit) error = %v, want invalid request", err)
}
repository.page.NextCursor = strings.Repeat("x", assessmentResultHistoryMaxCursorBytes+1)
if _, err := service.ListMine(t.Context(), ownerID, "", 1); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
t.Fatalf("ListMine(oversized next cursor) error = %v, want invalid history", err)
}
repository.page.NextCursor = ""
repository.page.Records = append(repository.page.Records,
AssessmentResultHistoryRecord{CandidateID: ownerID, Entry: entry})
if _, err := service.ListMine(t.Context(), ownerID, "", 2); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
t.Fatalf("ListMine(duplicate result) error = %v, want invalid history", err)
}
}
func TestAssessmentResultHistoryOrdersTiedDecisionsByAttemptIDDescending(t *testing.T) {
ownerID := uuid.New()
policy := categoryServiceTestPolicy(t)
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
decidedAt := time.Date(2026, time.September, 1, 11, 0, 0, 0, time.UTC)
entryForID := func(id string) domain.AssessmentAttemptResultHistoryEntry {
t.Helper()
resultCopy := result
resultCopy.Attempt.ID = domain.AssessmentAttemptID(uuid.MustParse(id))
resultCopy.DecidedAt = decidedAt
resultCopy.Attempt.FinishedAt = &decidedAt
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(resultCopy)
if err != nil {
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry(%s) error = %v", id, err)
}
return entry
}
higherID := entryForID("ffffffff-ffff-4fff-bfff-ffffffffffff")
lowerID := entryForID("00000000-0000-4000-8000-000000000001")
service := NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{
{CandidateID: ownerID, Entry: higherID},
{CandidateID: ownerID, Entry: lowerID},
}},
})
page, err := service.ListMine(t.Context(), ownerID, "", 2)
if err != nil {
t.Fatalf("ListMine(descending tie order) error = %v", err)
}
if len(page.Entries) != 2 || page.Entries[0].Result.Attempt.ID.String() <= page.Entries[1].Result.Attempt.ID.String() {
t.Fatalf("tied attempt IDs = %v, want descending order", []string{
page.Entries[0].Result.Attempt.ID.String(), page.Entries[1].Result.Attempt.ID.String(),
})
}
service = NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{
{CandidateID: ownerID, Entry: lowerID},
{CandidateID: ownerID, Entry: higherID},
}},
})
if _, err := service.ListMine(t.Context(), ownerID, "", 2); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
t.Fatalf("ListMine(ascending tie order) error = %v, want invalid history", err)
}
}
type assessmentResultHistoryRepositoryFake struct {
page AssessmentResultHistoryRepositoryPage
ownerID uuid.UUID
cursor string
limit int32
readErr error
}
func (repository *assessmentResultHistoryRepositoryFake) ListCandidateAssessmentResults(
_ context.Context,
ownerID uuid.UUID,
cursor string,
limit int32,
) (AssessmentResultHistoryRepositoryPage, error) {
repository.ownerID, repository.cursor, repository.limit = ownerID, cursor, limit
return repository.page, repository.readErr
}
@@ -0,0 +1,377 @@
package assessment
import (
"context"
"encoding/json"
"fmt"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
func TestAssessmentCategoryDecisionServiceRequiresDefaultOffGate(t *testing.T) {
userID := uuid.New()
policy := categoryServiceTestPolicy(t)
attempt, result := completedCategoryServiceAttempt(t, policy, userID, categoryServiceTestTime)
current := categoryServiceCurrent(t, attempt, policy, domain.GradeIntern)
review := categoryServiceReview(t, attempt, result, policy)
repository := &categoryDecisionRepositoryFake{current: &current, review: &review}
service := NewAssessmentCategoryDecisionService(AssessmentCategoryDecisionSettings{})
plan, err := service.PrepareFinalizedResult(t.Context(), repository, attempt, result, policy)
if err != nil {
t.Fatalf("PrepareFinalizedResult(default gate) error = %v", err)
}
if plan.Decision.Status != domain.AssessmentCategoryDecisionNotEligible || plan.ReplaceCurrent ||
plan.CurrentCategory == nil || plan.CurrentCategory.Snapshot().Grade != domain.GradeIntern ||
plan.Result.SchemaVersion != domain.AssessmentAttemptResultHistorySchemaV2 ||
plan.Result.CurrentConfirmedGrade == nil || *plan.Result.CurrentConfirmedGrade != domain.GradeIntern {
t.Fatalf("default-off plan = %+v, want existing category captured without assignment", plan)
}
if len(repository.calls) != 2 || repository.calls[0] != "lock" || repository.calls[1] != "current" {
t.Fatalf("repository calls = %v, want category lock and current read only", repository.calls)
}
}
func TestAssessmentCategoryDecisionServiceAssignsOnlyTheExactReviewedPolicySource(t *testing.T) {
userID := uuid.New()
policy := categoryServiceTestPolicy(t)
attempt, result := completedCategoryServiceAttempt(t, policy, userID, categoryServiceTestTime)
review := categoryServiceReview(t, attempt, result, policy)
repository := &categoryDecisionRepositoryFake{review: &review}
service := NewAssessmentCategoryDecisionService(AssessmentCategoryDecisionSettings{
SyntheticDemoAssignmentsEnabled: true,
})
plan, err := service.PrepareFinalizedResult(t.Context(), repository, attempt, result, policy)
if err != nil {
t.Fatalf("PrepareFinalizedResult(reviewed source) error = %v", err)
}
if plan.Decision.Status != domain.AssessmentCategoryDecisionAssigned || !plan.ReplaceCurrent ||
plan.CurrentCategory == nil || plan.CurrentCategory.Snapshot().Grade != domain.GradeJunior ||
plan.Result.SchemaVersion != domain.AssessmentAttemptResultHistorySchemaV2 ||
plan.Result.CurrentConfirmedGrade == nil || *plan.Result.CurrentConfirmedGrade != domain.GradeJunior {
t.Fatalf("reviewed plan = %+v, want pinned junior category assignment", plan)
}
if repository.reviewPins.Category != attempt.Snapshot().BankCategory ||
repository.reviewPins.OpeningID != result.Pins.OpeningID ||
repository.reviewPins.OpeningManifestHash != result.Pins.OpeningManifestHash ||
repository.reviewPins.ProductPolicyVersionID != result.Pins.ProductPolicyVersionID ||
repository.reviewPins.ProductPolicyVersion != result.Pins.ProductPolicyVersion {
t.Fatalf("review query pins = %+v, want exact finalized source pins", repository.reviewPins)
}
}
func TestAssessmentCategoryDecisionServiceKeepsExpressTrainingOutOfCategoryStorage(t *testing.T) {
userID := uuid.New()
policy := categoryServiceTestPolicy(t)
attempt, result := completedExpressCategoryServiceAttempt(t, policy, userID, categoryServiceTestTime)
repository := &categoryDecisionRepositoryFake{}
service := NewAssessmentCategoryDecisionService(AssessmentCategoryDecisionSettings{
SyntheticDemoAssignmentsEnabled: true,
})
plan, err := service.PrepareFinalizedResult(t.Context(), repository, attempt, result, policy)
if err != nil {
t.Fatalf("PrepareFinalizedResult(express) error = %v", err)
}
if plan.Decision.Status != domain.AssessmentCategoryDecisionTrainingOnly || plan.ReplaceCurrent ||
plan.Result.SchemaVersion != domain.AssessmentAttemptResultHistorySchemaV1 ||
plan.Result.CategoryDecision != nil || plan.Result.CurrentConfirmedGrade != nil || len(repository.calls) != 0 {
t.Fatalf("express plan = %+v with calls %v, want training-only v1 and no category reads", plan, repository.calls)
}
}
type categoryDecisionRepositoryFake struct {
calls []string
current *domain.CandidateAssessmentCategory
review *domain.AssessmentSyntheticCategoryReview
reviewPins AssessmentCategoryReviewPins
}
func (repository *categoryDecisionRepositoryFake) LockCandidateCategory(
context.Context,
uuid.UUID,
domain.SpecializationCode,
) error {
repository.calls = append(repository.calls, "lock")
return nil
}
func (repository *categoryDecisionRepositoryFake) GetCandidateCategory(
context.Context,
uuid.UUID,
domain.SpecializationCode,
) (domain.CandidateAssessmentCategory, bool, error) {
repository.calls = append(repository.calls, "current")
if repository.current == nil {
return domain.CandidateAssessmentCategory{}, false, nil
}
return *repository.current, true, nil
}
func (repository *categoryDecisionRepositoryFake) GetSyntheticCategoryReview(
_ context.Context,
pins AssessmentCategoryReviewPins,
) (domain.AssessmentSyntheticCategoryReview, bool, error) {
repository.calls = append(repository.calls, "review")
repository.reviewPins = pins
if repository.review == nil {
return domain.AssessmentSyntheticCategoryReview{}, false, nil
}
snapshot := repository.review.Snapshot()
if snapshot.Category != pins.Category || snapshot.OpeningID != pins.OpeningID ||
snapshot.OpeningManifestHash != pins.OpeningManifestHash ||
snapshot.ProductPolicyVersionID != pins.ProductPolicyVersionID ||
snapshot.ProductPolicyVersion != pins.ProductPolicyVersion {
return domain.AssessmentSyntheticCategoryReview{}, false, nil
}
return *repository.review, true, nil
}
var categoryServiceTestTime = time.Date(2026, time.September, 1, 10, 0, 0, 0, time.UTC)
const categoryServiceCorrectAnswers = 19
func categoryServiceTestPolicy(t *testing.T) domain.PolicyVersion {
t.Helper()
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor,
EffectiveAt: categoryServiceTestTime, Policy: domain.DemoProductPolicyV2(),
})
if err != nil {
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
}
numbered, err := draft.WithVersion(2)
if err != nil {
t.Fatalf("PolicyVersionDraft.WithVersion() error = %v", err)
}
hash := numbered.DocumentHash()
policy, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{
ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()),
Author: string(numbered.Author()), EffectiveAt: categoryServiceTestTime, CreatedAt: categoryServiceTestTime,
Document: numbered.Document(), DocumentHash: hash[:],
})
if err != nil {
t.Fatalf("RestorePolicyVersion() error = %v", err)
}
return policy
}
func completedCategoryServiceAttempt(
t *testing.T,
policy domain.PolicyVersion,
userID uuid.UUID,
createdAt time.Time,
) (domain.AssessmentAttempt, domain.AssessmentAttemptResultSnapshot) {
t.Helper()
items := categoryServiceAttemptItems(t, int(policy.Policy().Assessment.StopRule.MaxScoredItems+policy.Policy().Assessment.StopRule.SeedItems))
specialization, grade := domain.SpecializationBackend, domain.GradeJunior
attempt, err := domain.NewAssessmentAttempt(domain.NewAssessmentAttemptInput{
UserID: userID, Kind: domain.AssessmentAttemptKindRoot, BankCategory: "backend",
Specialization: &specialization, TargetGrade: &grade, Versions: categoryServiceAttemptVersions(t, policy),
Policy: policy, CreatedAt: createdAt, Items: items,
})
if err != nil {
t.Fatalf("NewAssessmentAttempt() error = %v", err)
}
attempt = submitCategoryServiceAnswers(t, attempt, categoryServiceCorrectAnswers, createdAt)
completed, changed, decision, err := attempt.FinalizeDemo(
attempt.Version(), policy.Policy().Assessment, createdAt.Add(time.Duration(len(items)+2)*time.Second),
)
if err != nil || !changed {
t.Fatalf("FinalizeDemo() = changed %v, error %v", changed, err)
}
result, err := domain.NewAssessmentAttemptResultSnapshot(completed, decision, "", []string{"uncalibrated_thresholds"})
if err != nil {
t.Fatalf("NewAssessmentAttemptResultSnapshot() error = %v", err)
}
return completed, result
}
func completedExpressCategoryServiceAttempt(
t *testing.T,
policy domain.PolicyVersion,
userID uuid.UUID,
createdAt time.Time,
) (domain.AssessmentAttempt, domain.AssessmentAttemptResultSnapshot) {
t.Helper()
items := categoryServiceAttemptItems(t, int(policy.Policy().Assessment.Training.DemoExpressItemCount))
attempt, err := domain.NewAssessmentAttempt(domain.NewAssessmentAttemptInput{
UserID: userID, Kind: domain.AssessmentAttemptKindDemoExpress, BankCategory: "training-demo",
Versions: domain.AssessmentAttemptVersions{
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
TrainingBindingID: uuid.New(), TrainingManifestHash: categoryServiceManifestHash(2),
BankVersion: "training-demo.v1", AlgorithmVersion: "assessment.v1",
},
Policy: policy, CreatedAt: createdAt, Items: items,
})
if err != nil {
t.Fatalf("NewAssessmentAttempt(express) error = %v", err)
}
attempt = submitCategoryServiceAnswers(t, attempt, len(items), createdAt)
completed, changed, decision, err := attempt.FinalizeDemo(
attempt.Version(), policy.Policy().Assessment, createdAt.Add(time.Duration(len(items)+2)*time.Second),
)
if err != nil || !changed {
t.Fatalf("FinalizeDemo(express) = changed %v, error %v", changed, err)
}
result, err := domain.NewAssessmentAttemptResultSnapshot(
completed, decision, "Training only.", []string{"demonstration_only"},
)
if err != nil {
t.Fatalf("NewAssessmentAttemptResultSnapshot(express) error = %v", err)
}
return completed, result
}
func submitCategoryServiceAnswers(
t *testing.T,
attempt domain.AssessmentAttempt,
correctCount int,
createdAt time.Time,
) domain.AssessmentAttempt {
t.Helper()
for index, item := range attempt.Snapshot().Items {
reference := item.Variant.ReferenceAnswer
if index >= correctCount {
reference += "1"
}
answer := json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s}`, reference))
updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, answer, createdAt.Add(time.Duration(index+1)*time.Second))
if err != nil || !changed {
t.Fatalf("SubmitAnswer(item %d) = changed %v, error %v", index, changed, err)
}
attempt = updated
}
return attempt
}
func categoryServiceAttemptItems(t *testing.T, count int) []domain.AssessmentAttemptItemInput {
t.Helper()
items := make([]domain.AssessmentAttemptItemInput, count)
for index := range items {
family := categoryServiceFamily(t, index)
variant, err := family.NewVariant(domain.VariantSeed(index + 1))
if err != nil {
t.Fatalf("AssessmentFamily.NewVariant(%d) error = %v", index, err)
}
items[index] = domain.AssessmentAttemptItemInput{Variant: variant}
}
return items
}
func categoryServiceFamily(t *testing.T, index int) domain.AssessmentFamily {
t.Helper()
draft, err := domain.NewAssessmentFamilyDraft(domain.NewAssessmentFamilyDraftInput{
Key: domain.AssessmentFamilyKey(fmt.Sprintf("category-service-family-%02d", index)),
Version: 1, Category: "backend", Specialization: "backend", Title: fmt.Sprintf("Category fixture %02d", index),
BundleName: "category-service-fixture", Author: "ai:category-service-test", ReviewStatus: domain.AssessmentReviewPending,
Generator: domain.AssessmentSeedGenerator{
Algorithm: "lru_hits.v1", Parameters: map[string]domain.AssessmentParameterRange{
"accesses": {Min: 10, Max: 30}, "keys": {Min: 3, Max: 8}, "capacity": {Min: 2, Max: 4},
},
StatementTemplate: "Capacity {{.capacity}}, reads {{.sequence}}.",
},
AnswerKey: domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatInteger, ReferenceSolution: "Simulate the cache."},
Rubric: domain.AssessmentRubric{
Principle: "Compare with the reference answer.",
Criteria: []domain.AssessmentRubricCriterion{{ID: "correct_answer", Description: "Matches the reference answer."}},
},
})
if err != nil {
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
}
core, hash := draft.Core(), draft.ContentHash()
generator, err := draft.SeedGeneratorJSON()
if err != nil {
t.Fatalf("SeedGeneratorJSON() error = %v", err)
}
answerKey, err := draft.AnswerKeyJSON()
if err != nil {
t.Fatalf("AnswerKeyJSON() error = %v", err)
}
rubric, err := draft.RubricJSON()
if err != nil {
t.Fatalf("RubricJSON() error = %v", err)
}
family, err := domain.RestoreAssessmentFamily(domain.StoredAssessmentFamily{
ID: draft.ID(), FamilyKey: string(core.Key), Version: core.Version, Category: string(core.Category),
Specialization: string(core.Specialization), Title: core.Title, BundleName: string(core.BundleName),
Author: string(core.Author), Reviewer: string(core.Reviewer), ReviewStatus: string(core.ReviewStatus),
SeedGenerator: generator, AnswerKey: answerKey, Rubric: rubric, ContentHash: hash[:],
HashScheme: draft.HashScheme(), Lifecycle: string(domain.AssessmentLifecycleDraft), CreatedAt: categoryServiceTestTime,
})
if err != nil {
t.Fatalf("RestoreAssessmentFamily() error = %v", err)
}
return family
}
func categoryServiceAttemptVersions(t *testing.T, policy domain.PolicyVersion) domain.AssessmentAttemptVersions {
t.Helper()
gradingID, err := domain.NewPolicyVersionID()
if err != nil {
t.Fatalf("NewPolicyVersionID() error = %v", err)
}
return domain.AssessmentAttemptVersions{
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
GradingPolicyVersionID: gradingID, OpeningID: uuid.New(), OpeningManifestHash: categoryServiceManifestHash(1),
BankVersion: "backend-demo.v1", AlgorithmVersion: "assessment.v1",
}
}
func categoryServiceManifestHash(value byte) [32]byte {
var digest [32]byte
digest[0] = value
return digest
}
func categoryServiceReview(
t *testing.T,
attempt domain.AssessmentAttempt,
result domain.AssessmentAttemptResultSnapshot,
policy domain.PolicyVersion,
) domain.AssessmentSyntheticCategoryReview {
t.Helper()
reviewer, err := domain.ParseAssessmentOperator("operator:category-reviewer")
if err != nil {
t.Fatalf("ParseAssessmentOperator() error = %v", err)
}
pins := result.Pins
review, err := domain.NewAssessmentSyntheticCategoryReview(domain.AssessmentSyntheticCategoryReviewSnapshot{
ID: uuid.New(), OpeningID: pins.OpeningID, Category: attempt.Snapshot().BankCategory,
Source: domain.AssessmentCategorySourceSyntheticDemo,
OpeningManifestHash: pins.OpeningManifestHash, ProductPolicyVersionID: policy.ID(),
ProductPolicyVersion: policy.Version(), ReviewedBy: reviewer, ReviewedAt: result.DecidedAt,
})
if err != nil {
t.Fatalf("NewAssessmentSyntheticCategoryReview() error = %v", err)
}
return review
}
func categoryServiceCurrent(
t *testing.T,
attempt domain.AssessmentAttempt,
policy domain.PolicyVersion,
grade domain.GradeCode,
) domain.CandidateAssessmentCategory {
t.Helper()
snapshot := attempt.Snapshot()
category, err := domain.RestoreCandidateAssessmentCategory(domain.CandidateAssessmentCategorySnapshot{
CandidateID: snapshot.UserID, Specialization: *snapshot.Specialization, Grade: grade,
SourceAttemptID: domain.AssessmentAttemptID(uuid.New()), SourceReviewID: uuid.New(),
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
OpeningID: snapshot.Versions.OpeningID, OpeningManifestHash: snapshot.Versions.OpeningManifestHash,
Source: domain.AssessmentCategorySourceSyntheticDemo,
CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, AssignedAt: categoryServiceTestTime,
})
if err != nil {
t.Fatalf("RestoreCandidateAssessmentCategory() error = %v", err)
}
return category
}
@@ -32,6 +32,7 @@ type canonicalAttemptFinalizeBody struct {
type AssessmentAttemptResult struct {
Attempt domain.AssessmentAttemptPublicSnapshot
Outcome domain.AssessmentAttemptOutcome
CategoryDecision *domain.AssessmentCategoryDecisionSnapshot
NotDeterminedReason string
BasicScore *domain.AssessmentBasicScore
Limitations []string
@@ -148,6 +149,20 @@ func lockAttemptForFinalize(
if err := lockSessionConsent(ctx, unit, command.ActorID, kind); err != nil {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - authorize finalization: %w", location, err)
}
selected, err := repository.GetForCandidate(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 candidate scope before attempt lock: %w", location, err)
}
selectedSnapshot := selected.Snapshot()
if selected.Kind() != kind {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed before lock: %w", location, domain.ErrInvalidAssessmentAttempt)
}
if err := repository.LockScope(ctx, command.ActorID, selectedSnapshot.Specialization); err != nil {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock candidate and specialization scope: %w", location, err)
}
current, err := repository.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID)
if err != nil {
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
@@ -155,8 +170,9 @@ func lockAttemptForFinalize(
}
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)
if current.Kind() != kind || current.Snapshot().Specialization == nil && selectedSnapshot.Specialization != nil ||
current.Snapshot().Specialization != nil && (selectedSnapshot.Specialization == nil || *current.Snapshot().Specialization != *selectedSnapshot.Specialization) {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt scope changed: %w", location, domain.ErrInvalidAssessmentAttempt)
}
return current, nil
}
@@ -228,10 +244,10 @@ func (service *AttemptService) finalizeActiveAttempt(
}
return fmt.Errorf("%s - calculate pinned decision: %w", location, finalizeErr)
}
return persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, result)
return service.persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, policy, result)
}
func persistFinalizedAttempt(
func (service *AttemptService) persistFinalizedAttempt(
ctx context.Context,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
@@ -239,6 +255,7 @@ func persistFinalizedAttempt(
current, updated domain.AssessmentAttempt,
changed bool,
decision domain.AssessmentAttemptDecision,
policy domain.PolicyVersion,
result *outbound.AssessmentAttemptCommandResult,
) error {
const location = "AttemptService.persistFinalizedAttempt"
@@ -251,8 +268,22 @@ func persistFinalizedAttempt(
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)
categoryPlan, err := service.categoryDecisions.PrepareFinalizedResult(
ctx, repository, updated, storedResult, policy,
)
if err != nil {
return fmt.Errorf("%s - prepare immutable category result: %w", location, err)
}
if err := repository.SaveResultHistoryEntry(ctx, command.ActorID, categoryPlan.Result); err != nil {
return fmt.Errorf("%s - persist immutable result history entry: %w", location, err)
}
if categoryPlan.ReplaceCurrent {
if categoryPlan.CurrentCategory == nil {
return fmt.Errorf("%s - category plan lacks assigned current value: %w", location, domain.ErrInvalidAssessmentCategory)
}
if err := repository.SaveCandidateAssessmentCategory(ctx, *categoryPlan.CurrentCategory); err != nil {
return fmt.Errorf("%s - persist current category: %w", location, err)
}
}
}
outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: updated.PublicSnapshot()}
@@ -343,14 +374,20 @@ func readCompletedAttemptResult(
attempt domain.AssessmentAttempt,
) (AssessmentAttemptResult, error) {
const location = "AttemptService.readCompletedAttemptResult"
stored, err := unit.AssessmentAttempts().GetResult(ctx, userID, attemptID)
stored, err := unit.AssessmentAttempts().GetResultHistoryEntry(ctx, userID, attemptID)
if err != nil {
return AssessmentAttemptResult{}, fmt.Errorf("%s - read immutable result: %w", location, err)
}
if !assessmentResultMatchesAttempt(stored, attempt) {
if !assessmentResultMatchesAttempt(stored.Result, attempt) {
return AssessmentAttemptResult{}, fmt.Errorf("%s - immutable result does not match its attempt: %w", location, domain.ErrInvalidAssessmentAttempt)
}
return assessmentAttemptResultFromSnapshot(stored), nil
entry, err := domain.RestoreAssessmentAttemptResultHistoryEntry(stored)
if err != nil {
return AssessmentAttemptResult{}, fmt.Errorf("%s - restore stored category result: %w", location, err)
}
result := assessmentAttemptResultFromSnapshot(entry.Result)
result.CategoryDecision = entry.CategoryDecision
return result, nil
}
func terminalAttemptResult(attempt domain.AssessmentAttempt) (AssessmentAttemptResult, error) {
@@ -0,0 +1,231 @@
package notification
import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
ErrInboxUnavailable = errors.New("notification inbox is unavailable")
// ErrInboxContentUnavailable means the referenced source is missing or its
// current visibility no longer permits the original presentation.
ErrInboxContentUnavailable = errors.New("notification content is unavailable")
)
const (
maxInboxTitleRunes = 120
maxInboxSummaryRunes = 500
)
// InboxContent is resolved from the current source at read time. It is never
// written to notification_inbox_events.
type InboxContent struct {
title string
summary string
linkPath string
}
// NewInboxContent validates a small same-origin presentation returned by a
// source resolver after its current visibility checks.
func NewInboxContent(title, summary, linkPath string) (InboxContent, error) {
const location = "notification.NewInboxContent"
if !validInboxText(title, maxInboxTitleRunes, false) || !validInboxText(summary, maxInboxSummaryRunes, true) {
return InboxContent{}, fmt.Errorf("%s - title and summary are invalid: %w", location, ErrInboxUnavailable)
}
if linkPath != "" && !validInboxLinkPath(linkPath) {
return InboxContent{}, fmt.Errorf("%s - link path must be relative and same-origin: %w", location, ErrInboxUnavailable)
}
return InboxContent{title: title, summary: summary, linkPath: linkPath}, nil
}
func (content InboxContent) Title() string { return content.title }
func (content InboxContent) Summary() string { return content.summary }
func (content InboxContent) LinkPath() string { return content.linkPath }
func validInboxText(value string, maxRunes int, allowNewlines bool) bool {
if !utf8.ValidString(value) || value == "" || strings.TrimSpace(value) != value || utf8.RuneCountInString(value) > maxRunes {
return false
}
for _, character := range value {
if character == 0 || (character < 0x20 && !(allowNewlines && (character == '\n' || character == '\t'))) || character == 0x7f {
return false
}
}
return true
}
func validInboxLinkPath(value string) bool {
if !strings.HasPrefix(value, "/") || strings.HasPrefix(value, "//") || strings.ContainsAny(value, "\\?#%") {
return false
}
parsed, err := url.ParseRequestURI(value)
if err != nil || parsed.IsAbs() || parsed.Host != "" || parsed.Path != value {
return false
}
for _, segment := range strings.Split(value, "/") {
if segment == "." || segment == ".." {
return false
}
}
return true
}
// InboxContentResolver reads the current source under its current visibility
// rules. It must return ErrInboxContentUnavailable when that source is gone or
// no longer safe to present.
type InboxContentResolver interface {
Resolve(ctx context.Context, entry domain.NotificationInboxEntry) (InboxContent, error)
}
// InboxItem pairs immutable event metadata with content resolved for this
// read. Content is nil when a safe generic fallback is required.
type InboxItem struct {
Entry domain.NotificationInboxEntry
Content *InboxContent
ContentUnavailable bool
}
// InboxListRequest is built from the authenticated recipient and optional
// organization context. The organization ID filters items but grants no
// authorization by itself.
type InboxListRequest struct {
RecipientUserID uuid.UUID
OrganizationID *uuid.UUID
After *outbound.NotificationInboxPosition
Limit int32
}
type InboxPage struct {
Items []InboxItem
HasMore bool
}
// InboxService coordinates recipient-scoped storage and read-time content
// resolution. A caller for employer-scoped notices must authorize current
// membership before constructing the request; invitation recipients need not
// belong to the sender's organization.
type InboxService struct {
repository outbound.NotificationInboxRepository
resolver InboxContentResolver
clock func() time.Time
}
func NewInboxService(
repository outbound.NotificationInboxRepository,
resolver InboxContentResolver,
clock func() time.Time,
) (*InboxService, error) {
if repository == nil || resolver == nil || clock == nil {
return nil, fmt.Errorf("notification.NewInboxService - repository, resolver, and clock are required: %w", ErrInboxUnavailable)
}
return &InboxService{repository: repository, resolver: resolver, clock: clock}, nil
}
// StoreInvitationDelivered stores the recipient-specific reference to an
// invitation-delivered event. A transaction-bound repository lets a future
// event handler commit this row with the invitation state and consumer marker.
func (service *InboxService) StoreInvitationDelivered(
ctx context.Context,
input domain.NotificationInboxEntryInput,
) (bool, error) {
const location = "InboxService.StoreInvitationDelivered"
entry, err := domain.NewNotificationInboxEntry(input)
if err != nil {
return false, err
}
created, err := service.repository.Store(ctx, entry)
if err != nil {
return false, fmt.Errorf("%s - store event: %w", location, err)
}
return created, nil
}
// List resolves each stored reference against its current source. A source
// that is missing or no longer visible is returned without source content.
func (service *InboxService) List(ctx context.Context, request InboxListRequest) (InboxPage, error) {
const location = "InboxService.List"
if err := validateInboxListRequest(request); err != nil {
return InboxPage{}, err
}
stored, err := service.repository.List(ctx, outbound.NotificationInboxListQuery{
RecipientUserID: request.RecipientUserID,
OrganizationID: request.OrganizationID,
After: request.After,
Limit: request.Limit,
})
if err != nil {
return InboxPage{}, fmt.Errorf("%s - list recipient events: %w", location, err)
}
page := InboxPage{Items: make([]InboxItem, 0, len(stored.Items)), HasMore: stored.HasMore}
for _, entry := range stored.Items {
if !inboxEntryMatchesRequest(entry, request) {
return InboxPage{}, fmt.Errorf("%s - repository returned an event outside the recipient scope: %w", location, ErrInboxUnavailable)
}
item := InboxItem{Entry: entry}
content, resolveErr := service.resolver.Resolve(ctx, entry)
if errors.Is(resolveErr, ErrInboxContentUnavailable) {
item.ContentUnavailable = true
} else if resolveErr != nil {
return InboxPage{}, fmt.Errorf("%s - resolve current event content: %w", location, resolveErr)
} else {
item.Content = &content
}
page.Items = append(page.Items, item)
}
return page, nil
}
// MarkRead persists the first read timestamp for one recipient and exact
// organization context. The source is not read and no private content is
// returned by this command.
func (service *InboxService) MarkRead(
ctx context.Context,
recipientUserID uuid.UUID,
organizationID uuid.UUID,
eventID uuid.UUID,
) (domain.NotificationInboxEntry, error) {
const location = "InboxService.MarkRead"
if recipientUserID == uuid.Nil || organizationID == uuid.Nil || eventID == uuid.Nil {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient, organization, and event IDs are required: %w", location, ErrInboxUnavailable)
}
at := service.clock()
if at.IsZero() {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - clock returned zero: %w", location, ErrInboxUnavailable)
}
entry, err := service.repository.MarkRead(ctx, recipientUserID, organizationID, eventID, at)
if err != nil {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - mark event read: %w", location, err)
}
return entry, nil
}
func validateInboxListRequest(request InboxListRequest) error {
const location = "notification.validateInboxListRequest"
if request.RecipientUserID == uuid.Nil || request.Limit < 1 || request.Limit > outbound.MaxNotificationInboxPageSize {
return fmt.Errorf("%s - recipient and a bounded page size are required: %w", location, ErrInboxUnavailable)
}
if request.OrganizationID != nil && *request.OrganizationID == uuid.Nil {
return fmt.Errorf("%s - organization context cannot be zero: %w", location, ErrInboxUnavailable)
}
if request.After != nil && (request.After.EventID == uuid.Nil || request.After.OccurredAt.IsZero()) {
return fmt.Errorf("%s - page position is invalid: %w", location, ErrInboxUnavailable)
}
return nil
}
func inboxEntryMatchesRequest(entry domain.NotificationInboxEntry, request InboxListRequest) bool {
if entry.IsZero() || entry.RecipientUserID() != request.RecipientUserID {
return false
}
return request.OrganizationID == nil || entry.OrganizationID() == *request.OrganizationID
}
@@ -0,0 +1,245 @@
package notification
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestInboxServiceStoreInvitationDeliveredDeduplicatesRecipientEvent(t *testing.T) {
t.Parallel()
repository := &memoryInboxRepository{}
service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now)
input := inboxTestEntryInput()
created, err := service.StoreInvitationDelivered(context.Background(), input)
if err != nil || !created {
t.Fatalf("StoreInvitationDelivered(first) = %t, %v, want true, nil", created, err)
}
created, err = service.StoreInvitationDelivered(context.Background(), input)
if err != nil || created {
t.Fatalf("StoreInvitationDelivered(retry) = %t, %v, want false, nil", created, err)
}
if len(repository.entries) != 1 {
t.Fatalf("stored entries = %d, want one", len(repository.entries))
}
changed := input
changed.SourceID = uuid.New()
if _, err := service.StoreInvitationDelivered(context.Background(), changed); !errors.Is(err, outbound.ErrNotificationInboxEventConflict) {
t.Fatalf("StoreInvitationDelivered(changed replay) error = %v, want ErrNotificationInboxEventConflict", err)
}
}
func TestInboxServiceListRechecksContentAndFallsBackSafely(t *testing.T) {
t.Parallel()
first := mustInboxTestEntry(t, inboxTestEntryInput())
secondInput := inboxTestEntryInput()
secondInput.RecipientUserID = first.RecipientUserID()
secondInput.OrganizationID = first.OrganizationID()
secondInput.EventID = uuid.New()
second := mustInboxTestEntry(t, secondInput)
wrongOrganizationInput := inboxTestEntryInput()
wrongOrganizationInput.RecipientUserID = first.RecipientUserID()
wrongOrganizationInput.EventID = uuid.New()
wrongOrganizationInput.OrganizationID = uuid.New()
wrongOrganization := mustInboxTestEntry(t, wrongOrganizationInput)
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{first, second, wrongOrganization}}
resolver := &memoryInboxResolver{unavailable: map[uuid.UUID]bool{second.EventID(): true}}
service := newInboxTestService(t, repository, resolver, time.Now)
orgID := first.OrganizationID()
page, err := service.List(context.Background(), InboxListRequest{
RecipientUserID: first.RecipientUserID(), OrganizationID: &orgID, Limit: 10,
})
if err != nil {
t.Fatalf("List() error = %v", err)
}
if len(page.Items) != 2 {
t.Fatalf("List() returned %d items, want 2", len(page.Items))
}
if page.Items[0].Content == nil || page.Items[0].ContentUnavailable {
t.Fatalf("visible item = %+v, want current content", page.Items[0])
}
if page.Items[1].Content != nil || !page.Items[1].ContentUnavailable {
t.Fatalf("hidden item = %+v, want safe fallback without source content", page.Items[1])
}
if resolver.calls != 2 {
t.Fatalf("resolver calls = %d, want one current visibility check per returned item", resolver.calls)
}
}
func TestInboxServiceListRejectsRepositoryRowsOutsideRecipientScope(t *testing.T) {
t.Parallel()
entry := mustInboxTestEntry(t, inboxTestEntryInput())
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}, ignoreListScope: true}
service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now)
_, err := service.List(context.Background(), InboxListRequest{
RecipientUserID: uuid.New(), OrganizationID: uuidPointer(entry.OrganizationID()), Limit: 10,
})
if !errors.Is(err, ErrInboxUnavailable) {
t.Fatalf("List(out-of-scope repository row) error = %v, want ErrInboxUnavailable", err)
}
}
func TestInboxServiceMarkReadPersistsAndKeepsFirstTime(t *testing.T) {
t.Parallel()
entry := mustInboxTestEntry(t, inboxTestEntryInput())
firstRead := time.Date(2026, time.October, 8, 13, 0, 0, 1000, time.UTC)
secondRead := firstRead.Add(time.Hour)
clockCalls := 0
clock := func() time.Time {
clockCalls++
if clockCalls == 1 {
return firstRead
}
return secondRead
}
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}}
service := newInboxTestService(t, repository, &memoryInboxResolver{}, clock)
for range 2 {
read, err := service.MarkRead(context.Background(), entry.RecipientUserID(), entry.OrganizationID(), entry.EventID())
if err != nil {
t.Fatalf("MarkRead() error = %v", err)
}
got, isRead := read.ReadAt()
if !isRead || !got.Equal(firstRead.UTC().Truncate(time.Microsecond)) {
t.Fatalf("ReadAt() = %s, %t, want the first read time", got, isRead)
}
}
}
func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) {
t.Parallel()
tests := []struct {
name string
path string
}{
{name: "external URL", path: "https://example.test/invitation"},
{name: "protocol-relative URL", path: "//example.test/invitation"},
{name: "query string", path: "/candidate/invitations?token=secret"},
{name: "fragment", path: "/candidate/invitations#current"},
{name: "backslash", path: `/candidate\\invitations`},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
if _, err := NewInboxContent("Приглашение", "Проверьте новое приглашение.", test.path); !errors.Is(err, ErrInboxUnavailable) {
t.Fatalf("NewInboxContent() error = %v, want ErrInboxUnavailable", err)
}
})
}
}
func newInboxTestService(
t *testing.T,
repository outbound.NotificationInboxRepository,
resolver InboxContentResolver,
clock func() time.Time,
) *InboxService {
t.Helper()
service, err := NewInboxService(repository, resolver, clock)
if err != nil {
t.Fatalf("NewInboxService() error = %v", err)
}
return service
}
func inboxTestEntryInput() domain.NotificationInboxEntryInput {
return domain.NotificationInboxEntryInput{
EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(),
EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1,
SourceType: domain.NotificationInboxSourceInvitation, SourceID: uuid.New(),
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC),
}
}
func mustInboxTestEntry(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry {
t.Helper()
entry, err := domain.NewNotificationInboxEntry(input)
if err != nil {
t.Fatalf("NewNotificationInboxEntry() error = %v", err)
}
return entry
}
func uuidPointer(value uuid.UUID) *uuid.UUID { return &value }
type memoryInboxRepository struct {
entries []domain.NotificationInboxEntry
ignoreListScope bool
}
func (repository *memoryInboxRepository) Store(_ context.Context, entry domain.NotificationInboxEntry) (bool, error) {
for _, existing := range repository.entries {
if existing.RecipientUserID() != entry.RecipientUserID() || existing.EventID() != entry.EventID() {
continue
}
if !sameInboxEvent(existing, entry) {
return false, outbound.ErrNotificationInboxEventConflict
}
return false, nil
}
repository.entries = append(repository.entries, entry)
return true, nil
}
func (repository *memoryInboxRepository) List(_ context.Context, query outbound.NotificationInboxListQuery) (outbound.NotificationInboxPage, error) {
page := outbound.NotificationInboxPage{}
for _, entry := range repository.entries {
if !repository.ignoreListScope && (entry.RecipientUserID() != query.RecipientUserID || (query.OrganizationID != nil && entry.OrganizationID() != *query.OrganizationID)) {
continue
}
page.Items = append(page.Items, entry)
}
return page, nil
}
func (repository *memoryInboxRepository) MarkRead(
_ context.Context,
recipientUserID uuid.UUID,
organizationID uuid.UUID,
eventID uuid.UUID,
at time.Time,
) (domain.NotificationInboxEntry, error) {
for index, entry := range repository.entries {
if entry.RecipientUserID() != recipientUserID || entry.OrganizationID() != organizationID || entry.EventID() != eventID {
continue
}
read, err := entry.MarkRead(at)
if err != nil {
return domain.NotificationInboxEntry{}, err
}
repository.entries[index] = read
return read, nil
}
return domain.NotificationInboxEntry{}, outbound.ErrNotificationInboxEntryNotFound
}
func sameInboxEvent(left, right domain.NotificationInboxEntry) bool {
return left.OrganizationID() == right.OrganizationID() && left.EventType() == right.EventType() &&
left.SchemaVersion() == right.SchemaVersion() && left.SourceType() == right.SourceType() &&
left.SourceID() == right.SourceID() && left.OccurredAt().Equal(right.OccurredAt())
}
type memoryInboxResolver struct {
unavailable map[uuid.UUID]bool
calls int
}
func (resolver *memoryInboxResolver) Resolve(_ context.Context, entry domain.NotificationInboxEntry) (InboxContent, error) {
resolver.calls++
if resolver.unavailable[entry.EventID()] {
return InboxContent{}, ErrInboxContentUnavailable
}
return NewInboxContent("Приглашение", "Проверьте новое приглашение.", "/candidate/invitations")
}