package domain import ( "encoding/json" "errors" "reflect" "regexp" "slices" "strconv" "strings" "testing" "time" "github.com/google/uuid" ) // choiceFamily restores a family of the choice algorithm lru_hits_choice.v1 // with the given parameter ranges. func choiceFamily(t *testing.T, parameters map[string]AssessmentParameterRange) AssessmentFamily { t.Helper() input := testAssessmentInput() input.Generator = AssessmentSeedGenerator{ Algorithm: "lru_hits_choice.v1", Parameters: parameters, StatementTemplate: "n={{.accesses}} k={{.keys}} c={{.capacity}} s={{.sequence}}", } input.AnswerKey.AnswerFormat = AnswerFormatChoice return restoreAssessment(t, input) } func defaultChoiceFamily(t *testing.T) AssessmentFamily { t.Helper() return choiceFamily(t, map[string]AssessmentParameterRange{ "accesses": {Min: 8, Max: 40}, "keys": {Min: 3, Max: 9}, "capacity": {Min: 2, Max: 5}, }) } var choiceStatementPattern = regexp.MustCompile(`^n=\d+ k=\d+ c=(\d+) s=([\d ]+)$`) // choiceInputOf reads the input that the candidate sees back from the // statement, so that a test can recompute the answer and the error models // without using the generator. func choiceInputOf(t *testing.T, statement string) ([]int, int) { t.Helper() match := choiceStatementPattern.FindStringSubmatch(statement) if match == nil { t.Fatalf("statement %q does not match the template", statement) } capacity, err := strconv.Atoi(match[1]) if err != nil { t.Fatalf("capacity %q: %v", match[1], err) } fields := strings.Fields(match[2]) accesses := make([]int, 0, len(fields)) for _, field := range fields { key, err := strconv.Atoi(field) if err != nil { t.Fatalf("key %q: %v", field, err) } accesses = append(accesses, key) } return accesses, capacity } func TestRegisteredAlgorithmsDeclareHowTheyProduceTheAnswer(t *testing.T) { for name, algorithm := range assessmentAlgorithms { isChoice := algorithm.answerFormat == AnswerFormatChoice if isChoice != (algorithm.generateChoice != nil) || isChoice == (algorithm.generate != nil) { t.Errorf("algorithm %s: format %q, generate set %v, generateChoice set %v; a choice algorithm sets only generateChoice and every other one only generate", name, algorithm.answerFormat, algorithm.generate != nil, algorithm.generateChoice != nil) } } } func TestCacheHitsModelsMatchHandComputedCases(t *testing.T) { // With capacity 2 the sequence 1 2 1 3 2 runs as follows. LRU: miss, miss, // hit (order 2 1), miss evicts 2, miss evicts 1: one hit. FIFO keeps 1 // where it entered, so 3 evicts 1 and the last 2 is still cached: two hits. // Evicting the newest key: 3 evicts the just-renewed 1, so 2 survives and // hits: two hits. accesses := []int{1, 2, 1, 3, 2} lru := cachePolicy{refreshOnHit: true} for name, want := range map[string]struct { capacity int policy cachePolicy hits int }{ "lru": {2, lru, 1}, "fifo": {2, cachePolicy{}, 2}, "evict newest": {2, cachePolicy{refreshOnHit: true, evictNewest: true}, 2}, "capacity 1": {1, lru, 0}, "capacity 3": {3, lru, 2}, "capacity bigger": {9, lru, 2}, } { if got := cacheHits(accesses, want.capacity, want.policy); got != want.hits { t.Errorf("%s: cacheHits = %d, want %d", name, got, want.hits) } } } func TestCacheHitsOfLRUMatchesTheSolverOfTheIntegerAlgorithm(t *testing.T) { for seed := range VariantSeed(200) { random := newSeededRandom("test.cache", seed) parameters := map[string]int32{"accesses": random.between(1, 60), "keys": random.between(1, 12), "capacity": random.between(1, 8)} accesses := drawLRUAccesses(random, parameters) capacity := int(parameters["capacity"]) if got, want := cacheHits(accesses, capacity, cachePolicy{refreshOnHit: true}), lruHits(accesses, capacity); got != want { t.Fatalf("seed %d: cacheHits(lru) = %d, lruHits = %d for %v with capacity %d", seed, got, want, accesses, capacity) } } } func TestChoiceVariantIsAFunctionOfTheSeed(t *testing.T) { family := defaultChoiceFamily(t) for seed := range VariantSeed(50) { first, err := family.NewVariant(seed) if err != nil { t.Fatalf("NewVariant(%d) error = %v", seed, err) } second, err := family.NewVariant(seed) if err != nil { t.Fatalf("NewVariant(%d) again error = %v", seed, err) } if !reflect.DeepEqual(first, second) { t.Fatalf("seed %d gave two different variants:\n%+v\n%+v", seed, first, second) } } } func TestChoiceOptionOrderFollowsTheSeed(t *testing.T) { family := defaultChoiceFamily(t) positions := make(map[int]int) orders := make(map[string]bool) for seed := range VariantSeed(400) { variant, err := family.NewVariant(seed) if err != nil { t.Fatalf("NewVariant(%d) error = %v", seed, err) } index, ok := choiceCorrectIndex(variant) if !ok { t.Fatalf("seed %d: key %q is not an option index", seed, variant.ReferenceAnswer) } positions[index]++ texts := make([]string, 0, len(variant.Options)) for _, option := range variant.Options { texts = append(texts, option.Text) } orders[strings.Join(texts, ",")] = true } for index := range choiceOptionCount { if positions[index] < 60 { t.Errorf("the correct option was at position %d for %d of 400 seeds, want a spread over all positions (%v)", index, positions[index], positions) } } if len(orders) < 100 { t.Errorf("400 seeds gave only %d distinct option orders", len(orders)) } } // Every distractor is the result of a typical mistake, recomputed here from // the statement alone. A last-resort value near the answer appears only when // the mistakes did not give three distinct wrong values. func TestChoiceDistractorsComeFromTheErrorModels(t *testing.T) { family := defaultChoiceFamily(t) lru := cachePolicy{refreshOnHit: true} for seed := range VariantSeed(600) { variant, err := family.NewVariant(seed) if err != nil { t.Fatalf("NewVariant(%d) error = %v", seed, err) } accesses, capacity := choiceInputOf(t, variant.Statement) hits := lruHits(accesses, capacity) total := len(accesses) mistakes := map[int]bool{ hits + 1: true, hits - 1: true, total - hits: true, cacheHits(accesses, capacity, cachePolicy{}): true, cacheHits(accesses, capacity, cachePolicy{refreshOnHit: true, evictNewest: true}): true, cacheHits(accesses, capacity-1, lru): true, cacheHits(accesses, capacity+1, lru): true, } delete(mistakes, hits) for value := range mistakes { if value < 0 || value > total { delete(mistakes, value) } } if len(variant.Options) != choiceOptionCount { t.Fatalf("seed %d: %d options, want %d", seed, len(variant.Options), choiceOptionCount) } index, _ := choiceCorrectIndex(variant) if variant.Options[index].Text != strconv.Itoa(hits) { t.Fatalf("seed %d: the key points at %q, the hit count is %d", seed, variant.Options[index].Text, hits) } texts, ids := map[string]bool{}, map[string]bool{} fromMistakes := 0 for position, option := range variant.Options { if texts[option.Text] || ids[option.ID] || !assessmentChoiceOptionIDPattern.MatchString(option.ID) { t.Fatalf("seed %d: options %+v repeat a text or an ID, or an ID has the wrong shape", seed, variant.Options) } texts[option.Text], ids[option.ID] = true, true if position == index { continue } value, err := strconv.Atoi(option.Text) if err != nil || value < 0 || value > total { t.Fatalf("seed %d: distractor %q is not a possible count", seed, option.Text) } if mistakes[value] { fromMistakes++ continue } if len(mistakes) >= choiceOptionCount-1 { t.Fatalf("seed %d: distractor %d is no error-model value although %d of them exist", seed, value, len(mistakes)) } if distance := value - hits; distance > nearbyCountSteps || -distance > nearbyCountSteps { t.Fatalf("seed %d: distractor %d is neither an error-model value nor near the answer %d", seed, value, hits) } } if fromMistakes != min(len(mistakes), choiceOptionCount-1) { t.Fatalf("seed %d: %d distractors from the error models, want %d", seed, fromMistakes, min(len(mistakes), choiceOptionCount-1)) } } } // The lowest parameters are the hardest case for finding three distinct wrong // values; the import probe and this test both must find them. func TestChoiceAlgorithmGivesEnoughDistractorsAtTheLowestParameters(t *testing.T) { family := choiceFamily(t, map[string]AssessmentParameterRange{ "accesses": {Min: 8, Max: 8}, "keys": {Min: 3, Max: 3}, "capacity": {Min: 2, Max: 2}, }) for seed := range VariantSeed(300) { variant, err := family.NewVariant(seed) if err != nil || len(variant.Options) != choiceOptionCount { t.Fatalf("NewVariant(%d) = %d options, %v, want %d", seed, len(variant.Options), err, choiceOptionCount) } } } // goldenChoiceVariant pins the exact output of a fixed seed: the statement, // the options in their order with their IDs, and the key. The IDs and the // order are drawn from the seed and are the contract that stored families // depend on. func TestGoldenChoiceVariant(t *testing.T) { family := choiceFamily(t, map[string]AssessmentParameterRange{ "accesses": {Min: 10, Max: 10}, "keys": {Min: 4, Max: 4}, "capacity": {Min: 2, Max: 2}, }) variant, err := family.NewVariant(12345) if err != nil { t.Fatalf("NewVariant() error = %v", err) } wantOptions := []AssessmentChoiceOption{ {ID: "o9977452e", Text: "1"}, {ID: "o5cf6605e", Text: "8"}, {ID: "o2e021c69", Text: "5"}, {ID: "o5c5d057c", Text: "2"}, } // By hand: with capacity 2 the sequence runs 4 m, 1 m, 2 m, 3 m, 2 hit, // 1 m, 4 m, 4 hit, 2 m, 1 m, which is 2 hits, and the key points at "2". if variant.Statement != "n=10 k=4 c=2 s=4 1 2 3 2 1 4 4 2 1" || variant.ReferenceAnswer != "3" || variant.AnswerFormat != AnswerFormatChoice || !slices.Equal(variant.Options, wantOptions) { t.Fatalf("seed 12345 of lru_hits_choice.v1:\nstatement %q\nkey %q\noptions %+v\nwant key \"3\" and options %+v", variant.Statement, variant.ReferenceAnswer, variant.Options, wantOptions) } } func TestChoiceOptionsDropDuplicatesAndTopUpFromNearbyValues(t *testing.T) { random := newSeededRandom("test.options", 1) // The mistakes repeat the correct text and each other, so only "1" and // "2" survive; the nearby values supply the third, in their order. options, correct, err := newChoiceOptions(random, "5", []string{"5", "1", "1", "2", ""}, []string{"2", "7", "8"}, 3) if err != nil { t.Fatalf("newChoiceOptions() error = %v", err) } texts := make([]string, 0, len(options)) for _, option := range options { texts = append(texts, option.Text) } slices.Sort(texts) if !slices.Equal(texts, []string{"1", "2", "5", "7"}) || options[correct].Text != "5" { t.Fatalf("options = %v with the key at %d, want 1 2 5 7 and the key on 5", texts, correct) } if _, _, err := newChoiceOptions(random, "5", []string{"5", "1"}, []string{"1"}, 3); !errors.Is(err, ErrInvalidAssessmentFamily) { t.Fatalf("newChoiceOptions(too few distinct distractors) error = %v, want ErrInvalidAssessmentFamily", err) } if _, _, err := newChoiceOptions(random, "5", []string{"1"}, nil, 0); !errors.Is(err, ErrInvalidAssessmentFamily) { t.Fatalf("newChoiceOptions(no distractors wanted) error = %v, want ErrInvalidAssessmentFamily", err) } } func choiceAnswer(optionIDs ...string) json.RawMessage { encoded, err := json.Marshal(choiceAssessmentAnswer{Format: AnswerFormatChoice, OptionIDs: optionIDs}) if err != nil { panic(err) } return encoded } func TestChoiceAnswersAreGradedByTheKey(t *testing.T) { variant, err := defaultChoiceFamily(t).NewVariant(7) if err != nil { t.Fatalf("NewVariant() error = %v", err) } index, _ := choiceCorrectIndex(variant) for position, option := range variant.Options { canonical, correct, err := CanonicalAssessmentAnswerForVariant(choiceAnswer(option.ID), variant) if err != nil || correct != (position == index) { t.Fatalf("option %d graded (%s, %v, %v), want correct=%v", position, canonical, correct, err, position == index) } } } func TestChoiceAnswersOutsideTheVariantAreInvalid(t *testing.T) { choice, err := defaultChoiceFamily(t).NewVariant(7) if err != nil { t.Fatalf("NewVariant(choice) error = %v", err) } integer, err := restoreAssessment(t, testAssessmentInput()).NewVariant(7) if err != nil { t.Fatalf("NewVariant(integer) error = %v", err) } first, second := choice.Options[0].ID, choice.Options[1].ID for name, test := range map[string]struct { variant AssessmentVariant answer json.RawMessage }{ "an ID of no option": {choice, choiceAnswer("o00000000")}, "two options": {choice, choiceAnswer(first, second)}, "the same option twice": {choice, choiceAnswer(first, first)}, "no option": {choice, choiceAnswer()}, "an ID with a forbidden char": {choice, choiceAnswer("a b")}, "a number for a choice variant": {choice, json.RawMessage(`{"format":"number","number":1}`)}, "an extra field": {choice, json.RawMessage(`{"format":"choice","option_ids":["` + first + `"],"correct":true}`)}, "a choice for an integer item": {integer, choiceAnswer(first)}, } { t.Run(name, func(t *testing.T) { if _, _, err := CanonicalAssessmentAnswerForVariant(test.answer, test.variant); !errors.Is(err, ErrInvalidAssessmentAttempt) { t.Fatalf("CanonicalAssessmentAnswerForVariant() error = %v, want ErrInvalidAssessmentAttempt", err) } }) } } func TestChoiceAnswerCanonicalFormSortsTheSelection(t *testing.T) { canonical, err := CanonicalAssessmentAnswer(choiceAnswer("ob", "oa")) if err != nil || string(canonical) != `{"format":"choice","option_ids":["oa","ob"]}` { t.Fatalf("CanonicalAssessmentAnswer() = %s, %v, want the sorted selection", canonical, err) } // The stored form is what the generic attempt check accepts unchanged. stored, err := CanonicalAssessmentAttemptAnswer(canonical) if err != nil || string(stored) != string(canonical) { t.Fatalf("CanonicalAssessmentAttemptAnswer() = %s, %v, want the same bytes", stored, err) } } func choiceAttempt(t *testing.T, seeds ...VariantSeed) AssessmentAttempt { t.Helper() policy := testAssessmentAttemptPolicyVersion(t) items := make([]AssessmentAttemptItemInput, len(seeds)) for index, seed := range seeds { input := testAssessmentInput() input.Key = AssessmentFamilyKey("unit-choice-family-" + strconv.Itoa(index)) input.Generator = defaultChoiceFamily(t).core.Generator input.AnswerKey.AnswerFormat = AnswerFormatChoice variant, err := restoreAssessment(t, input).NewVariant(seed) if err != nil { t.Fatalf("NewVariant() error = %v", err) } items[index] = AssessmentAttemptItemInput{Variant: variant} } specialization, grade := SpecializationBackend, GradeJunior attempt, err := NewAssessmentAttempt(NewAssessmentAttemptInput{ UserID: uuid.New(), Kind: AssessmentAttemptKindRoot, BankCategory: "unit-category", Policy: policy, Specialization: &specialization, TargetGrade: &grade, Versions: testAssessmentAttemptVersions(t, policy), CreatedAt: testAssessmentAttemptCreatedAt, Items: items, }) if err != nil { t.Fatalf("NewAssessmentAttempt(choice items) error = %v", err) } return attempt } // The candidate receives the opaque IDs and the texts of the options and the // flag of the content, and nothing else: no key, no index, no seed, and no // trace of how the distractors were made. func TestChoiceCandidateProjectionExposesOnlyOptionIDsAndTexts(t *testing.T) { attempt := choiceAttempt(t, 3, 4) item := attempt.Snapshot().Items[0] public := attempt.PublicSnapshot() if public.CurrentItem == nil || public.CurrentItem.Content.Format != AnswerFormatChoice || public.CurrentItem.Content.Multiple { t.Fatalf("current item = %+v, want a single-selection choice item", public.CurrentItem) } encoded, err := json.Marshal(public) if err != nil { t.Fatalf("json.Marshal(public snapshot) error = %v", err) } var document struct { CurrentItem map[string]json.RawMessage `json:"current_item"` } if err := json.Unmarshal(encoded, &document); err != nil { t.Fatalf("decode public snapshot: %v", err) } var content map[string]json.RawMessage if err := json.Unmarshal(document.CurrentItem["content"], &content); err != nil { t.Fatalf("decode content: %v", err) } contentKeys, itemKeys := make([]string, 0, len(content)), make([]string, 0, len(document.CurrentItem)) for key := range content { contentKeys = append(contentKeys, key) } for key := range document.CurrentItem { itemKeys = append(itemKeys, key) } slices.Sort(contentKeys) slices.Sort(itemKeys) if !slices.Equal(contentKeys, []string{"elements", "format"}) || !slices.Equal(itemKeys, []string{"content", "id", "prompt", "sequence"}) { t.Fatalf("item keys %v and content keys %v, want only the allowlisted fields", itemKeys, contentKeys) } var elements []map[string]string if err := json.Unmarshal(content["elements"], &elements); err != nil || len(elements) != len(item.Variant.Options) { t.Fatalf("elements = %v, %v, want %d options", elements, err, len(item.Variant.Options)) } for position, element := range elements { if len(element) != 2 || element["id"] != item.Variant.Options[position].ID || element["text"] != item.Variant.Options[position].Text { t.Fatalf("element %d = %v, want only the ID and the text of option %+v", position, element, item.Variant.Options[position]) } } // The wire form never carries the key under any name. for _, forbidden := range []string{"ReferenceAnswer", "reference", "correct", "key", "seed", "distractor", "mistake", "Options", "parameters"} { if strings.Contains(strings.ToLower(string(encoded)), strings.ToLower(forbidden)) { t.Fatalf("public snapshot %s contains %q", encoded, forbidden) } } } func TestChoiceAnswerIsStoredAndScoredWithTheAttempt(t *testing.T) { attempt := choiceAttempt(t, 3, 4) items := attempt.Snapshot().Items policy := testAssessmentAttemptPolicyVersion(t).Policy().Assessment policy.StopRule.MaxScoredItems, policy.StopRule.SeedItems = 2, 0 at := attempt.Snapshot().CreatedAt for index, item := range items { answer := correctAssessmentTestAnswer(t, item.Variant) if index == 0 { answer = incorrectAssessmentTestAnswer(t, item.Variant) } updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, answer, at.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 } _, _, decision, err := attempt.FinalizeDemo(attempt.Version(), policy, at.Add(3*time.Second)) if err != nil || decision.Score == nil || decision.Score.Points != 1 || decision.Score.MaxPoints != 2 { t.Fatalf("FinalizeDemo() = %+v, %v, want one of two points: the wrong choice scores nothing", decision, err) } } func TestFrozenChoiceVariantRoundTripsAndOldDocumentsStillDecode(t *testing.T) { variant, err := defaultChoiceFamily(t).NewVariant(11) if err != nil { t.Fatalf("NewVariant() error = %v", err) } encoded, err := MarshalAssessmentAttemptVariant(variant) if err != nil { t.Fatalf("MarshalAssessmentAttemptVariant() error = %v", err) } restored, err := UnmarshalAssessmentAttemptVariant(encoded) if err != nil || !reflect.DeepEqual(restored, variant) { t.Fatalf("round trip = %+v, %v, want the original %+v", restored, err, variant) } // An integer variant stores the layout it always had, without Options. integer, err := restoreAssessment(t, testAssessmentInput()).NewVariant(11) if err != nil { t.Fatalf("NewVariant(integer) error = %v", err) } integerDocument, err := MarshalAssessmentAttemptVariant(integer) if err != nil || strings.Contains(string(integerDocument), "Options") { t.Fatalf("integer variant document %s, %v, want no Options field", integerDocument, err) } if _, err := UnmarshalAssessmentAttemptVariant(integerDocument); err != nil { t.Fatalf("UnmarshalAssessmentAttemptVariant(integer document) error = %v", err) } } func TestFrozenChoiceVariantsWithABrokenKeyAreRefused(t *testing.T) { good, err := defaultChoiceFamily(t).NewVariant(11) if err != nil { t.Fatalf("NewVariant() error = %v", err) } if !validFrozenVariant(good) { t.Fatal("a generated choice variant must be a valid frozen variant") } for name, mutate := range map[string]func(*AssessmentVariant){ "key beyond the options": func(v *AssessmentVariant) { v.ReferenceAnswer = strconv.Itoa(len(v.Options)) }, "key with a leading zero": func(v *AssessmentVariant) { v.ReferenceAnswer = "00" }, "negative key": func(v *AssessmentVariant) { v.ReferenceAnswer = "-1" }, "repeated option text": func(v *AssessmentVariant) { v.Options[1].Text = v.Options[0].Text }, "repeated option ID": func(v *AssessmentVariant) { v.Options[1].ID = v.Options[0].ID }, "option ID with a space": func(v *AssessmentVariant) { v.Options[0].ID = "a b" }, "a single option": func(v *AssessmentVariant) { v.Options = v.Options[:1] }, "options on an integer key": func(v *AssessmentVariant) { v.AnswerFormat = AnswerFormatInteger }, } { t.Run(name, func(t *testing.T) { variant := cloneAssessmentVariant(good) mutate(&variant) if validFrozenVariant(variant) { t.Fatalf("variant %+v was accepted", variant) } }) } }