feat(assessment): grade choice answers with distractors from error models

This commit is contained in:
shira committed 2026-10-11 03:12:24 +03:00
1 parent efa41d5967
commit f1147b1885
22 files changed
+1346 -47

No files matched your search

@@ -844,6 +844,14 @@ func assessmentItemContent(content domain.AssessmentAttemptPublicItemContent) (a
unit.SetTo(*content.Unit)
}
return api.NewNumberItemContentItemContent(api.NumberItemContent{Format: api.NumberItemContentFormatNumber, Unit: unit}), nil
case domain.AnswerFormatChoice:
options := make([]api.AssessmentOption, 0, len(content.Elements))
for _, element := range content.Elements {
options = append(options, api.AssessmentOption{ID: api.AssessmentOptionId(element.ID), Text: element.Text})
}
return api.NewChoiceItemContentItemContent(api.ChoiceItemContent{
Format: api.ChoiceItemContentFormatChoice, Options: options, Multiple: content.Multiple,
}), nil
case "order":
elements := make([]api.AssessmentOption, 0, len(content.Elements))
for _, element := range content.Elements {
@@ -1,6 +1,7 @@
package domain
import (
"slices"
"strconv"
"strings"
)
@@ -44,6 +45,17 @@ var assessmentAlgorithms = map[string]assessmentAlgorithm{
requiredNames: []string{"sequence", "capacity"},
generate: generateLRUHits,
},
"lru_hits_choice.v1": {
answerFormat: AnswerFormatChoice,
parameters: []assessmentParameterSpec{
{name: "accesses", lowest: 8, highest: 500},
{name: "keys", lowest: 3, highest: 100},
{name: "capacity", lowest: 2, highest: 50},
},
dataNames: []string{"sequence"},
requiredNames: []string{"sequence", "capacity"},
generateChoice: generateLRUHitsChoice,
},
"dependency_order.v1": {
answerFormat: AnswerFormatIntegerSequence,
parameters: []assessmentParameterSpec{
@@ -141,12 +153,107 @@ func dedupProcessed(keys, times []int, ttl int) int {
// Data names: sequence.
func generateLRUHits(random *seededRandom, parameters map[string]int32) (map[string]string, string) {
accesses := drawLRUAccesses(random, parameters)
hits := lruHits(accesses, int(parameters["capacity"]))
return map[string]string{"sequence": joinInts(accesses)}, strconv.Itoa(hits)
}
// drawLRUAccesses draws the access sequence of the cache algorithms. The
// draws are part of what the golden tests of lru_hits.v1 pin.
func drawLRUAccesses(random *seededRandom, parameters map[string]int32) []int {
accesses := make([]int, parameters["accesses"])
for index := range accesses {
accesses[index] = 1 + random.below(int(parameters["keys"]))
}
hits := lruHits(accesses, int(parameters["capacity"]))
return map[string]string{"sequence": joinInts(accesses)}, strconv.Itoa(hits)
return accesses
}
// nearbyCountSteps is how far from the correct count the last-resort
// distractors of a count answer reach.
const nearbyCountSteps = 8
// Data names: sequence. The answer is the number of hits like lru_hits.v1,
// offered among options. The wrong options come from mistakes that a solver
// typically makes: an off-by-one count in either direction, counting misses
// instead of hits, a cache where a hit does not renew the key (FIFO
// eviction), a cache that evicts the most recently used key, and a capacity
// that is off by one in either direction.
func generateLRUHitsChoice(random *seededRandom, parameters map[string]int32) choiceTask {
accesses := drawLRUAccesses(random, parameters)
capacity := int(parameters["capacity"])
total := len(accesses)
hits := cacheHits(accesses, capacity, cachePolicy{refreshOnHit: true})
mistakes := []int{
hits + 1,
hits - 1,
total - hits,
cacheHits(accesses, capacity, cachePolicy{}),
cacheHits(accesses, capacity, cachePolicy{refreshOnHit: true, evictNewest: true}),
cacheHits(accesses, capacity-1, cachePolicy{refreshOnHit: true}),
cacheHits(accesses, capacity+1, cachePolicy{refreshOnHit: true}),
}
var nearby []int
for step := 2; step <= nearbyCountSteps; step++ {
nearby = append(nearby, hits+step, hits-step)
}
return choiceTask{
data: map[string]string{"sequence": joinInts(accesses)},
correct: strconv.Itoa(hits),
mistakes: possibleCounts(mistakes, total),
nearby: possibleCounts(nearby, total),
}
}
// possibleCounts writes the values that a count of up to total can take, in
// their order.
func possibleCounts(values []int, total int) []string {
texts := make([]string, 0, len(values))
for _, value := range values {
if value >= 0 && value <= total {
texts = append(texts, strconv.Itoa(value))
}
}
return texts
}
// cachePolicy selects a replacement rule of cacheHits. The zero value is a
// first-in-first-out cache that evicts its oldest key.
type cachePolicy struct {
// refreshOnHit makes a hit renew the key, which is the rule of a
// least-recently-used cache.
refreshOnHit bool
// evictNewest evicts the newest key of a full cache instead of the oldest.
evictNewest bool
}
// cacheHits counts the accesses that find their key in a cache of the given
// capacity under the replacement rule. With refreshOnHit and no evictNewest
// it counts like lruHits, which the tests keep equal; the other rules model
// wrong solutions and exist only to make distractors.
func cacheHits(accesses []int, capacity int, policy cachePolicy) int {
// held keeps the cached keys from the oldest entry to the newest.
held := make([]int, 0, capacity)
hits := 0
for _, key := range accesses {
position := slices.Index(held, key)
if position >= 0 {
hits++
if policy.refreshOnHit {
held = append(held[:position], held[position+1:]...)
held = append(held, key)
}
continue
}
if len(held) == capacity {
if policy.evictNewest {
held = held[:len(held)-1]
} else {
held = held[1:]
}
}
held = append(held, key)
}
return hits
}
// lruHits counts the accesses that find their key in a least-recently-used
@@ -6,7 +6,9 @@ import (
"errors"
"fmt"
"io"
"maps"
"math"
"slices"
"strconv"
"strings"
"time"
@@ -39,6 +41,11 @@ type orderAssessmentAnswer struct {
ElementIDs []string `json:"element_ids"`
}
type choiceAssessmentAnswer struct {
Format string `json:"format"`
OptionIDs []string `json:"option_ids"`
}
// CanonicalAssessmentAnswer validates and canonicalizes a request answer
// before its idempotency fingerprint is created.
func CanonicalAssessmentAnswer(answer json.RawMessage) (json.RawMessage, error) {
@@ -60,6 +67,12 @@ func CanonicalAssessmentAnswer(answer json.RawMessage) (json.RawMessage, error)
return nil, fmt.Errorf("%s - order answer is invalid or exceeds its bound: %w", location, err)
}
return canonical, nil
case AnswerFormatChoice:
canonical, err := canonicalChoiceAssessmentAnswer(answer)
if err != nil {
return nil, fmt.Errorf("%s - choice answer is invalid or exceeds its bound: %w", location, err)
}
return canonical, nil
default:
return nil, fmt.Errorf("%s - answer format is not supported by the current bank: %w", location, ErrInvalidAssessmentAttempt)
}
@@ -112,6 +125,33 @@ func canonicalOrderAssessmentAnswer(answer []byte) ([]byte, error) {
return canonical, nil
}
// canonicalChoiceAssessmentAnswer accepts the selected option IDs as a set:
// two answers that select the same options in any order are the same answer,
// so the canonical form lists the IDs in sorted order.
func canonicalChoiceAssessmentAnswer(answer []byte) ([]byte, error) {
var submitted choiceAssessmentAnswer
if err := decodeStrictAssessmentAnswer(answer, &submitted); err != nil ||
len(submitted.OptionIDs) < 1 || len(submitted.OptionIDs) > maxChoiceOptions {
return nil, ErrInvalidAssessmentAttempt
}
seen := make(map[string]struct{}, len(submitted.OptionIDs))
for _, optionID := range submitted.OptionIDs {
if !assessmentChoiceOptionIDPattern.MatchString(optionID) {
return nil, ErrInvalidAssessmentAttempt
}
if _, exists := seen[optionID]; exists {
return nil, ErrInvalidAssessmentAttempt
}
seen[optionID] = struct{}{}
}
sorted := slices.Sorted(maps.Keys(seen))
canonical, err := json.Marshal(choiceAssessmentAnswer{Format: AnswerFormatChoice, OptionIDs: sorted})
if err != nil || len(canonical) > maxAssessmentAttemptAnswerBytes {
return nil, ErrInvalidAssessmentAttempt
}
return canonical, nil
}
func validateAssessmentOrderElements(elementIDs []string) error {
seen := make(map[string]struct{}, len(elementIDs))
for _, elementID := range elementIDs {
@@ -148,11 +188,36 @@ func CanonicalAssessmentAnswerForVariant(answer json.RawMessage, variant Assessm
return nil, false, fmt.Errorf("%s - compare frozen order key: %w", location, err)
}
return canonical, correct, nil
case AnswerFormatChoice:
correct, err := assessmentChoiceAnswerIsCorrect(canonical, variant)
if err != nil {
return nil, false, fmt.Errorf("%s - compare frozen choice key: %w", location, err)
}
return canonical, correct, nil
default:
return nil, false, fmt.Errorf("%s - frozen answer format is unsupported: %w", location, ErrInvalidAssessmentAttempt)
}
}
// assessmentChoiceAnswerIsCorrect grades a canonical choice answer against the
// frozen options and key of the variant. A variant has one correct option and
// accepts one selected option; an ID that names no option of the variant is an
// invalid answer, not a wrong one.
func assessmentChoiceAnswerIsCorrect(canonical []byte, variant AssessmentVariant) (bool, error) {
var submitted choiceAssessmentAnswer
if err := decodeStrictAssessmentAnswer(canonical, &submitted); err != nil || submitted.Format != AnswerFormatChoice ||
len(submitted.OptionIDs) != 1 || !validFrozenChoiceVariant(variant) {
return false, ErrInvalidAssessmentAttempt
}
correctIndex, _ := choiceCorrectIndex(variant)
for index, option := range variant.Options {
if option.ID == submitted.OptionIDs[0] {
return index == correctIndex, nil
}
}
return false, ErrInvalidAssessmentAttempt
}
func assessmentIntegerAnswerIsCorrect(canonical []byte, referenceAnswer string) (bool, error) {
var submitted numberAssessmentAnswer
if err := decodeStrictAssessmentAnswer(canonical, &submitted); err != nil || submitted.Format != "number" || len(submitted.Number) == 0 {
@@ -226,6 +226,9 @@ func correctAssessmentTestAnswer(t *testing.T, variant AssessmentVariant) json.R
t.Fatalf("json.Marshal(order answer) error = %v", err)
}
return encoded
case AnswerFormatChoice:
index, _ := choiceCorrectIndex(variant)
return choiceAnswer(variant.Options[index].ID)
default:
t.Fatalf("unsupported test answer format %q", variant.AnswerFormat)
return nil
@@ -252,6 +255,10 @@ func incorrectAssessmentTestAnswer(t *testing.T, variant AssessmentVariant) json
t.Fatalf("marshal incorrect order answer: %v", err)
}
return encoded
case AnswerFormatChoice:
correct, _ := choiceCorrectIndex(variant)
wrong := (correct + 1) % len(variant.Options)
return choiceAnswer(variant.Options[wrong].ID)
default:
t.Fatalf("unsupported test answer format %q", variant.AnswerFormat)
return nil
+93 -22
View File
@@ -139,7 +139,37 @@ type assessmentAttemptVariantDocument struct {
Statement string `json:"Statement"`
ReferenceAnswer string `json:"ReferenceAnswer"`
AnswerFormat string `json:"AnswerFormat"`
Rubric AssessmentRubric `json:"Rubric"`
// Options is present only for a choice variant, so the documents of the
// other formats keep the layout they were stored with.
Options []assessmentAttemptChoiceOptionDocument `json:"Options,omitempty"`
Rubric AssessmentRubric `json:"Rubric"`
}
type assessmentAttemptChoiceOptionDocument struct {
ID string `json:"ID"`
Text string `json:"Text"`
}
func assessmentAttemptChoiceOptionDocuments(options []AssessmentChoiceOption) []assessmentAttemptChoiceOptionDocument {
if len(options) == 0 {
return nil
}
documents := make([]assessmentAttemptChoiceOptionDocument, len(options))
for index, option := range options {
documents[index] = assessmentAttemptChoiceOptionDocument(option)
}
return documents
}
func assessmentAttemptChoiceOptionsFromDocuments(documents []assessmentAttemptChoiceOptionDocument) []AssessmentChoiceOption {
if len(documents) == 0 {
return nil
}
options := make([]AssessmentChoiceOption, len(documents))
for index, document := range documents {
options[index] = AssessmentChoiceOption(document)
}
return options
}
func assessmentAttemptVariantDocumentFromVariant(variant AssessmentVariant) assessmentAttemptVariantDocument {
@@ -152,6 +182,7 @@ func assessmentAttemptVariantDocumentFromVariant(variant AssessmentVariant) asse
document.Statement = variant.Statement
document.ReferenceAnswer = variant.ReferenceAnswer
document.AnswerFormat = variant.AnswerFormat
document.Options = assessmentAttemptChoiceOptionDocuments(variant.Options)
document.Rubric = variant.Rubric
return document
}
@@ -166,6 +197,7 @@ func (document assessmentAttemptVariantDocument) variant() AssessmentVariant {
variant.Statement = document.Statement
variant.ReferenceAnswer = document.ReferenceAnswer
variant.AnswerFormat = document.AnswerFormat
variant.Options = assessmentAttemptChoiceOptionsFromDocuments(document.Options)
variant.Rubric = document.Rubric
return variant
}
@@ -243,13 +275,18 @@ type AssessmentAttemptPublicItem struct {
// AssessmentAttemptPublicItemContent is an allowlisted candidate-facing
// projection of the formats currently produced by the reviewed bank.
type AssessmentAttemptPublicItemContent struct {
Format string `json:"format"`
Unit *string `json:"unit,omitempty"`
Format string `json:"format"`
Unit *string `json:"unit,omitempty"`
// Elements are the elements of an order item or the options of a choice
// item, in the order of this instance.
Elements []AssessmentAttemptPublicOption `json:"elements,omitempty"`
// Multiple says whether a choice item accepts several options. Generated
// choice variants have one correct option and accept one selection.
Multiple bool `json:"multiple,omitempty"`
}
// AssessmentAttemptPublicOption is a generated task element, not a family or
// variant identifier.
// AssessmentAttemptPublicOption is a generated task element or choice option:
// an opaque ID and a text, not a family or variant identifier.
type AssessmentAttemptPublicOption struct {
ID string `json:"id"`
Text string `json:"text"`
@@ -636,8 +673,7 @@ func buildAssessmentAttemptItems(input []AssessmentAttemptItemInput) ([]Assessme
}
func validFrozenVariant(variant AssessmentVariant) bool {
if variant.FamilyID.IsZero() || variant.FamilyVersion < 1 ||
(variant.AnswerFormat != AnswerFormatInteger && variant.AnswerFormat != AnswerFormatIntegerSequence) ||
if variant.FamilyID.IsZero() || variant.FamilyVersion < 1 || !validFrozenVariantFormat(variant) ||
variant.ReferenceAnswer == "" || !utf8.ValidString(variant.ReferenceAnswer) ||
!utf8.ValidString(variant.Statement) || len(variant.Statement) == 0 || len(variant.Statement) > maxStatementBytes ||
!validStoredFamilyKey(variant.FamilyKey) || !validStoredVariantRubric(variant.Rubric) {
@@ -647,6 +683,20 @@ func validFrozenVariant(variant AssessmentVariant) bool {
return err == nil && len(encoded) <= maxAssessmentAttemptVariantBytes
}
// validFrozenVariantFormat accepts the answer formats that the bank
// produces. Only a choice variant carries options, and its key must name one
// of them.
func validFrozenVariantFormat(variant AssessmentVariant) bool {
switch variant.AnswerFormat {
case AnswerFormatInteger, AnswerFormatIntegerSequence:
return len(variant.Options) == 0
case AnswerFormatChoice:
return validFrozenChoiceVariant(variant)
default:
return false
}
}
const maxAssessmentAttemptVariantBytes = 1 << 20
func validStoredFamilyKey(value AssessmentFamilyKey) bool {
@@ -672,6 +722,7 @@ func validStoredVariantRubric(rubric AssessmentRubric) bool {
func cloneAssessmentVariant(variant AssessmentVariant) AssessmentVariant {
variant.Parameters = maps.Clone(variant.Parameters)
variant.Options = cloneChoiceOptions(variant.Options)
variant.Rubric = variant.Rubric.clone()
return variant
}
@@ -1064,6 +1115,17 @@ func publicItemContent(variant AssessmentVariant) (AssessmentAttemptPublicItemCo
switch variant.AnswerFormat {
case AnswerFormatInteger:
return AssessmentAttemptPublicItemContent{Format: "number"}, true
case AnswerFormatChoice:
if !validFrozenChoiceVariant(variant) {
return AssessmentAttemptPublicItemContent{}, false
}
// Only the opaque IDs and the texts leave the server: the index of
// the correct option and the way the distractors were made do not.
options := make([]AssessmentAttemptPublicOption, 0, len(variant.Options))
for _, option := range variant.Options {
options = append(options, AssessmentAttemptPublicOption(option))
}
return AssessmentAttemptPublicItemContent{Format: AnswerFormatChoice, Elements: options}, true
case AnswerFormatIntegerSequence:
taskCount, ok := variant.Parameters["tasks"]
if !ok || taskCount < 2 || taskCount > 20 {
@@ -1205,27 +1267,36 @@ func validAssessmentAttemptPublicState(snapshot AssessmentAttemptPublicSnapshot)
func validAssessmentAttemptPublicItemContent(content AssessmentAttemptPublicItemContent) bool {
switch content.Format {
case "number":
return len(content.Elements) == 0 && (content.Unit == nil || *content.Unit != "" && len(*content.Unit) <= 32)
return len(content.Elements) == 0 && !content.Multiple && (content.Unit == nil || *content.Unit != "" && len(*content.Unit) <= 32)
case AnswerFormatChoice:
return content.Unit == nil && validAssessmentAttemptPublicElements(content.Elements, minChoiceOptions, maxChoiceOptions, assessmentChoiceOptionIDPattern)
case "order":
if content.Unit != nil || len(content.Elements) < 2 || len(content.Elements) > 20 {
return false
}
seen := make(map[string]struct{}, len(content.Elements))
for _, element := range content.Elements {
if !assessmentPublicTaskElementIDPattern.MatchString(element.ID) || element.Text == "" || len(element.Text) > 2000 || !utf8.ValidString(element.Text) {
return false
}
if _, exists := seen[element.ID]; exists {
return false
}
seen[element.ID] = struct{}{}
}
return true
return content.Unit == nil && validAssessmentAttemptPublicElements(content.Elements, 2, 20, assessmentPublicTaskElementIDPattern)
default:
return false
}
}
// validAssessmentAttemptPublicElements checks the options of a choice item or
// the elements of an order item: a bounded count, IDs of the given shape
// without repeats, and non-empty bounded text.
func validAssessmentAttemptPublicElements(elements []AssessmentAttemptPublicOption, minCount, maxCount int, idPattern *regexp.Regexp) bool {
if len(elements) < minCount || len(elements) > maxCount {
return false
}
seen := make(map[string]struct{}, len(elements))
for _, element := range elements {
if !idPattern.MatchString(element.ID) || element.Text == "" || len(element.Text) > 2000 || !utf8.ValidString(element.Text) {
return false
}
if _, exists := seen[element.ID]; exists {
return false
}
seen[element.ID] = struct{}{}
}
return true
}
func (attempt AssessmentAttempt) String() string { return redactedAssessmentAttempt }
func (attempt AssessmentAttempt) GoString() string { return redactedAssessmentAttempt }
func (attempt AssessmentAttempt) Format(state fmt.State, _ rune) {
@@ -0,0 +1,166 @@
package domain
import (
"fmt"
"regexp"
"strconv"
"unicode/utf8"
)
const (
// choiceOptionCount is the number of options that a generated choice
// variant offers: the correct one and choiceOptionCount-1 distractors.
choiceOptionCount = 4
// minChoiceOptions and maxChoiceOptions bound the options of a frozen
// choice variant. They are the bounds of the public contract.
minChoiceOptions = 2
maxChoiceOptions = 10
// maxChoiceOptionBytes bounds the text of one option. The public contract
// allows more; a task option is a short value or phrase.
maxChoiceOptionBytes = 500
)
// assessmentChoiceOptionIDPattern is the shape of an opaque option ID. It
// matches the public contract of AssessmentOptionId.
var assessmentChoiceOptionIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,32}$`)
// AssessmentChoiceOption is one option of a choice variant as the server
// froze it. The ID is opaque: it is drawn from the variant seed after the
// options were put in order, so it says nothing about the position or the
// correctness of the option.
type AssessmentChoiceOption struct {
ID string
Text string
}
// choiceTask is the output of a choice algorithm. The algorithm names the
// correct value and the wrong values that typical mistakes produce; the
// shared code removes duplicates, selects, orders by the seed, and assigns
// the opaque IDs.
type choiceTask struct {
data map[string]string
correct string
// mistakes are the results of known error models, for example an
// off-by-one count or a wrong boundary, in the order of the model list.
// A seed selects among them.
mistakes []string
// nearby are plausible values close to the correct one. They top up the
// distractors only when the mistakes yield too few distinct values, for
// example when two error models coincide on a small input.
nearby []string
}
// newChoiceOptions builds the options of one variant from the correct text and
// the candidate distractors. A candidate that repeats the correct text or an
// earlier candidate is dropped, so no two options show the same text. The
// seed selects wrongCount of the mistakes when there are more, puts the
// options in order, and draws their IDs. It returns the options in
// presentation order and the index of the correct one.
func newChoiceOptions(random *seededRandom, correct string, mistakes, nearby []string, wrongCount int) ([]AssessmentChoiceOption, int, error) {
const location = "domain.newChoiceOptions"
if wrongCount < minChoiceOptions-1 || wrongCount > maxChoiceOptions-1 {
return nil, 0, invalidAssessmentFamily(location, "choice variant must offer 2 to 10 options")
}
seen := map[string]bool{correct: true}
primary := uniqueChoiceTexts(mistakes, seen)
secondary := uniqueChoiceTexts(nearby, seen)
if len(primary) > wrongCount {
// A partial Fisher-Yates shuffle: the seed picks which mistakes appear.
for position := range wrongCount {
swap := position + random.below(len(primary)-position)
primary[position], primary[swap] = primary[swap], primary[position]
}
primary = primary[:wrongCount]
}
wrong := primary
for _, text := range secondary {
if len(wrong) >= wrongCount {
break
}
wrong = append(wrong, text)
}
if len(wrong) < wrongCount {
return nil, 0, invalidAssessmentFamily(location, "choice algorithm produced too few distinct distractors")
}
texts := append([]string{correct}, wrong...)
for position := len(texts) - 1; position > 0; position-- {
swap := random.below(position + 1)
texts[position], texts[swap] = texts[swap], texts[position]
}
options := make([]AssessmentChoiceOption, len(texts))
usedIDs := make(map[string]bool, len(texts))
correctIndex := -1
for position, text := range texts {
if text == correct {
correctIndex = position
}
id := nextChoiceOptionID(random, usedIDs)
options[position] = AssessmentChoiceOption{ID: id, Text: text}
}
return options, correctIndex, nil
}
// uniqueChoiceTexts returns the candidates that are not in seen, without
// repeats, in their order, and adds them to seen. Empty and oversized texts
// are dropped as well, since they cannot be options.
func uniqueChoiceTexts(candidates []string, seen map[string]bool) []string {
unique := make([]string, 0, len(candidates))
for _, text := range candidates {
if text == "" || len(text) > maxChoiceOptionBytes || seen[text] {
continue
}
seen[text] = true
unique = append(unique, text)
}
return unique
}
// nextChoiceOptionID draws an ID that no earlier option of the variant has.
func nextChoiceOptionID(random *seededRandom, used map[string]bool) string {
for {
id := fmt.Sprintf("o%08x", random.next()>>32)
if !used[id] {
used[id] = true
return id
}
}
}
func cloneChoiceOptions(options []AssessmentChoiceOption) []AssessmentChoiceOption {
if len(options) == 0 {
return nil
}
return append([]AssessmentChoiceOption(nil), options...)
}
// choiceCorrectIndex reads the index of the correct option from the reference
// answer of a choice variant.
func choiceCorrectIndex(variant AssessmentVariant) (int, bool) {
index, err := strconv.Atoi(variant.ReferenceAnswer)
if err != nil || index < 0 || index >= len(variant.Options) || strconv.Itoa(index) != variant.ReferenceAnswer {
return 0, false
}
return index, true
}
// validFrozenChoiceVariant checks the options and the key of a frozen choice
// variant: 2 to 10 options with distinct opaque IDs and distinct non-empty
// texts, and a key that is the decimal index of one of them.
func validFrozenChoiceVariant(variant AssessmentVariant) bool {
if len(variant.Options) < minChoiceOptions || len(variant.Options) > maxChoiceOptions {
return false
}
if _, ok := choiceCorrectIndex(variant); !ok {
return false
}
ids := make(map[string]bool, len(variant.Options))
texts := make(map[string]bool, len(variant.Options))
for _, option := range variant.Options {
if !assessmentChoiceOptionIDPattern.MatchString(option.ID) || ids[option.ID] ||
option.Text == "" || len(option.Text) > maxChoiceOptionBytes || !utf8.ValidString(option.Text) || texts[option.Text] {
return false
}
ids[option.ID], texts[option.Text] = true, true
}
return true
}
@@ -0,0 +1,508 @@
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)
}
})
}
}
+3 -2
View File
@@ -237,8 +237,9 @@ func ParseAssessmentLifecycle(value string) (AssessmentLifecycle, error) {
// AssessmentAnswerKey is the reference answer description of a family. The
// reference answer of a variant itself comes from the family's algorithm.
type AssessmentAnswerKey struct {
// AnswerFormat is the format of the reference answer: "integer" or
// "integer_sequence". It must match the algorithm of the generator.
// AnswerFormat is the format of the reference answer: "integer",
// "integer_sequence", or "choice". It must match the algorithm of the
// generator.
AnswerFormat string `json:"answer_format"`
// ReferenceSolution describes the reference approach in prose.
ReferenceSolution string `json:"reference_solution"`
+44 -11
View File
@@ -16,6 +16,9 @@ const (
// AnswerFormatIntegerSequence is decimal integers separated by single
// spaces.
AnswerFormatIntegerSequence = "integer_sequence"
// AnswerFormatChoice is the decimal index of the correct option of a
// choice variant. The options and their order are part of the variant.
AnswerFormatChoice = "choice"
)
// variantSeedDomain separates the seed derivation of variants from any other
@@ -122,7 +125,21 @@ func (generator AssessmentSeedGenerator) instantiate(
}
values[spec.name] = random.between(parameterRange.Min, parameterRange.Max)
}
data, answer := algorithm.generate(random, values)
var (
data map[string]string
answer string
options []AssessmentChoiceOption
)
if algorithm.generateChoice != nil {
task := algorithm.generateChoice(random, values)
built, correct, err := newChoiceOptions(random, task.correct, task.mistakes, task.nearby, choiceOptionCount-1)
if err != nil {
return variantBody{}, fmt.Errorf("AssessmentSeedGenerator.instantiate - build choice options: %w", err)
}
data, answer, options = task.data, strconv.Itoa(correct), built
} else {
data, answer = algorithm.generate(random, values)
}
for name, value := range values {
data[name] = strconv.Itoa(int(value))
}
@@ -130,27 +147,37 @@ func (generator AssessmentSeedGenerator) instantiate(
if err != nil {
return variantBody{}, err
}
return variantBody{parameters: values, statement: rendered, answer: answer}, nil
return variantBody{parameters: values, statement: rendered, answer: answer, options: options}, nil
}
type variantBody struct {
parameters map[string]int32
statement string
answer string
// answer is the reference answer; for a choice variant it is the decimal
// index of the correct option.
answer string
options []AssessmentChoiceOption
}
// AssessmentVariant is one generated task of a family version. The rubric is
// the family's rubric: no seed changes it.
type AssessmentVariant struct {
FamilyID AssessmentFamilyID
FamilyKey AssessmentFamilyKey
FamilyVersion int32
Seed VariantSeed
Parameters map[string]int32
Statement string
FamilyID AssessmentFamilyID
FamilyKey AssessmentFamilyKey
FamilyVersion int32
Seed VariantSeed
Parameters map[string]int32
Statement string
// ReferenceAnswer is the key. For AnswerFormatChoice it is the decimal
// index of the correct entry of Options.
ReferenceAnswer string
AnswerFormat string
Rubric AssessmentRubric
// Options are the options of a choice variant in the order that the
// candidate sees, with the server-side IDs; empty for other formats. They
// are private to the server like the key: a candidate is shown only the
// IDs and texts, never the index of the correct one.
Options []AssessmentChoiceOption
Rubric AssessmentRubric
}
// NewVariant generates the variant of a seed. It is a pure function of the
@@ -181,6 +208,7 @@ func (family AssessmentFamily) NewVariant(seed VariantSeed) (AssessmentVariant,
Statement: body.statement,
ReferenceAnswer: body.answer,
AnswerFormat: algorithm.answerFormat,
Options: body.options,
Rubric: family.core.Rubric.clone(),
}, nil
}
@@ -243,8 +271,13 @@ type assessmentAlgorithm struct {
// the candidate would not see the input.
requiredNames []string
// generate returns the input data for the statement template and the
// reference answer.
// reference answer. It is set for the algorithms of every answer format
// except AnswerFormatChoice.
generate func(random *seededRandom, parameters map[string]int32) (data map[string]string, answer string)
// generateChoice is set instead of generate exactly for the algorithms
// whose answer format is AnswerFormatChoice. It returns the input data, the
// correct value, and the wrong values of known error models.
generateChoice func(random *seededRandom, parameters map[string]int32) choiceTask
}
// probeSeedCount is the number of seeds that an importer renders at the
@@ -96,6 +96,18 @@ type AssessmentAnswerObservation struct {
ObservedAt time.Time
}
// SignalAnswerFormat names the answer format under which the signals observe
// an answer of the given variant format. The speed floors and the duplicate
// evidence cap depend on the size of the answer space: a choice among a few
// options is as small as an integer, so it is observed as one. The stored
// column therefore keeps the two classes it was created with.
func SignalAnswerFormat(answerFormat string) string {
if answerFormat == AnswerFormatChoice {
return AnswerFormatInteger
}
return answerFormat
}
// Validate checks that the observation can be stored.
func (observation AssessmentAnswerObservation) Validate() error {
const location = "AssessmentAnswerObservation.Validate"
@@ -165,3 +165,27 @@ func TestParseAssessmentReviewActorRequiresAnOperatorHandle(t *testing.T) {
}
}
}
// A choice among a few options has an answer space as small as an integer, so
// the signals observe it in that class; a stored observation can hold only the
// two classes it was created with.
func TestSignalAnswerFormatObservesAChoiceLikeAnInteger(t *testing.T) {
for variantFormat, want := range map[string]string{
AnswerFormatChoice: AnswerFormatInteger,
AnswerFormatInteger: AnswerFormatInteger,
AnswerFormatIntegerSequence: AnswerFormatIntegerSequence,
} {
got := SignalAnswerFormat(variantFormat)
if got != want {
t.Errorf("SignalAnswerFormat(%q) = %q, want %q", variantFormat, got, want)
}
observation := AssessmentAnswerObservation{
AttemptID: AssessmentAttemptID(uuid.New()), UserID: uuid.New(), ItemInstanceID: uuid.New(),
FamilyID: AssessmentFamilyID(uuid.New()), FamilyVersion: 1, AnswerFormat: got,
Fingerprint: AssessmentDigest{1}, KeyVersion: 1, ObservedAt: time.Now(),
}
if err := observation.Validate(); err != nil {
t.Errorf("Validate() for variant format %q error = %v", variantFormat, err)
}
}
}
@@ -112,7 +112,7 @@ func (observer *SignalObserver) observeAnswer(
observation := domain.AssessmentAnswerObservation{
AttemptID: snapshot.ID, UserID: snapshot.UserID, ItemInstanceID: item.ID,
FamilyID: item.Variant.FamilyID, FamilyVersion: item.Variant.FamilyVersion, Seed: item.Variant.Seed,
AnswerFormat: item.Variant.AnswerFormat,
AnswerFormat: domain.SignalAnswerFormat(item.Variant.AnswerFormat),
Fingerprint: observer.digester.AssessmentAnswerFingerprint(
uuid.UUID(item.Variant.FamilyID), item.Variant.FamilyVersion, item.Answer,
),