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

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

No files matched your search

@@ -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())
}
}
}