chore: checkpoint assessment and inbox integration
This commit is contained in:
1 parent
88a31ba0d5
commit
5c52fd8b91
31 files changed
+4608
-181
No files matched your search
@@ -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 = ¤t
|
||||
}
|
||||
|
||||
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 = ¤tValue
|
||||
}
|
||||
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: ¤t, 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) {
|
||||
|
||||
Reference in new issue
Block a user