feat(assessment): grade choice answers with distractors from error models
This commit is contained in:
1 parent
efa41d5967
commit
f1147b1885
22 files changed
+1346
-47
No files matched your search
@@ -387,6 +387,21 @@ func assessmentAnswerHTTPBodyWithCorrectness(
|
||||
if err != nil {
|
||||
t.Fatalf("marshal order answer: %v", err)
|
||||
}
|
||||
case domain.AnswerFormatChoice:
|
||||
chosen, err := strconv.Atoi(item.Variant.ReferenceAnswer)
|
||||
if err != nil || chosen < 0 || chosen >= len(item.Variant.Options) {
|
||||
t.Fatalf("frozen choice key %q does not name one of %d options", item.Variant.ReferenceAnswer, len(item.Variant.Options))
|
||||
}
|
||||
if !wantCorrect {
|
||||
chosen = (chosen + 1) % len(item.Variant.Options)
|
||||
}
|
||||
answer, err = json.Marshal(struct {
|
||||
Format string `json:"format"`
|
||||
OptionIDs []string `json:"option_ids"`
|
||||
}{Format: "choice", OptionIDs: []string{item.Variant.Options[chosen].ID}})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal choice answer: %v", err)
|
||||
}
|
||||
default:
|
||||
t.Fatalf("unsupported fixture answer format %q", item.Variant.AnswerFormat)
|
||||
}
|
||||
|
||||
@@ -621,6 +621,19 @@ func seedAssessmentAttemptHTTPBank(ctx context.Context, t *testing.T, pool *pgxp
|
||||
// seedAssessmentAttemptHTTPBankWithSignals seeds the attempt fixture bank under
|
||||
// a product policy that carries the given signal thresholds, or none.
|
||||
func seedAssessmentAttemptHTTPBankWithSignals(ctx context.Context, t *testing.T, pool *pgxpool.Pool, signals *domain.AssessmentSignalPolicy) {
|
||||
t.Helper()
|
||||
seedAssessmentAttemptHTTPBankFrom(ctx, t, pool, signals, loadDemoBundleFile(t))
|
||||
}
|
||||
|
||||
// seedAssessmentAttemptHTTPBankFrom seeds the attempt fixture bank from the
|
||||
// families of the given bundle, which every fixture category repeats in turn.
|
||||
func seedAssessmentAttemptHTTPBankFrom(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
pool *pgxpool.Pool,
|
||||
signals *domain.AssessmentSignalPolicy,
|
||||
sourceBundle assessment.Bundle,
|
||||
) {
|
||||
t.Helper()
|
||||
transactor := postgresadapter.NewTransactor(pool)
|
||||
bank := assessment.NewBank(transactor)
|
||||
@@ -628,7 +641,7 @@ func seedAssessmentAttemptHTTPBankWithSignals(ctx context.Context, t *testing.T,
|
||||
publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now)
|
||||
fixture := assessmentFixture{
|
||||
ctx: ctx, pool: pool, store: store, transactor: transactor,
|
||||
bank: bank, publisher: publisher, demoBundle: loadDemoBundleFile(t),
|
||||
bank: bank, publisher: publisher, demoBundle: sourceBundle,
|
||||
}
|
||||
productPolicy := integrationPolicy(11)
|
||||
productPolicy.Assessment.MaxAttemptsPerWindow = 1
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
// choiceBankFamilies returns the families of a bank that offers the choice
|
||||
// answer format next to the integer one: a choice family whose distractors
|
||||
// come from error models, and the first demo family. The choice family reuses
|
||||
// the rubric and the identity of the first demo family.
|
||||
func choiceBankFamilies(t *testing.T, base assessment.BundleFamily) []assessment.BundleFamily {
|
||||
t.Helper()
|
||||
choice := base
|
||||
choice.Key = "choice-lru-hits"
|
||||
choice.SeedGenerator = domain.AssessmentSeedGenerator{
|
||||
Algorithm: "lru_hits_choice.v1",
|
||||
Parameters: map[string]domain.AssessmentParameterRange{
|
||||
"accesses": {Min: 12, Max: 30}, "keys": {Min: 4, Max: 8}, "capacity": {Min: 2, Max: 4},
|
||||
},
|
||||
StatementTemplate: "A cache of capacity {{.capacity}} drops its least recently used key when it is full. Keys are read in this order: {{.sequence}}. How many reads find their key in the cache?",
|
||||
}
|
||||
choice.AnswerKey = domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatChoice, ReferenceSolution: "Simulate the cache."}
|
||||
return []assessment.BundleFamily{choice, base}
|
||||
}
|
||||
|
||||
// allowedItemKeys are the fields that a candidate item may carry per format.
|
||||
var allowedItemContentKeys = map[string][]string{
|
||||
"number": {"format", "unit"},
|
||||
"choice": {"format", "multiple", "options"},
|
||||
}
|
||||
|
||||
func TestAssessmentChoiceFamiliesAreServedAndGradedOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolatedEnv := *env
|
||||
isolatedEnv.Config.DatabaseURL = databaseURL
|
||||
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
||||
|
||||
source := loadDemoBundleFile(t)
|
||||
source.Families = choiceBankFamilies(t, source.Families[0])
|
||||
seedAssessmentAttemptHTTPBankFrom(ctx, t, harness.pool, nil, source)
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "choice-owner@example.test", passwordHash, true)
|
||||
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil {
|
||||
t.Fatalf("set candidate onboarding step: %v", err)
|
||||
}
|
||||
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.140:1234")
|
||||
if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.141:1234"); response.Code != http.StatusOK {
|
||||
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.142:1234")
|
||||
|
||||
create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
||||
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf,
|
||||
"choice-flow-create", "203.0.113.143:1234")
|
||||
if create.Code != http.StatusCreated {
|
||||
t.Fatalf("create real attempt = %d %s; logs: %s", create.Code, create.Body.String(), harness.logs.String())
|
||||
}
|
||||
var attempt assessmentAnswerHTTPAttempt
|
||||
if err := json.Unmarshal(create.Body.Bytes(), &attempt); err != nil || attempt.ID == uuid.Nil || attempt.CurrentItem == nil {
|
||||
t.Fatalf("created attempt = %+v, decode error %v", attempt, err)
|
||||
}
|
||||
items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID)
|
||||
formats := make(map[string]int)
|
||||
for _, item := range items {
|
||||
formats[item.Variant.AnswerFormat]++
|
||||
}
|
||||
if formats[domain.AnswerFormatChoice] < 2 || formats[domain.AnswerFormatInteger] < 1 {
|
||||
t.Fatalf("frozen formats = %v, want at least two choice items and one integer item", formats)
|
||||
}
|
||||
|
||||
attemptsPath := "/api/v1/me/assessment-attempts/" + attempt.ID.String()
|
||||
assertCandidateItem := func(label string, body []byte, item assessmentAnswerHTTPItem) {
|
||||
t.Helper()
|
||||
assertAssessmentChoiceItemDTO(t, label, body, item)
|
||||
}
|
||||
assertCandidateItem("create response", create.Body.Bytes(), items[0])
|
||||
|
||||
// Answers: a choice item alternates between a wrong and a correct option
|
||||
// (starting wrong), and every other item is answered correctly.
|
||||
version, choiceIndex := attempt.Version, 0
|
||||
var wantCorrect []bool
|
||||
for _, item := range items {
|
||||
correct := true
|
||||
if item.Variant.AnswerFormat == domain.AnswerFormatChoice {
|
||||
correct = choiceIndex%2 == 1
|
||||
choiceIndex++
|
||||
}
|
||||
wantCorrect = append(wantCorrect, correct)
|
||||
if item.Ordinal == 1 {
|
||||
assertChoiceAnswerProblems(t, harness, attemptsPath, cookie.Value, csrf, version, item)
|
||||
}
|
||||
body := assessmentAnswerHTTPBodyWithCorrectness(t, version, item, correct)
|
||||
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, attemptsPath+"/answers", string(body),
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("choice-flow-item-%d", item.Ordinal),
|
||||
fmt.Sprintf("203.0.113.%d:1234", 150+item.Ordinal))
|
||||
var next assessmentAnswerHTTPAttempt
|
||||
if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil || next.Version != version+1 {
|
||||
t.Fatalf("answer item %d = %d %s, want version %d", item.Ordinal, response.Code, response.Body.String(), version+1)
|
||||
}
|
||||
if int(item.Ordinal) < len(items) {
|
||||
assertCandidateItem(fmt.Sprintf("response after item %d", item.Ordinal), response.Body.Bytes(), items[item.Ordinal])
|
||||
}
|
||||
version = next.Version
|
||||
}
|
||||
|
||||
// The wrong-then-correct alternation of the choice items reached the
|
||||
// result through the key: the server scored the first max_points items.
|
||||
finalizeBody, err := json.Marshal(map[string]int64{"expected_version": version})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal finalization: %v", err)
|
||||
}
|
||||
finalized := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, attemptsPath+"/finalize", string(finalizeBody),
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "choice-flow-finalize", "203.0.113.190:1234")
|
||||
if finalized.Code != http.StatusOK {
|
||||
t.Fatalf("finalize = %d %s", finalized.Code, finalized.Body.String())
|
||||
}
|
||||
result := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, attemptsPath+"/result", "", "", cookie.Value, "", "", "203.0.113.191:1234")
|
||||
var document struct {
|
||||
BasicScore struct {
|
||||
Points int `json:"points"`
|
||||
MaxPoints int `json:"max_points"`
|
||||
} `json:"basic_score"`
|
||||
}
|
||||
if result.Code != http.StatusOK || json.Unmarshal(result.Body.Bytes(), &document) != nil || document.BasicScore.MaxPoints < 1 {
|
||||
t.Fatalf("result = %d %s, want a basic score", result.Code, result.Body.String())
|
||||
}
|
||||
wantPoints := 0
|
||||
for _, correct := range wantCorrect[:document.BasicScore.MaxPoints] {
|
||||
if correct {
|
||||
wantPoints++
|
||||
}
|
||||
}
|
||||
if document.BasicScore.Points != wantPoints || wantPoints == document.BasicScore.MaxPoints {
|
||||
t.Fatalf("score = %d of %d, want %d: every wrong choice scores nothing and every correct one scores", document.BasicScore.Points, document.BasicScore.MaxPoints, wantPoints)
|
||||
}
|
||||
for _, private := range []string{"ReferenceAnswer", "answer_key", "option_ids", "distractor"} {
|
||||
if strings.Contains(result.Body.String(), private) {
|
||||
t.Fatalf("result exposes %q: %s", private, result.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Every accepted answer left a signal observation; a choice is observed as
|
||||
// an answer of a small answer space, like an integer.
|
||||
var observed, choiceObserved int
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_answer_observations WHERE attempt_id=$1`, attempt.ID).Scan(&observed); err != nil || observed != len(items) {
|
||||
t.Fatalf("answer observations = %d, %v, want %d", observed, err, len(items))
|
||||
}
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_answer_observations WHERE attempt_id=$1 AND answer_format='integer'`, attempt.ID).Scan(&choiceObserved); err != nil ||
|
||||
choiceObserved != formats[domain.AnswerFormatChoice]+formats[domain.AnswerFormatInteger] {
|
||||
t.Fatalf("observations of the integer class = %d, %v, want %d", choiceObserved, err, formats[domain.AnswerFormatChoice]+formats[domain.AnswerFormatInteger])
|
||||
}
|
||||
}
|
||||
|
||||
// assertAssessmentChoiceItemDTO checks that the candidate sees the item of
|
||||
// the attempt in the allowlisted shape: for a choice item the opaque option
|
||||
// IDs and texts in the stored order, and no key or service field anywhere.
|
||||
func assertAssessmentChoiceItemDTO(t *testing.T, label string, body []byte, item assessmentAnswerHTTPItem) {
|
||||
t.Helper()
|
||||
var document struct {
|
||||
CurrentItem map[string]json.RawMessage `json:"current_item"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &document); err != nil || document.CurrentItem == nil {
|
||||
t.Fatalf("%s: no current item in %s (%v)", label, body, err)
|
||||
}
|
||||
var itemKeys []string
|
||||
for key := range document.CurrentItem {
|
||||
itemKeys = append(itemKeys, key)
|
||||
}
|
||||
slices.Sort(itemKeys)
|
||||
var id uuid.UUID
|
||||
if !slices.Equal(itemKeys, []string{"content", "id", "prompt", "sequence"}) ||
|
||||
json.Unmarshal(document.CurrentItem["id"], &id) != nil || id != item.ID {
|
||||
t.Fatalf("%s: item keys %v for item %s, want exactly content, id, prompt, and sequence of %s", label, itemKeys, id, item.ID)
|
||||
}
|
||||
var content map[string]json.RawMessage
|
||||
if err := json.Unmarshal(document.CurrentItem["content"], &content); err != nil {
|
||||
t.Fatalf("%s: decode content: %v", label, err)
|
||||
}
|
||||
var format string
|
||||
if err := json.Unmarshal(content["format"], &format); err != nil {
|
||||
t.Fatalf("%s: decode content format: %v", label, err)
|
||||
}
|
||||
var contentKeys []string
|
||||
for key := range content {
|
||||
contentKeys = append(contentKeys, key)
|
||||
}
|
||||
slices.Sort(contentKeys)
|
||||
if want, known := allowedItemContentKeys[format]; !known || !slices.Equal(contentKeys, want) {
|
||||
t.Fatalf("%s: content of format %q has keys %v, want %v", label, format, contentKeys, want)
|
||||
}
|
||||
if item.Variant.AnswerFormat == domain.AnswerFormatChoice {
|
||||
var options []map[string]string
|
||||
if err := json.Unmarshal(content["options"], &options); err != nil || len(options) != len(item.Variant.Options) {
|
||||
t.Fatalf("%s: options = %v, %v, want %d", label, options, err, len(item.Variant.Options))
|
||||
}
|
||||
for position, option := range options {
|
||||
stored := item.Variant.Options[position]
|
||||
if len(option) != 2 || option["id"] != stored.ID || option["text"] != stored.Text {
|
||||
t.Fatalf("%s: option %d = %v, want only the ID and the text of the stored option", label, position, option)
|
||||
}
|
||||
}
|
||||
if string(content["multiple"]) != "false" {
|
||||
t.Fatalf("%s: multiple = %s, want false", label, content["multiple"])
|
||||
}
|
||||
}
|
||||
for _, private := range []string{"ReferenceAnswer", "reference", "answer_key", "distractor", "mistake", "correct", "\"seed\"", "variant", "\"row\""} {
|
||||
if strings.Contains(string(body), private) {
|
||||
t.Fatalf("%s: candidate response contains %q: %s", label, private, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// assertChoiceAnswerProblems checks that an option the item does not have and
|
||||
// a selection of two options are refused as invalid input, without an answer
|
||||
// being stored. It is a no-op for an item that is not a choice.
|
||||
func assertChoiceAnswerProblems(
|
||||
t *testing.T,
|
||||
harness *assessmentAttemptHTTPHarness,
|
||||
attemptsPath, session, csrf string,
|
||||
version int64,
|
||||
item assessmentAnswerHTTPItem,
|
||||
) {
|
||||
t.Helper()
|
||||
if item.Variant.AnswerFormat != domain.AnswerFormatChoice {
|
||||
return
|
||||
}
|
||||
for name, selection := range map[string][]string{
|
||||
"an option of no item": {"onotanoption"},
|
||||
"two options at once": {item.Variant.Options[0].ID, item.Variant.Options[1].ID},
|
||||
} {
|
||||
encoded, err := json.Marshal(map[string]any{
|
||||
"expected_version": version, "item_id": item.ID,
|
||||
"answer": map[string]any{"format": "choice", "option_ids": selection},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal %s: %v", name, err)
|
||||
}
|
||||
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, attemptsPath+"/answers", string(encoded),
|
||||
sessionHTTPTestOrigin, session, csrf, "choice-flow-bad-"+strings.ReplaceAll(name, " ", "-"), "203.0.113.149:1234")
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("answer with %s = %d %s, want 400", name, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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"`
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
|
||||
+2
-2
@@ -36,5 +36,5 @@ reference solutions, and rubrics.
|
||||
Documented by the types `assessment.Bundle` and `domain.AssessmentFamily`.
|
||||
Seed algorithms are registered in `internal/domain/assessment_algorithms.go`
|
||||
under versioned names (`rate_limit_window.v1`, `dedup_window.v1`,
|
||||
`lru_hits.v1`, `dependency_order.v1`); the statement templates use the
|
||||
parameter names and the data names of the chosen algorithm.
|
||||
`lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`); the statement
|
||||
templates use the parameter names and the data names of the chosen algorithm.
|
||||
@@ -667,7 +667,8 @@ Implemented as storage and a loader, not as a candidate-facing feature: migratio
|
||||
- Family version. One `assessment_families` row is one version of one family (`family_key`, `version`): category, specialization (the domain inside the category), title, author (`ai:<name>` or `operator:<handle>`), reviewer (`operator:<handle>` or NULL), `review_status` (`pending`, `approved`, `rejected`), the seed generator, the answer key, the rubric, a content hash with its `hash_scheme`, a lifecycle (`draft`, `published`, `retired`), and the operators and times of publication and retirement. The reviewer is never the author, and a review is pending exactly while there is no reviewer (CHECK constraints; the domain applies the same rules). The reviewer in a bundle and the operator of a publication are declared values, not authenticated identities, until reviewer and operator accounts exist.
|
||||
- Immutability. The content of a stored version never changes: the trigger `assessment_families_guard_update` refuses every UPDATE that changes a column other than the lifecycle columns (`lifecycle`, `published_at`, `published_by`, `retired_at`, `retired_by`), and `assessment_families_refuse_removal` refuses DELETE and TRUNCATE, all with SQLSTATE 23000 and the constraint name `assessment_families_immutable`, which the adapter maps to `outbound.ErrAssessmentFamilyImmutable`. The lifecycle moves only forward (draft, published, retired), the trigger sets the times and keeps the publisher through a retirement, and a version is published only with an approved review by a reviewer (`assessment_families_published_requires_review`). A change is a new version with the next number; the loader accepts only version 1 for a new family and the successor of the latest version otherwise. A pending draft is never approved in place: its review is recorded by importing a new version of the family that carries the review, and the pending version stays an unpublished draft. The domain recomputes the content hash when it reads a row and returns `ErrAssessmentFamilyIntegrity` for a row changed outside the application. The hash is the SHA-256 of a canonical JSON document that holds the content without the bundle name, ID, lifecycle, and publication fields. The `hash_scheme` column (a smallint with a CHECK of the known values, one of the immutable columns) names the layout: the domain verifies a row with the hash function of the scheme the row was stored with, so a later scheme (a new function and a new CHECK value, never an edit of scheme 1) verifies new rows without invalidating old ones, and a row with an unknown scheme is refused; tests verify a row with its own scheme and pin the scheme 1 hash of a fixed input. As for `policy_versions`, a role that owns the table can still disable the triggers.
|
||||
- One published version per family. A partial unique index (`assessment_families_one_published_key`) allows at most one published version of a key. `Bank.PublishFamily` retires the published older version in the same transaction and refuses with `newer_version_published` when a newer version of the key exists in any state, a draft or a retired one included, so superseded content is never put back in the bank (earlier content is published again by importing it as a new version); `Bank.ActiveFamily` reads the single published version. Coverage counts each family once.
|
||||
- Seed generator and variants. A generator names a registered algorithm with a versioned name (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `dependency_order.v1`), the ranges of its parameters, and a statement template. A seed selects a variant: the same version and seed always give the same statement and reference answer (the pseudo-random source is SplitMix64 written out in the domain, so variants stay reproducible across Go releases; golden tests pin one statement and answer per algorithm), and the rubric is a property of the family, so no seed changes it. The reference answer comes from the algorithm's solver, which has unit tests with hand-computed cases. The registry only grows: a changed algorithm gets a new name, because stored versions refer to the old one.
|
||||
- Seed generator and variants. A generator names a registered algorithm with a versioned name (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`), the ranges of its parameters, and a statement template. A seed selects a variant: the same version and seed always give the same statement and reference answer (the pseudo-random source is SplitMix64 written out in the domain, so variants stay reproducible across Go releases; golden tests pin one statement and answer per algorithm), and the rubric is a property of the family, so no seed changes it. The reference answer comes from the algorithm's solver, which has unit tests with hand-computed cases. The registry only grows: a changed algorithm gets a new name, because stored versions refer to the old one.
|
||||
- Choice answer format. The answer format `choice` offers options instead of asking for a value. A choice variant stores its options and the key on the server: the frozen variant holds the options in presentation order, each with an opaque ID and a text, and the reference answer is the decimal index of the correct one. The candidate receives the option IDs and texts in that order (`ChoiceItemContent` of the public contract, `multiple` false) and nothing else: not the index, not the seed, and not how a distractor was made (the allowlisted projection and the response snapshot are checked for this). The seed decides the order of the options and the IDs: the order is a seeded Fisher-Yates shuffle, and each ID is drawn after the shuffle, so an ID says nothing about the position or the correctness of its option; the same family version and seed give the same options in the same order. A choice answer names the selected option IDs (`{"format":"choice","option_ids":[...]}`); the server grades it against the key. An ID that is not an option of the item, a second option, or an answer of another format is an invalid answer (400), not a wrong one. Distractors come from the algorithm, not from chance: a choice algorithm returns the correct value and the wrong values of known error models, and the shared code removes duplicates and the correct value, lets the seed choose among the mistakes, and tops up from plausible nearby values only when the mistakes give too few distinct ones. The registered `lru_hits_choice.v1` asks for the number of cache hits and offers wrong counts from an off-by-one count in either direction, counting misses instead of hits, a cache where a hit does not renew a key (FIFO), a cache that evicts the most recently used key, and a capacity off by one in either direction; its parameter bounds guarantee enough distinct values. The signals observe a choice answer as an answer of a small answer space, like an integer (`domain.SignalAnswerFormat`), so the observation column keeps its two classes. A choice variant is stored with an `Options` field in the frozen variant document, which is omitted for the other formats, so stored attempts keep decoding.
|
||||
- Statement templates. A template is plain text with `{{.name}}` placeholders and nothing else: the text/template parser reads it without functions, and a whitelist walk refuses every node except text and a single field action (so `define`, `template`, `block`, `range`, `with`, `if`, variables, pipelines, and calls such as `printf` are refused). The loader renders the placeholders itself, never runs the template engine, and caps the template at 2000 bytes and the rendered statement at 8 KiB. Every placeholder must belong to the algorithm, and the template must contain the placeholders the answer depends on (the input data and the answer-relevant parameters), so a statement always shows the input. A bundle is validated fully at import, with probe renders at the lowest parameter values and, for eight seeds each, at the highest values (the largest inputs) and at drawn values, so a template close to the size cap cannot pass on one lucky seed; reading a stored row does not repeat the probes, because the content hash proves the content is the one that passed them. Titles, templates, and rubric texts refuse control characters, Unicode format characters (for example bidirectional overrides), and the line and paragraph separators U+2028 and U+2029; the title CHECK constraint also refuses the common ones.
|
||||
- Rubric. A rubric holds a principle and a list of criteria. It has no points, weights, or pass mark; how criteria become a grade is not decided in the bank.
|
||||
- Lifecycle and the loader. `Bank.ImportBundle` stores every family of a bundle as a draft in one transaction and never publishes, whatever the review says; importing the same bundle again, also concurrently, reports the versions as unchanged. `Bank.PublishFamily` and `Bank.RetireFamily` take the operator, and refuse with a reason (`reviewer_missing`, `review_not_approved`, `not_draft`, `not_published`, `newer_version_published`); the refusal is a `*domain.AssessmentRefusalError` that carries the reason, and the sentinels of a race that the database decided (a lifecycle step that lost to another, a missing approved review, insufficient coverage) become the same refusals. Publishing, retiring, and opening take a transaction-scoped advisory lock of the category first, so they run one after another per category; `LockCategory` works only inside a transaction (the repository of a unit of work takes it, the standalone store returns `ErrAssessmentLockOutsideTransaction`).
|
||||
|
||||
@@ -183,7 +183,7 @@ A record that depends on policy values adds `policy_version_id uuid NOT NULL REF
|
||||
|
||||
### Assessment bank
|
||||
|
||||
Migration `00011_create_assessment_bank.sql` creates `assessment_families` (immutable family versions) and `assessment_category_openings`; the queries are in `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` is available through `UnitOfWork.AssessmentBank()` and `postgres.AssessmentBankStore` outside a transaction; `assessment.Bank` imports a `Bundle`, publishes a version as an operator (retiring the published older one), retires it, opens a category under the policy version in force, reports live availability, and generates a variant of a seed. To change a family, import a new version; a stored version is never edited, and a pending draft is approved by importing a new version that carries the review. A new seed algorithm gets a new versioned name in `domain/assessment_algorithms.go`, its required placeholders, a solver test with hand-computed cases, and a golden test; never change a registered algorithm. Statement templates are plain text with `{{.name}}` placeholders only. The demo bundle in `backend/testdata/assessment/` is an unreviewed AI draft: do not fill in its reviewer to open the category. See [ARCHITECTURE.md](ARCHITECTURE.md#assessment-bank).
|
||||
Migration `00011_create_assessment_bank.sql` creates `assessment_families` (immutable family versions) and `assessment_category_openings`; the queries are in `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` is available through `UnitOfWork.AssessmentBank()` and `postgres.AssessmentBankStore` outside a transaction; `assessment.Bank` imports a `Bundle`, publishes a version as an operator (retiring the published older one), retires it, opens a category under the policy version in force, reports live availability, and generates a variant of a seed. To change a family, import a new version; a stored version is never edited, and a pending draft is approved by importing a new version that carries the review. A new seed algorithm gets a new versioned name in `domain/assessment_algorithms.go`, its required placeholders, a solver test with hand-computed cases, and a golden test; never change a registered algorithm. An algorithm with the answer format `choice` sets `generateChoice` instead of `generate` and returns the correct value with the wrong values of named error models (`lru_hits_choice.v1` is the example); its tests recompute the error models from the statement. The demo bundle in `backend/testdata/assessment/` is an unreviewed AI draft: do not fill in its reviewer to open the category. See [ARCHITECTURE.md](ARCHITECTURE.md#assessment-bank).
|
||||
|
||||
### Outbox relay
|
||||
|
||||
|
||||
+2
-1
@@ -498,7 +498,7 @@ Unit tests (`make -C backend test`) check the visibility rules without a databas
|
||||
|
||||
## Assessment bank tests
|
||||
|
||||
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go`, and `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) check without a database: invalid family content is refused (review rules, unknown algorithm, parameter bounds, answer format mismatch, rubric shape, Unicode format characters); statement templates accept only text and `{{.name}}` placeholders, and a nested `define` bomb, a `printf` width bomb, a `range` over a number, and a recursive `block` are refused within a second without being run; a template without the placeholders its answer depends on is refused; the rendered statement size is bounded; a changed stored document fails the hash check; each publication refusal names its reason; one seed gives one variant while the rubric stays the same across seeds; golden tests pin the exact statement and reference answer of a fixed seed for each of the four algorithms and the scheme 1 content hash of a fixed input; a row is verified with the hash scheme it was stored with (a test registers a second scheme, and a hash of one scheme under the name of the other, or an unknown scheme, is refused); a template whose statement reaches the size bound for one probe seed only is refused at import, because the highest parameter values are rendered for eight seeds; the line and paragraph separators are refused like format characters; the four solvers match hand-computed cases; the coverage required for an opening is `max_scored_items` plus `seed_items` of the policy; and the demo bundle parses as an AI draft with a pending review and no reviewer. With in-memory fakes of the repository and the unit of work, the usecase tests prove that a concurrent identical import reports the version as unchanged and a concurrent import with other content is refused, that the sentinels of database races become refusals with the matching reason, that publishing retires the older published version after taking the category lock and is refused when a newer one is published, that opening requires the policy version in force, that availability is refused when the published count falls below the opening's requirement or when the opening's policy version is no longer in force, and that an older approved draft is refused while a newer version exists as a draft, a published, or a retired one. `internal/adapter/secondary/postgres/assessment_bank_test.go` checks that the bank constraints map to their sentinels without the failing row, that a list page outside its limit fails before any statement, and that the category lock is refused outside a transaction.
|
||||
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go`, and `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) check without a database: invalid family content is refused (review rules, unknown algorithm, parameter bounds, answer format mismatch, rubric shape, Unicode format characters); statement templates accept only text and `{{.name}}` placeholders, and a nested `define` bomb, a `printf` width bomb, a `range` over a number, and a recursive `block` are refused within a second without being run; a template without the placeholders its answer depends on is refused; the rendered statement size is bounded; a changed stored document fails the hash check; each publication refusal names its reason; one seed gives one variant while the rubric stays the same across seeds; golden tests pin the exact statement and reference answer of a fixed seed for each of the four algorithms and the scheme 1 content hash of a fixed input; a row is verified with the hash scheme it was stored with (a test registers a second scheme, and a hash of one scheme under the name of the other, or an unknown scheme, is refused); a template whose statement reaches the size bound for one probe seed only is refused at import, because the highest parameter values are rendered for eight seeds; the line and paragraph separators are refused like format characters; the four solvers match hand-computed cases; the coverage required for an opening is `max_scored_items` plus `seed_items` of the policy; and the demo bundle parses as an AI draft with a pending review and no reviewer. `assessment_choice_test.go` covers the choice format without a database: the same seed gives identical options, IDs, and order, and across 400 seeds the correct option appears at every position; every distractor of `lru_hits_choice.v1` is recomputed from the statement as the result of a named error model (and the nearby fill-in is used only when the models give fewer than three distinct values), the options never repeat a text, the cache models match hand-computed cases and the LRU model equals the solver of `lru_hits.v1`, and a golden test pins the options, their IDs, and the key of one seed; the correct option, a wrong option, an option of no item, two options, a number answer for a choice item, and a choice answer for an integer item are graded or refused as stated, the candidate projection holds only the opaque IDs and texts, and a broken key or repeated option of a frozen variant is refused.
|
||||
|
||||
`TestAssessmentBank` in `backend/integration_test/assessment_bank_test.go` uses `bootstrap(t, postgresService)` and gives every case its own migrated database:
|
||||
|
||||
@@ -510,6 +510,7 @@ Unit tests (`make -C backend test`) check the visibility rules without a databas
|
||||
- Publishing a later version of a family retires the published older version and records both operators; publishing an older version while a newer one is published is refused; the table allows one published version per family and refuses a rewrite of the recorded publisher.
|
||||
- A transaction that holds the category lock makes an opening wait until the deadline, and the opening succeeds after the lock is released.
|
||||
- An older approved draft cannot be published once a newer version exists, also when that version is retired. Policy-in-force checks use the database clock, with no clock offset in the test.
|
||||
- `TestAssessmentChoiceFamiliesAreServedAndGradedOverHTTP` in `backend/integration_test/assessment_choice_http_test.go` runs a real attempt over a bank of a choice algorithm and an integer algorithm: every item the candidate receives has only the allowlisted fields (for a choice the option IDs and texts in the stored order, and no key, seed, or distractor field), an option of no item and two options are refused with 400, a wrong choice scores nothing and a right one scores through the key, the result matches the expected points, and every answer left a signal observation.
|
||||
- Raw policy rows whose document lacks the scored item bounds or holds them as text, as an oversized, fractional, or negative number, or without the seed items are refused by the opening trigger with the thresholds refusal, not with a cast error; a stored hash scheme outside the CHECK list is refused, and the scheme cannot be edited.
|
||||
- Written around the usecase, an opening that claims a lower requirement, an opening below the coverage, an opening under an unknown policy version, and a title with a bidirectional override are refused by the table.
|
||||
- Families are listed in pages of two after a cursor, each once and in order.
|
||||
|
||||
@@ -667,7 +667,8 @@ contact_grant относится к паре кандидат-компания
|
||||
- Версия семейства. Одна строка `assessment_families` - одна версия одного семейства (`family_key`, `version`): категория, специализация (область внутри категории), название, автор (`ai:<name>` или `operator:<handle>`), рецензент (`operator:<handle>` или NULL), `review_status` (`pending`, `approved`, `rejected`), генератор по seed, ключ ответа, рубрика, хеш содержимого с его `hash_scheme`, жизненный цикл (`draft`, `published`, `retired`) и операторы и время публикации и вывода из обращения. Рецензент не бывает автором, а рецензия остается `pending`, пока рецензента нет (CHECK-ограничения; домен применяет те же правила). Рецензент в пакете и оператор публикации - заявленные значения, а не аутентифицированные личности, пока нет учетных записей рецензентов и операторов.
|
||||
- Неизменяемость. Содержимое сохраненной версии не меняется: триггер `assessment_families_guard_update` отклоняет любой UPDATE, который меняет колонки кроме колонок жизненного цикла (`lifecycle`, `published_at`, `published_by`, `retired_at`, `retired_by`), а `assessment_families_refuse_removal` отклоняет DELETE и TRUNCATE, все с SQLSTATE 23000 и именем ограничения `assessment_families_immutable`, которое адаптер преобразует в `outbound.ErrAssessmentFamilyImmutable`. Жизненный цикл идет только вперед (draft, published, retired), время ставит триггер и он же сохраняет публикатора при выводе из обращения, а версия публикуется только с одобренной рецензией рецензента (`assessment_families_published_requires_review`). Изменение - это новая версия со следующим номером: загрузчик принимает версию 1 для нового семейства и преемника последней версии для существующего. Черновик с рецензией `pending` никогда не одобряется на месте: рецензия записывается импортом новой версии семейства, которая ее несет, а версия `pending` остается неопубликованным черновиком. Домен пересчитывает хеш содержимого при чтении строки и возвращает `ErrAssessmentFamilyIntegrity`, если строку изменили вне приложения. Хеш - это SHA-256 канонического JSON-документа, который содержит содержимое без имени пакета, ID, жизненного цикла и полей публикации. Колонка `hash_scheme` (smallint с CHECK известных значений, одна из неизменяемых колонок) называет формат: домен проверяет строку хеш-функцией той схемы, с которой строка сохранена, поэтому следующая схема (новая функция и новое значение CHECK, а не правка схемы 1) проверяет новые строки и не ломает старые, а строка с неизвестной схемой отклоняется; тесты проверяют строку ее собственной схемой и фиксируют хеш схемы 1 для заданного входа. Как и для `policy_versions`, роль-владелец таблицы все еще может отключить триггеры.
|
||||
- Одна опубликованная версия на семейство. Частичный уникальный индекс (`assessment_families_one_published_key`) допускает не более одной опубликованной версии ключа. `Bank.PublishFamily` в той же транзакции выводит из обращения опубликованную более старую версию и отказывает с `newer_version_published`, если существует более новая версия ключа в любом состоянии, включая черновик и выведенную из обращения, поэтому устаревшее содержимое не возвращается в банк (прежнее содержимое публикуется снова импортом как новая версия); `Bank.ActiveFamily` читает единственную опубликованную версию. Покрытие считает каждое семейство один раз.
|
||||
- Генератор и варианты. Генератор называет зарегистрированный алгоритм с версионным именем (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `dependency_order.v1`), диапазоны его параметров и шаблон условия. Seed выбирает вариант: одинаковые версия и seed всегда дают одинаковые условие и эталонный ответ (источник псевдослучайных чисел - SplitMix64, записанный в домене, поэтому варианты воспроизводимы между версиями Go; golden-тесты фиксируют по одному условию и ответу на алгоритм), а рубрика - свойство семейства, поэтому seed ее не меняет. Эталонный ответ считает решатель алгоритма; для него есть unit-тесты с посчитанными вручную случаями. Реестр только растет: измененный алгоритм получает новое имя, потому что сохраненные версии ссылаются на старое.
|
||||
- Генератор и варианты. Генератор называет зарегистрированный алгоритм с версионным именем (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`), диапазоны его параметров и шаблон условия. Seed выбирает вариант: одинаковые версия и seed всегда дают одинаковые условие и эталонный ответ (источник псевдослучайных чисел - SplitMix64, записанный в домене, поэтому варианты воспроизводимы между версиями Go; golden-тесты фиксируют по одному условию и ответу на алгоритм), а рубрика - свойство семейства, поэтому seed ее не меняет. Эталонный ответ считает решатель алгоритма; для него есть unit-тесты с посчитанными вручную случаями. Реестр только растет: измененный алгоритм получает новое имя, потому что сохраненные версии ссылаются на старое.
|
||||
- Формат ответа с выбором. Формат ответа `choice` предлагает варианты вместо ввода значения. Вариант с выбором хранит варианты ответа и ключ на сервере: замороженный вариант содержит варианты в порядке показа, у каждого непрозрачный ID и текст, а эталонный ответ - десятичный индекс правильного. Кандидат получает ID и тексты вариантов в этом порядке (`ChoiceItemContent` публичного контракта, `multiple` равно false) и ничего больше: ни индекса, ни seed, ни того, как сделан отвлекающий вариант (для этого проверяются проекция по белому списку и снимок ответа). Seed определяет порядок вариантов и ID: порядок - перемешивание Фишера-Йетса по seed, а каждый ID выбирается после перемешивания, поэтому ID ничего не говорит о позиции и правильности варианта; одинаковые версия семейства и seed дают одинаковые варианты в одинаковом порядке. Ответ с выбором называет выбранные ID (`{"format":"choice","option_ids":[...]}`), сервер оценивает его по ключу. ID, которого нет среди вариантов задания, второй вариант или ответ другого формата - это некорректный ответ (400), а не неверный. Отвлекающие варианты дает алгоритм, а не случай: алгоритм с выбором возвращает правильное значение и неверные значения известных моделей ошибок, а общий код убирает повторы и правильное значение, дает seed выбрать среди ошибок и добирает правдоподобными соседними значениями, только если ошибки дали слишком мало различных. Зарегистрированный `lru_hits_choice.v1` спрашивает число попаданий в кэш и предлагает неверные числа из ошибки на единицу в обе стороны, подсчета промахов вместо попаданий, кэша, где попадание не обновляет ключ (FIFO), кэша, вытесняющего самый недавний ключ, и емкости, неверной на единицу в обе стороны; границы его параметров гарантируют достаточно различных значений. Сигналы наблюдают ответ с выбором как ответ с малым пространством ответов, как целое число (`domain.SignalAnswerFormat`), поэтому колонка наблюдений сохраняет свои два класса. Вариант с выбором хранится с полем `Options` в документе замороженного варианта; для других форматов поле опускается, поэтому сохраненные попытки продолжают читаться.
|
||||
- Шаблоны условий. Шаблон - обычный текст с подстановками `{{.name}}` и ничем больше: парсер text/template читает его без функций, а обход по белому списку отклоняет любой узел кроме текста и одного обращения к полю (то есть `define`, `template`, `block`, `range`, `with`, `if`, переменные, конвейеры и вызовы вроде `printf` отклоняются). Загрузчик подставляет значения сам и не запускает движок шаблонов, ограничивает шаблон 2000 байтами, а готовое условие 8 КиБ. Каждая подстановка должна принадлежать алгоритму, а шаблон обязан содержать подстановки, от которых зависит ответ (входные данные и параметры, влияющие на ответ), поэтому условие всегда показывает вход. Пакет проверяется полностью при импорте, с пробными подстановками на наименьших значениях параметров и, по восемь seed каждая, на наибольших значениях (самые большие входы) и на выбранных значениях, поэтому шаблон у границы размера не пройдет из-за одного удачного seed; чтение сохраненной строки проб не повторяет, потому что хеш содержимого доказывает, что это то самое содержимое, которое их прошло. Названия, шаблоны и тексты рубрики отклоняют управляющие символы, символы формата Unicode (например, переопределения направления текста) и разделители строки и абзаца U+2028 и U+2029; CHECK-ограничение названия отклоняет самые распространенные из них.
|
||||
- Рубрика. Рубрика содержит принцип и список критериев. В ней нет баллов, весов и проходного порога; как критерии превращаются в грейд, банк не решает.
|
||||
- Жизненный цикл и загрузчик. `Bank.ImportBundle` сохраняет все семейства пакета как черновики в одной транзакции и никогда не публикует, что бы ни говорила рецензия; повторный импорт того же пакета, в том числе одновременный, сообщает версии как неизмененные. `Bank.PublishFamily` и `Bank.RetireFamily` принимают оператора и отказывают с причиной (`reviewer_missing`, `review_not_approved`, `not_draft`, `not_published`, `newer_version_published`); отказ - это `*domain.AssessmentRefusalError` с причиной, а sentinel-ошибки гонки, которую решила база (шаг жизненного цикла проиграл другому, нет одобренной рецензии, недостаточное покрытие), становятся теми же отказами. Публикация, вывод из обращения и открытие сначала берут транзакционную advisory-блокировку категории, поэтому выполняются по очереди в пределах категории; `LockCategory` работает только внутри транзакции (репозиторий единицы работы берет блокировку, автономное хранилище возвращает `ErrAssessmentLockOutsideTransaction`).
|
||||
|
||||
@@ -183,7 +183,7 @@ goose выполняет каждую миграцию в отдельной т
|
||||
|
||||
### Банк заданий оценки
|
||||
|
||||
Миграция `00011_create_assessment_bank.sql` создает `assessment_families` (неизменяемые версии семейств) и `assessment_category_openings`; запросы лежат в `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` доступен через `UnitOfWork.AssessmentBank()` и через `postgres.AssessmentBankStore` вне транзакции; `assessment.Bank` импортирует `Bundle`, публикует версию от имени оператора (выводя из обращения опубликованную более старую), выводит ее из обращения, открывает категорию под действующей версией политики, сообщает живую доступность и генерирует вариант по seed. Чтобы изменить семейство, импортируйте новую версию; сохраненная версия не редактируется, а черновик `pending` одобряется импортом новой версии с рецензией. Новый алгоритм seed получает новое версионное имя в `domain/assessment_algorithms.go`, обязательные подстановки, тест решателя с посчитанными вручную случаями и golden-тест; зарегистрированный алгоритм не меняйте. Шаблоны условий - обычный текст только с подстановками `{{.name}}`. Демонстрационный пакет в `backend/testdata/assessment/` - непроверенный черновик ИИ: не заполняйте в нем рецензента, чтобы открыть категорию. См. [ARCHITECTURE.md](ARCHITECTURE.md#банк-заданий-оценки).
|
||||
Миграция `00011_create_assessment_bank.sql` создает `assessment_families` (неизменяемые версии семейств) и `assessment_category_openings`; запросы лежат в `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` доступен через `UnitOfWork.AssessmentBank()` и через `postgres.AssessmentBankStore` вне транзакции; `assessment.Bank` импортирует `Bundle`, публикует версию от имени оператора (выводя из обращения опубликованную более старую), выводит ее из обращения, открывает категорию под действующей версией политики, сообщает живую доступность и генерирует вариант по seed. Чтобы изменить семейство, импортируйте новую версию; сохраненная версия не редактируется, а черновик `pending` одобряется импортом новой версии с рецензией. Новый алгоритм seed получает новое версионное имя в `domain/assessment_algorithms.go`, обязательные подстановки, тест решателя с посчитанными вручную случаями и golden-тест; зарегистрированный алгоритм не меняйте. Алгоритм с форматом ответа `choice` задает `generateChoice` вместо `generate` и возвращает правильное значение вместе с неверными значениями именованных моделей ошибок (пример - `lru_hits_choice.v1`); его тесты пересчитывают модели ошибок по условию. Демонстрационный пакет в `backend/testdata/assessment/` - непроверенный черновик ИИ: не заполняйте в нем рецензента, чтобы открыть категорию. См. [ARCHITECTURE.md](ARCHITECTURE.md#банк-заданий-оценки).
|
||||
|
||||
### Relay outbox
|
||||
|
||||
|
||||
+2
-1
@@ -498,7 +498,7 @@ Spec не проверяет запланированные переходы б
|
||||
|
||||
## Тесты банка заданий
|
||||
|
||||
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go` и `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) проверяют без базы: отклоняется некорректное содержимое семейства (правила рецензии, неизвестный алгоритм, границы параметров, несоответствие формата ответа, форма рубрики, символы формата Unicode); шаблоны условий принимают только текст и подстановки `{{.name}}`, а бомба из вложенных `define`, бомба ширины `printf`, `range` по числу и рекурсивный `block` отклоняются быстрее секунды и не запускаются; шаблон без подстановок, от которых зависит ответ, отклоняется; размер готового условия ограничен; измененный сохраненный документ не проходит проверку хеша; каждый отказ в публикации называет причину; один seed дает один вариант, а рубрика одинакова для всех seed; golden-тесты фиксируют точное условие и эталонный ответ для заданного seed у каждого из четырех алгоритмов и хеш содержимого схемы 1 для заданного входа; строка проверяется схемой хеша, с которой она сохранена (тест регистрирует вторую схему, а хеш одной схемы под именем другой и неизвестная схема отклоняются); шаблон, чье условие достигает границы размера только для одного пробного seed, отклоняется при импорте, потому что наибольшие значения параметров подставляются для восьми seed; разделители строки и абзаца отклоняются как символы формата; четыре решателя совпадают с посчитанными вручную случаями; покрытие для открытия равно `max_scored_items` плюс `seed_items` политики; демонстрационный пакет читается как черновик ИИ с рецензией `pending` и без рецензента. С in-memory подделками репозитория и единицы работы usecase-тесты доказывают: одновременный идентичный импорт сообщает версию как неизмененную, а одновременный импорт с другим содержимым отклоняется; sentinel-ошибки гонок базы становятся отказами с подходящей причиной; публикация после взятия блокировки категории выводит из обращения более старую опубликованную версию и отклоняется, если опубликована более новая; открытие требует действующую версию политики; доступность отклоняется, когда число опубликованных семейств падает ниже требования открытия или когда версия политики открытия больше не действует; более старый одобренный черновик отклоняется, пока существует более новая версия: черновик, опубликованная или выведенная из обращения. `internal/adapter/secondary/postgres/assessment_bank_test.go` проверяет, что ограничения банка преобразуются в свои sentinel-ошибки без строки с нарушением, что страница списка вне предела падает до любого запроса и что блокировка категории отклоняется вне транзакции.
|
||||
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go` и `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) проверяют без базы: отклоняется некорректное содержимое семейства (правила рецензии, неизвестный алгоритм, границы параметров, несоответствие формата ответа, форма рубрики, символы формата Unicode); шаблоны условий принимают только текст и подстановки `{{.name}}`, а бомба из вложенных `define`, бомба ширины `printf`, `range` по числу и рекурсивный `block` отклоняются быстрее секунды и не запускаются; шаблон без подстановок, от которых зависит ответ, отклоняется; размер готового условия ограничен; измененный сохраненный документ не проходит проверку хеша; каждый отказ в публикации называет причину; один seed дает один вариант, а рубрика одинакова для всех seed; golden-тесты фиксируют точное условие и эталонный ответ для заданного seed у каждого из четырех алгоритмов и хеш содержимого схемы 1 для заданного входа; строка проверяется схемой хеша, с которой она сохранена (тест регистрирует вторую схему, а хеш одной схемы под именем другой и неизвестная схема отклоняются); шаблон, чье условие достигает границы размера только для одного пробного seed, отклоняется при импорте, потому что наибольшие значения параметров подставляются для восьми seed; разделители строки и абзаца отклоняются как символы формата; четыре решателя совпадают с посчитанными вручную случаями; покрытие для открытия равно `max_scored_items` плюс `seed_items` политики; демонстрационный пакет читается как черновик ИИ с рецензией `pending` и без рецензента. `assessment_choice_test.go` проверяет формат с выбором без базы: один seed дает одинаковые варианты, ID и порядок, а по 400 seed правильный вариант встречается на каждой позиции; каждый отвлекающий вариант `lru_hits_choice.v1` пересчитывается по условию как результат именованной модели ошибки (а добор соседними значениями используется, только если модели дали меньше трех различных значений), варианты не повторяют текст, модели кэша совпадают с посчитанными вручную случаями, а модель LRU равна решателю `lru_hits.v1`, golden-тест фиксирует варианты, их ID и ключ одного seed; правильный вариант, неверный вариант, вариант чужого задания, два варианта, числовой ответ на задание с выбором и ответ с выбором на целочисленное задание оцениваются или отклоняются, как описано, проекция для кандидата содержит только непрозрачные ID и тексты, а поврежденный ключ или повторяющийся вариант замороженного варианта отклоняются.
|
||||
|
||||
`TestAssessmentBank` в `backend/integration_test/assessment_bank_test.go` использует `bootstrap(t, postgresService)` и дает каждому случаю свою мигрированную базу:
|
||||
|
||||
@@ -510,6 +510,7 @@ Spec не проверяет запланированные переходы б
|
||||
- Публикация более поздней версии семейства выводит из обращения опубликованную более старую и записывает обоих операторов; публикация более старой версии при опубликованной более новой отклоняется; таблица допускает одну опубликованную версию на семейство и отклоняет перезапись записанного публикатора.
|
||||
- Транзакция, держащая блокировку категории, заставляет открытие ждать до срока, а после освобождения блокировки открытие проходит.
|
||||
- Более старый одобренный черновик нельзя опубликовать, когда существует более новая версия, в том числе выведенная из обращения. Проверки действующей политики используют часы базы данных, без сдвига часов в тесте.
|
||||
- `TestAssessmentChoiceFamiliesAreServedAndGradedOverHTTP` в `backend/integration_test/assessment_choice_http_test.go` проходит настоящую попытку по банку из алгоритма с выбором и целочисленного алгоритма: каждое задание, которое получает кандидат, содержит только разрешенные поля (для выбора - ID и тексты вариантов в сохраненном порядке, без поля ключа, seed или отвлекающего варианта), вариант чужого задания и два варианта отклоняются с 400, неверный выбор не дает баллов, а верный дает их по ключу, результат совпадает с ожидаемым числом баллов, и каждый ответ оставил наблюдение сигналов.
|
||||
- Сырые строки политики, в документе которых нет границ оцениваемых заданий, они заданы текстом, слишком большим, дробным или отрицательным числом или нет seed-заданий, отклоняются триггером открытия отказом по порогам, а не ошибкой приведения типа; сохраненная схема хеша вне списка CHECK отклоняется, а саму схему изменить нельзя.
|
||||
- В обход usecase таблица отклоняет открытие с заниженным требованием, открытие ниже покрытия, открытие под неизвестной версией политики и название с переопределением направления текста.
|
||||
- Семейства выводятся страницами по две после курсора, каждое один раз и по порядку.
|
||||
|
||||
Reference in new issue
Block a user