feat(assessment): add table families that pick a variant row by seed

This commit is contained in:
shira committed 2026-10-11 08:19:17 +03:00
1 parent f1147b1885
commit 5e1db37746
16 files changed
+1023 -56

No files matched your search

@@ -0,0 +1,37 @@
-- +goose Up
-- Content hash scheme 2 is the layout of a table generator: a family whose
-- variants are rows of a table, with the answers written in the rows. A new
-- version of such a family is stored with scheme 2. Scheme 1 stays the layout
-- of an algorithmic generator, so existing rows and the hash of every
-- algorithmic version are unchanged, and importing one of them again is still
-- recognized as the same version.
--
-- Only the list of known schemes changes. hash_scheme stays one of the
-- immutable columns that the guard trigger protects.
ALTER TABLE assessment_families
DROP CONSTRAINT assessment_families_hash_scheme_known,
ADD CONSTRAINT assessment_families_hash_scheme_known CHECK (
hash_scheme IN (1, 2)
);
-- +goose Down
-- A stored version never changes and is never removed, so a row of scheme 2
-- cannot be given another scheme. The down step refuses while one exists.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM assessment_families WHERE hash_scheme = 2) THEN
RAISE EXCEPTION USING
ERRCODE = 'object_not_in_prerequisite_state',
MESSAGE = 'table generator families are stored',
HINT = 'A stored family version cannot be removed or rehashed; keep migration 00047 applied.';
END IF;
END
$$;
-- +goose StatementEnd
ALTER TABLE assessment_families
DROP CONSTRAINT assessment_families_hash_scheme_known,
ADD CONSTRAINT assessment_families_hash_scheme_known CHECK (
hash_scheme IN (1)
);
@@ -478,6 +478,51 @@ func TestAssessmentBank(t *testing.T) {
assertPgError(t, "unknown hash scheme", err, assessmentCheckSQLState, "assessment_families_hash_scheme_known")
})
t.Run("a table family is stored with hash scheme 2 and imports again unchanged", func(t *testing.T) {
fixture := newFixture(t)
bundle := fixture.demoBundle
bundle.Name = "table-family-bundle"
bundle.Families = choiceTableBankFamilies(t, bundle.Families[0])
first, err := fixture.bank.ImportBundle(ctx, bundle)
if err != nil || len(first.Created) != 3 || len(first.Unchanged) != 0 {
t.Fatalf("ImportBundle(table bundle) = %+v, %v, want three created versions", first, err)
}
fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE hash_scheme = 2`, 2)
fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE hash_scheme = 1`, 1)
again, err := fixture.bank.ImportBundle(ctx, bundle)
if err != nil || len(again.Created) != 0 || len(again.Unchanged) != 3 {
t.Fatalf("ImportBundle(table bundle again) = %+v, %v, want three unchanged versions", again, err)
}
// The stored row is verified with its own scheme when it is read, and
// the same seed gives the same variant from it.
for _, family := range bundle.Families {
key := domain.AssessmentFamilyKey(family.Key)
stored, err := fixture.store.AssessmentBank().GetFamilyVersion(ctx, key, 1)
if err != nil {
t.Fatalf("GetFamilyVersion(%s) error = %v", key, err)
}
wantScheme := int16(2)
if family.SeedGenerator.Table == nil {
wantScheme = 1
}
if stored.HashScheme() != wantScheme {
t.Fatalf("family %s scheme = %d, want %d", key, stored.HashScheme(), wantScheme)
}
one, err := fixture.bank.GenerateVariant(ctx, key, 1, 77)
if err != nil {
t.Fatalf("GenerateVariant(%s) error = %v", key, err)
}
two, err := fixture.bank.GenerateVariant(ctx, key, 1, 77)
if err != nil || one.Statement != two.Statement || one.ReferenceAnswer != two.ReferenceAnswer || !slices.Equal(one.Options, two.Options) {
t.Fatalf("GenerateVariant(%s) twice = %+v and %+v (%v), want one variant", key, one, two, err)
}
}
// A table row edited in the database fails the hash, whatever the edit
// path: the trigger refuses the edit, and the row stays as imported.
_, err = fixture.pool.Exec(ctx, `UPDATE assessment_families SET seed_generator = replace(seed_generator::text, '"404"', '"405"')::jsonb WHERE hash_scheme = 2`)
assertPgError(t, "edit a table", err, assessmentIntegritySQLState, "assessment_families_immutable")
})
t.Run("families are listed in pages after a cursor", func(t *testing.T) {
fixture := newFixture(t)
bundle := fixture.reviewedBundle(5)
@@ -17,11 +17,11 @@ import (
"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 {
// choiceTableBankFamilies returns the families of a bank that offers every new
// answer format: a choice family whose distractors come from error models, a
// table family with integer answers, and a table family with choice answers.
// They reuse the rubric and the identity of the first demo family.
func choiceTableBankFamilies(t *testing.T, base assessment.BundleFamily) []assessment.BundleFamily {
t.Helper()
choice := base
choice.Key = "choice-lru-hits"
@@ -33,7 +33,32 @@ func choiceBankFamilies(t *testing.T, base assessment.BundleFamily) []assessment
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}
integerTable := base
integerTable.Key = "table-integer-limits"
integerTable.SeedGenerator = domain.AssessmentSeedGenerator{
StatementTemplate: "A pool opens {{.connections}} connections at most and each request holds one for {{.seconds}} seconds. How many requests per minute can it serve at most?",
Table: &domain.AssessmentVariantTable{Rows: []domain.AssessmentVariantRow{
{Values: map[string]string{"connections": "10", "seconds": "2"}, Answer: "300"},
{Values: map[string]string{"connections": "4", "seconds": "3"}, Answer: "80"},
{Values: map[string]string{"connections": "6", "seconds": "5"}, Answer: "72"},
{Values: map[string]string{"connections": "20", "seconds": "1"}, Answer: "1200"},
}},
}
integerTable.AnswerKey = domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatInteger, ReferenceSolution: "Multiply by sixty and divide by the hold time."}
choiceTable := base
choiceTable.Key = "table-choice-status"
choiceTable.SeedGenerator = domain.AssessmentSeedGenerator{
StatementTemplate: "Which status code does an API return for {{.situation}}?",
Table: &domain.AssessmentVariantTable{Rows: []domain.AssessmentVariantRow{
{Values: map[string]string{"situation": "a resource that does not exist"}, Answer: "404", Distractors: []string{"400", "410", "500"}},
{Values: map[string]string{"situation": "a call without credentials"}, Answer: "401", Distractors: []string{"403", "407", "511"}},
{Values: map[string]string{"situation": "an update on a stale version"}, Answer: "412", Distractors: []string{"409", "422", "428"}},
}},
}
choiceTable.AnswerKey = domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatChoice, ReferenceSolution: "Match the situation to the status code."}
return []assessment.BundleFamily{choice, integerTable, choiceTable}
}
// allowedItemKeys are the fields that a candidate item may carry per format.
@@ -42,7 +67,7 @@ var allowedItemContentKeys = map[string][]string{
"choice": {"format", "multiple", "options"},
}
func TestAssessmentChoiceFamiliesAreServedAndGradedOverHTTP(t *testing.T) {
func TestAssessmentChoiceAndTableFamiliesAreServedAndGradedOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
defer cancel()
@@ -53,9 +78,18 @@ func TestAssessmentChoiceFamiliesAreServedAndGradedOverHTTP(t *testing.T) {
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
source := loadDemoBundleFile(t)
source.Families = choiceBankFamilies(t, source.Families[0])
source.Families = choiceTableBankFamilies(t, source.Families[0])
seedAssessmentAttemptHTTPBankFrom(ctx, t, harness.pool, nil, source)
// The bank holds both kinds of generator: the table families are stored
// with hash scheme 2 and the algorithmic family with scheme 1.
for scheme, want := range map[int]bool{1: true, 2: true} {
var stored int
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_families WHERE hash_scheme = $1`, scheme).Scan(&stored); err != nil || (stored > 0) != want {
t.Fatalf("families with hash scheme %d = %d, %v, want some", scheme, stored, err)
}
}
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
+97 -25
View File
@@ -239,7 +239,7 @@ func ParseAssessmentLifecycle(value string) (AssessmentLifecycle, error) {
type AssessmentAnswerKey struct {
// AnswerFormat is the format of the reference answer: "integer",
// "integer_sequence", or "choice". It must match the algorithm of the
// generator.
// generator; a table generator takes "integer" or "choice".
AnswerFormat string `json:"answer_format"`
// ReferenceSolution describes the reference approach in prose.
ReferenceSolution string `json:"reference_solution"`
@@ -289,9 +289,11 @@ func (rubric AssessmentRubric) validate(location string) error {
return nil
}
func (key AssessmentAnswerKey) validate(location string, algorithm assessmentAlgorithm) error {
if key.AnswerFormat != algorithm.answerFormat {
return invalidAssessmentFamily(location, "answer format does not match the answer format of the generator algorithm")
// validate checks the answer key against the answer format that the
// generator produces.
func (key AssessmentAnswerKey) validate(location, generatorFormat string) error {
if key.AnswerFormat != generatorFormat {
return invalidAssessmentFamily(location, "answer format does not match the answer format of the generator")
}
return checkAssessmentText(location, "reference solution", key.ReferenceSolution)
}
@@ -379,16 +381,33 @@ func (core AssessmentFamilyCore) validate(location string, probe bool) error {
if err := core.validateReview(location); err != nil {
return err
}
algorithm, err := core.Generator.validate(location, probe)
generatorFormat, err := core.validateGenerator(location, probe)
if err != nil {
return err
}
if err := core.AnswerKey.validate(location, algorithm); err != nil {
if err := core.AnswerKey.validate(location, generatorFormat); err != nil {
return err
}
return core.Rubric.validate(location)
}
// validateGenerator validates the generator of either kind and returns the
// answer format that it produces. A table generator produces the format its
// answer key declares, after the table has been checked against it.
func (core AssessmentFamilyCore) validateGenerator(location string, probe bool) (string, error) {
if core.Generator.Table != nil {
if err := core.Generator.validateTable(location, core.AnswerKey.AnswerFormat, probe); err != nil {
return "", err
}
return core.AnswerKey.AnswerFormat, nil
}
algorithm, err := core.Generator.validate(location, probe)
if err != nil {
return "", err
}
return algorithm.answerFormat, nil
}
func (core AssessmentFamilyCore) validateReview(location string) error {
if _, err := ParseAssessmentReviewStatus(string(core.ReviewStatus)); err != nil {
return fmt.Errorf("%s - validate review status: %w", location, err)
@@ -408,25 +427,58 @@ func (core AssessmentFamilyCore) validateReview(location string) error {
return nil
}
// currentAssessmentHashScheme is the scheme that new versions are stored
// with. A stored row keeps its own scheme in the hash_scheme column, and
// RestoreAssessmentFamily verifies it with that scheme's function, so a later
// scheme verifies new rows without invalidating the old ones. A change of the
// canonical layout, of a field, or of the encoding adds a scheme here and to
// the assessment_families_hash_scheme_known CHECK; it never edits the
// function of an existing scheme.
const currentAssessmentHashScheme int16 = 1
// The hash schemes of family content. A stored row keeps its own scheme in
// the hash_scheme column, and RestoreAssessmentFamily verifies it with that
// scheme's function, so a later scheme verifies new rows without invalidating
// the old ones. A change of the canonical layout, of a field, or of the
// encoding adds a scheme here and to the assessment_families_hash_scheme_known
// CHECK; it never edits the function of an existing scheme.
//
// Scheme 1 hashes the layout of an algorithmic generator. Scheme 2 is the
// layout of a table generator, whose canonical content holds the table instead
// of an algorithm and its parameters. A new version gets the scheme of its
// generator kind, so the content of an algorithmic family keeps the hash it
// had before table generators existed, and importing it again is still
// recognized as the same version.
const (
assessmentHashSchemeAlgorithmic int16 = 1
assessmentHashSchemeTable int16 = 2
)
// hashScheme is the scheme that a new version of this content is stored with.
func (core AssessmentFamilyCore) hashScheme() int16 {
if core.Generator.Table != nil {
return assessmentHashSchemeTable
}
return assessmentHashSchemeAlgorithmic
}
// assessmentHashSchemes maps a scheme number to its hash function. It is a
// variable only so that a test can register a scheme.
var assessmentHashSchemes = map[int16]func(AssessmentFamilyCore) (AssessmentContentHash, error){
1: contentHashV1,
assessmentHashSchemeAlgorithmic: contentHashV1,
assessmentHashSchemeTable: contentHashV2,
}
// assessmentCanonicalContentV1 is the form that scheme 1 hashes. The bundle
// name, the ID, and the lifecycle are not part of it: they are provenance and
// state, not content.
type assessmentCanonicalContentV1 struct {
// assessmentCanonicalGeneratorV1 is the generator layout of scheme 1. It is a
// type of its own, so that a later field of AssessmentSeedGenerator cannot
// change what scheme 1 hashes.
type assessmentCanonicalGeneratorV1 struct {
Algorithm string `json:"algorithm"`
Parameters map[string]AssessmentParameterRange `json:"parameters"`
StatementTemplate string `json:"statement_template"`
}
// assessmentCanonicalGeneratorV2 is the generator layout of scheme 2.
type assessmentCanonicalGeneratorV2 struct {
StatementTemplate string `json:"statement_template"`
Table *AssessmentVariantTable `json:"table"`
}
// assessmentCanonicalContent is the form that the schemes hash, with the
// generator layout of the scheme. The bundle name, the ID, and the lifecycle
// are not part of it: they are provenance and state, not content.
type assessmentCanonicalContent[Generator any] struct {
Key AssessmentFamilyKey `json:"family_key"`
Version int32 `json:"version"`
Category AssessmentCategory `json:"category"`
@@ -435,7 +487,7 @@ type assessmentCanonicalContentV1 struct {
Author AssessmentAuthor `json:"author"`
Reviewer AssessmentOperator `json:"reviewer,omitempty"`
ReviewStatus AssessmentReviewStatus `json:"review_status"`
Generator AssessmentSeedGenerator `json:"seed_generator"`
Generator Generator `json:"seed_generator"`
AnswerKey AssessmentAnswerKey `json:"answer_key"`
Rubric AssessmentRubric `json:"rubric"`
}
@@ -454,13 +506,32 @@ func (core AssessmentFamilyCore) contentHash(scheme int16) (AssessmentContentHas
}
func contentHashV1(core AssessmentFamilyCore) (AssessmentContentHash, error) {
encoded, err := json.Marshal(assessmentCanonicalContentV1{
if core.Generator.Table != nil {
return AssessmentContentHash{}, invalidAssessmentFamily("domain.contentHashV1", "scheme 1 does not cover a table generator")
}
return hashCanonicalContent("domain.contentHashV1", core, assessmentCanonicalGeneratorV1{
Algorithm: core.Generator.Algorithm, Parameters: core.Generator.Parameters,
StatementTemplate: core.Generator.StatementTemplate,
})
}
func contentHashV2(core AssessmentFamilyCore) (AssessmentContentHash, error) {
if core.Generator.Table == nil || core.Generator.Algorithm != "" || len(core.Generator.Parameters) != 0 {
return AssessmentContentHash{}, invalidAssessmentFamily("domain.contentHashV2", "scheme 2 covers only a table generator")
}
return hashCanonicalContent("domain.contentHashV2", core, assessmentCanonicalGeneratorV2{
StatementTemplate: core.Generator.StatementTemplate, Table: core.Generator.Table,
})
}
func hashCanonicalContent[Generator any](location string, core AssessmentFamilyCore, generator Generator) (AssessmentContentHash, error) {
encoded, err := json.Marshal(assessmentCanonicalContent[Generator]{
Key: core.Key, Version: core.Version, Category: core.Category, Specialization: core.Specialization,
Title: core.Title, Author: core.Author, Reviewer: core.Reviewer, ReviewStatus: core.ReviewStatus,
Generator: core.Generator, AnswerKey: core.AnswerKey, Rubric: core.Rubric,
Generator: generator, AnswerKey: core.AnswerKey, Rubric: core.Rubric,
})
if err != nil {
return AssessmentContentHash{}, fmt.Errorf("domain.contentHashV1 - encode canonical content: %w", err)
return AssessmentContentHash{}, fmt.Errorf("%s - encode canonical content: %w", location, err)
}
return sha256.Sum256(encoded), nil
}
@@ -483,7 +554,8 @@ func NewAssessmentFamilyDraft(input NewAssessmentFamilyDraftInput) (AssessmentFa
if err := core.validate(location, true); err != nil {
return AssessmentFamilyDraft{}, err
}
hash, err := core.contentHash(currentAssessmentHashScheme)
scheme := core.hashScheme()
hash, err := core.contentHash(scheme)
if err != nil {
return AssessmentFamilyDraft{}, err
}
@@ -491,7 +563,7 @@ func NewAssessmentFamilyDraft(input NewAssessmentFamilyDraftInput) (AssessmentFa
if err != nil {
return AssessmentFamilyDraft{}, fmt.Errorf("%s - assign ID: %w", location, err)
}
return AssessmentFamilyDraft{id: id, core: core, hash: hash, scheme: currentAssessmentHashScheme}, nil
return AssessmentFamilyDraft{id: id, core: core, hash: hash, scheme: scheme}, nil
}
func (draft AssessmentFamilyDraft) ID() AssessmentFamilyID { return draft.id }
@@ -314,7 +314,9 @@ func TestNewAssessmentCategoryOpeningDraftReadsCoverageFromThePolicy(t *testing.
// A row is verified with the scheme it was stored with, so adding a scheme
// later does not invalidate old rows or accept a hash of the wrong scheme.
func TestRestoreVerifiesARowWithItsOwnHashScheme(t *testing.T) {
const testScheme int16 = 2
// A number that no real scheme uses, so that the registration cannot
// shadow one.
const testScheme int16 = 8
assessmentHashSchemes[testScheme] = func(core AssessmentFamilyCore) (AssessmentContentHash, error) {
hash, err := contentHashV1(core)
hash[0] ^= 0xff // a different function of the same content
@@ -326,8 +328,8 @@ func TestRestoreVerifiesARowWithItsOwnHashScheme(t *testing.T) {
if err != nil {
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
}
if draft.HashScheme() != currentAssessmentHashScheme {
t.Fatalf("draft scheme = %d, want the current scheme %d", draft.HashScheme(), currentAssessmentHashScheme)
if draft.HashScheme() != assessmentHashSchemeAlgorithmic {
t.Fatalf("draft scheme = %d, want the algorithmic scheme %d", draft.HashScheme(), assessmentHashSchemeAlgorithmic)
}
old := storedAssessmentFrom(t, draft)
if family, err := RestoreAssessmentFamily(old); err != nil || family.HashScheme() != 1 {
@@ -337,18 +339,18 @@ func TestRestoreVerifiesARowWithItsOwnHashScheme(t *testing.T) {
core := draft.Core()
newer, err := core.contentHash(testScheme)
if err != nil {
t.Fatalf("contentHash(scheme 2) error = %v", err)
t.Fatalf("contentHash(test scheme) error = %v", err)
}
row := old
row.HashScheme, row.ContentHash = testScheme, newer[:]
if family, err := RestoreAssessmentFamily(row); err != nil || family.HashScheme() != testScheme {
t.Fatalf("RestoreAssessmentFamily(scheme 2 row) = scheme %d, %v, want a verified row of scheme 2", family.HashScheme(), err)
t.Fatalf("RestoreAssessmentFamily(test scheme row) = scheme %d, %v, want a verified row of the test scheme", family.HashScheme(), err)
}
// The hash of one scheme under the name of the other, and an unknown
// scheme, are refused.
row.ContentHash = old.ContentHash
if _, err := RestoreAssessmentFamily(row); !errors.Is(err, ErrAssessmentFamilyIntegrity) {
t.Fatalf("RestoreAssessmentFamily(scheme 1 hash under scheme 2) error = %v, want ErrAssessmentFamilyIntegrity", err)
t.Fatalf("RestoreAssessmentFamily(scheme 1 hash under the test scheme) error = %v, want ErrAssessmentFamilyIntegrity", err)
}
row.HashScheme = 9
if _, err := RestoreAssessmentFamily(row); !errors.Is(err, ErrInvalidAssessmentFamily) {
@@ -36,23 +36,30 @@ type AssessmentParameterRange struct {
Max int32 `json:"max"`
}
// AssessmentSeedGenerator describes how seeds become variants: a named
// algorithm, the ranges of its parameters, and the statement template. The
// algorithm is code that is registered in this package under a versioned
// name, so an old family version keeps its algorithm after a newer one
// exists.
// AssessmentSeedGenerator describes how seeds become variants. There are two
// kinds. An algorithmic generator names an algorithm, the ranges of its
// parameters, and the statement template; the algorithm is code that is
// registered in this package under a versioned name, so an old family version
// keeps its algorithm after a newer one exists. A table generator holds the
// variants themselves as rows with their answers and the statement template;
// the seed selects a row and no code computes the answer. A table generator
// has no algorithm and no parameters.
type AssessmentSeedGenerator struct {
Algorithm string `json:"algorithm"`
Parameters map[string]AssessmentParameterRange `json:"parameters"`
Algorithm string `json:"algorithm,omitempty"`
Parameters map[string]AssessmentParameterRange `json:"parameters,omitempty"`
// StatementTemplate is plain text with {{.name}} placeholders for the
// parameters and the generated input data of the algorithm. Nothing else
// of the text/template language is accepted; see compileStatementTemplate.
// parameters and the generated input data of the algorithm, or for the
// columns of the table. Nothing else of the text/template language is
// accepted; see compileStatementTemplate.
StatementTemplate string `json:"statement_template"`
// Table is set for a table generator and nil for an algorithmic one.
Table *AssessmentVariantTable `json:"table,omitempty"`
}
func (generator AssessmentSeedGenerator) clone() AssessmentSeedGenerator {
copied := generator
copied.Parameters = maps.Clone(generator.Parameters)
copied.Table = generator.Table.clone()
return copied
}
@@ -63,6 +70,9 @@ func (generator AssessmentSeedGenerator) clone() AssessmentSeedGenerator {
// proves that the content is the one that passed them. It returns the
// algorithm.
func (generator AssessmentSeedGenerator) validate(location string, probe bool) (assessmentAlgorithm, error) {
if generator.Table != nil {
return assessmentAlgorithm{}, invalidAssessmentFamily(location, "a table generator has no algorithm")
}
algorithm, ok := assessmentAlgorithms[generator.Algorithm]
if !ok {
return assessmentAlgorithm{}, invalidAssessmentFamily(location, "generator algorithm is unknown")
@@ -187,6 +197,9 @@ func (family AssessmentFamily) NewVariant(seed VariantSeed) (AssessmentVariant,
if family.IsZero() {
return AssessmentVariant{}, invalidAssessmentFamily(location, "family was not built by RestoreAssessmentFamily")
}
if family.core.Generator.Table != nil {
return family.newTableVariant(seed)
}
algorithm, ok := assessmentAlgorithms[family.core.Generator.Algorithm]
if !ok {
return AssessmentVariant{}, invalidAssessmentFamily(location, "generator algorithm is unknown")
+261
View File
@@ -0,0 +1,261 @@
package domain
import (
"fmt"
"maps"
"regexp"
"slices"
"strconv"
"strings"
)
const (
// minTableRows: a table with one row is a fixed task, not a generator.
minTableRows = 2
// maxTableRows, maxTableColumns, maxTableValueBytes, and maxTableBytes
// bound a table. The attempt service reads every published family of a
// category when it starts an attempt, so a table stays small; a family
// that needs more variants is a Go algorithm.
maxTableRows = 500
maxTableColumns = 16
maxTableValueBytes = 1000
maxTableBytes = 64 << 10
// tableSelectionName separates the seed derivation of table rows from
// that of every algorithm. The selection is part of what stored table
// families depend on, so a different rule would be a new name.
tableSelectionName = "table.v1"
)
var (
assessmentTableColumnPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,31}$`)
// assessmentTableIntegerPattern is a canonical decimal integer of at most
// 15 digits, which a JSON number carries exactly.
assessmentTableIntegerPattern = regexp.MustCompile(`^(0|-?[1-9][0-9]{0,14})$`)
)
// AssessmentVariantTable is the declarative variant source of a table
// generator: a table of rows, each with the placeholder values of the
// statement template and the answer. It is data, never code: the seed selects
// a row, the statement template substitutes its values, and the answer is the
// one written in the row. Nothing is computed from the table.
type AssessmentVariantTable struct {
Rows []AssessmentVariantRow `json:"rows"`
}
// AssessmentVariantRow is one variant of a table.
type AssessmentVariantRow struct {
// Values maps each column, that is, each placeholder of the statement
// template, to the text that replaces it. Every row has the same columns.
Values map[string]string `json:"values"`
// Answer is the reference answer: a canonical decimal integer for the
// answer format integer, and the text of the correct option for choice.
Answer string `json:"answer"`
// Distractors are the wrong options of a choice row. A row of any other
// format has none.
Distractors []string `json:"distractors,omitempty"`
}
func (table *AssessmentVariantTable) clone() *AssessmentVariantTable {
if table == nil {
return nil
}
copied := &AssessmentVariantTable{Rows: make([]AssessmentVariantRow, len(table.Rows))}
for index, row := range table.Rows {
copied.Rows[index] = AssessmentVariantRow{
Values: maps.Clone(row.Values), Answer: row.Answer, Distractors: slices.Clone(row.Distractors),
}
}
return copied
}
// columns returns the column names of the table, which are the names of the
// first row, in sorted order.
func (table *AssessmentVariantTable) columns() []string {
if table == nil || len(table.Rows) == 0 {
return nil
}
return slices.Sorted(maps.Keys(table.Rows[0].Values))
}
// tableAlgorithm describes the placeholders of a table to the statement
// template compiler: every column is a known placeholder, and every column
// must appear in the statement, because a hidden column would make rows that
// differ only there indistinguishable to the candidate.
func tableAlgorithm(columns []string) assessmentAlgorithm {
return assessmentAlgorithm{dataNames: columns, requiredNames: columns}
}
// validateTable checks a table generator against the answer format of the
// family. Every failure that belongs to a row names the row by its index in
// the rows array, counted from zero, and never quotes the content. With
// probe set it also renders the statement of every row, which an importer
// does and the read of a stored row does not, because the content hash
// proves that the content is the one that passed.
func (generator AssessmentSeedGenerator) validateTable(location, answerFormat string, probe bool) error {
table := generator.Table
if generator.Algorithm != "" || len(generator.Parameters) != 0 {
return invalidAssessmentFamily(location, "a table generator has no algorithm and no parameters")
}
if answerFormat != AnswerFormatInteger && answerFormat != AnswerFormatChoice {
return invalidAssessmentFamily(location, "table answer format must be integer or choice")
}
if len(table.Rows) < minTableRows || len(table.Rows) > maxTableRows {
return invalidAssessmentFamily(location, fmt.Sprintf("table must have %d to %d rows", minTableRows, maxTableRows))
}
columns := table.columns()
if len(columns) == 0 || len(columns) > maxTableColumns {
return invalidAssessmentFamily(location, fmt.Sprintf("table rows[0] must have 1 to %d columns", maxTableColumns))
}
for _, column := range columns {
if !assessmentTableColumnPattern.MatchString(column) {
return invalidAssessmentFamily(location, "table column names must be 1 to 32 lowercase letters, digits, or '_', starting with a letter")
}
}
statement, err := compileStatementTemplate(location, generator.StatementTemplate, tableAlgorithm(columns))
if err != nil {
return err
}
return validateTableRows(location, table, columns, statement, answerFormat, probe)
}
func validateTableRows(
location string,
table *AssessmentVariantTable,
columns []string,
statement statementTemplate,
answerFormat string,
probe bool,
) error {
firstRowOf := make(map[string]int, len(table.Rows))
totalBytes := 0
for index, row := range table.Rows {
rowLocation := fmt.Sprintf("%s - table rows[%d]", location, index)
if len(row.Values) != len(columns) {
return invalidAssessmentFamily(rowLocation, "values must have exactly the columns of rows[0]")
}
var identity strings.Builder
for _, column := range columns {
value, ok := row.Values[column]
if !ok {
return invalidAssessmentFamily(rowLocation, "values must have exactly the columns of rows[0]")
}
if err := checkTableValue(rowLocation, "value of column "+column, value, maxTableValueBytes); err != nil {
return err
}
totalBytes += len(value)
identity.WriteString(value)
identity.WriteByte(0)
}
if earlier, repeated := firstRowOf[identity.String()]; repeated {
return invalidAssessmentFamily(rowLocation, fmt.Sprintf("values repeat rows[%d]", earlier))
}
firstRowOf[identity.String()] = index
if err := validateTableAnswer(rowLocation, row, answerFormat); err != nil {
return err
}
totalBytes += len(row.Answer)
for _, distractor := range row.Distractors {
totalBytes += len(distractor)
}
if totalBytes > maxTableBytes {
return invalidAssessmentFamily(rowLocation, fmt.Sprintf("table text exceeds %d bytes", maxTableBytes))
}
if probe {
if _, err := statement.render(row.Values); err != nil {
return fmt.Errorf("%s - render statement: %w", rowLocation, err)
}
}
}
return nil
}
// checkTableValue is checkAssessmentText with the table bound.
func checkTableValue(location, field, value string, limit int) error {
if len(value) > limit {
return invalidAssessmentFamily(location, fmt.Sprintf("%s must be at most %d bytes", field, limit))
}
return checkAssessmentText(location, field, value)
}
// checkTableOption accepts one line of option text.
func checkTableOption(location, field, value string) error {
if strings.Contains(value, "\n") {
return invalidAssessmentFamily(location, field+" must be one line")
}
return checkTableValue(location, field, value, maxChoiceOptionBytes)
}
// validateTableAnswer checks that the answer of a row has the format of the
// family. For choice it requires distinct options, so that no two options
// show the same text and the correct one is not repeated among the
// distractors.
func validateTableAnswer(location string, row AssessmentVariantRow, answerFormat string) error {
if answerFormat == AnswerFormatInteger {
if !assessmentTableIntegerPattern.MatchString(row.Answer) {
return invalidAssessmentFamily(location, "answer must be a canonical decimal integer of at most 15 digits")
}
if len(row.Distractors) != 0 {
return invalidAssessmentFamily(location, "an integer answer has no distractors")
}
return nil
}
if err := checkTableOption(location, "answer", row.Answer); err != nil {
return err
}
if len(row.Distractors) < 1 || len(row.Distractors) > maxChoiceOptions-1 {
return invalidAssessmentFamily(location, fmt.Sprintf("choice row must have 1 to %d distractors", maxChoiceOptions-1))
}
seen := map[string]bool{row.Answer: true}
for _, distractor := range row.Distractors {
if err := checkTableOption(location, "distractor", distractor); err != nil {
return err
}
if seen[distractor] {
return invalidAssessmentFamily(location, "options must be distinct: a distractor repeats the answer or another distractor")
}
seen[distractor] = true
}
return nil
}
// newTableVariant selects the row of a seed and returns its variant. It is a
// pure function of the table and the seed. The family was validated when it
// was imported and again when it was read, so the answer of the row is not
// examined again here.
func (family AssessmentFamily) newTableVariant(seed VariantSeed) (AssessmentVariant, error) {
const location = "AssessmentFamily.newTableVariant"
generator := family.core.Generator
table := generator.Table
statement, err := compileStatementTemplate(location, generator.StatementTemplate, tableAlgorithm(table.columns()))
if err != nil {
return AssessmentVariant{}, err
}
random := newSeededRandom(tableSelectionName, seed)
index := random.below(len(table.Rows))
row := table.Rows[index]
rendered, err := statement.render(row.Values)
if err != nil {
return AssessmentVariant{}, fmt.Errorf("%s - render statement of rows[%d]: %w", location, index, err)
}
variant := AssessmentVariant{
FamilyID: family.id,
FamilyKey: family.core.Key,
FamilyVersion: family.core.Version,
Seed: seed,
// The row index is private provenance, kept with the frozen variant
// like the parameters of an algorithm.
Parameters: map[string]int32{"row": int32(index)}, //nolint:gosec // the index is below maxTableRows.
Statement: rendered,
ReferenceAnswer: row.Answer,
AnswerFormat: family.core.AnswerKey.AnswerFormat,
Rubric: family.core.Rubric.clone(),
}
if variant.AnswerFormat == AnswerFormatChoice {
options, correct, err := newChoiceOptions(random, row.Answer, row.Distractors, nil, len(row.Distractors))
if err != nil {
return AssessmentVariant{}, fmt.Errorf("%s - build choice options of rows[%d]: %w", location, index, err)
}
variant.Options, variant.ReferenceAnswer = options, strconv.Itoa(correct)
}
return variant, nil
}
@@ -0,0 +1,431 @@
package domain
import (
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"testing"
)
const tableStatementTemplate = "A limiter allows {{.limit}} requests per {{.window}} seconds."
// integerTableInput is a table family whose answers are written in its rows.
// The third answer is deliberately not what any computation of the values
// would give: the table, not code, decides.
func integerTableInput() NewAssessmentFamilyDraftInput {
input := testAssessmentInput()
input.Key = "unit-table-family"
input.Generator = AssessmentSeedGenerator{
StatementTemplate: tableStatementTemplate + " How many of the first 10 requests in the first second pass?",
Table: &AssessmentVariantTable{Rows: []AssessmentVariantRow{
{Values: map[string]string{"limit": "3", "window": "10"}, Answer: "3"},
{Values: map[string]string{"limit": "5", "window": "10"}, Answer: "5"},
{Values: map[string]string{"limit": "2", "window": "60"}, Answer: "-7"},
{Values: map[string]string{"limit": "8", "window": "1"}, Answer: "0"},
}},
}
input.AnswerKey.AnswerFormat = AnswerFormatInteger
return input
}
func choiceTableInput() NewAssessmentFamilyDraftInput {
input := testAssessmentInput()
input.Key = "unit-table-choice-family"
input.Generator = AssessmentSeedGenerator{
StatementTemplate: "Which status code does {{.situation}} return?",
Table: &AssessmentVariantTable{Rows: []AssessmentVariantRow{
{Values: map[string]string{"situation": "a missing resource"}, Answer: "404", Distractors: []string{"400", "410", "500"}},
{Values: map[string]string{"situation": "a request without credentials"}, Answer: "401", Distractors: []string{"403", "407"}},
{Values: map[string]string{"situation": "a conflicting update"}, Answer: "409", Distractors: []string{"412", "422", "428", "423"}},
}},
}
input.AnswerKey.AnswerFormat = AnswerFormatChoice
return input
}
func TestTableFamilySelectsRowsBySeedAndTakesTheAnswerFromTheTable(t *testing.T) {
input := integerTableInput()
family := restoreAssessment(t, input)
rows := input.Generator.Table.Rows
seen := make(map[int32]bool)
for seed := range VariantSeed(80) {
variant, err := family.NewVariant(seed)
if err != nil {
t.Fatalf("NewVariant(%d) error = %v", seed, err)
}
again, err := family.NewVariant(seed)
if err != nil || !reflect.DeepEqual(variant, again) {
t.Fatalf("seed %d gave two variants: %+v and %+v (%v)", seed, variant, again, err)
}
index := variant.Parameters["row"]
row := rows[index]
want := "A limiter allows " + row.Values["limit"] + " requests per " + row.Values["window"] +
" seconds. How many of the first 10 requests in the first second pass?"
if variant.Statement != want || variant.ReferenceAnswer != row.Answer || variant.AnswerFormat != AnswerFormatInteger || len(variant.Options) != 0 {
t.Fatalf("seed %d selected rows[%d]: variant %+v, want statement %q and the table answer %q", seed, index, variant, want, row.Answer)
}
seen[index] = true
}
if len(seen) != len(rows) {
t.Fatalf("80 seeds selected %d of %d rows", len(seen), len(rows))
}
}
// The row of a seed is part of what stored table families depend on: a change
// of the selection rule must be a new rule name, so one seed is pinned.
func TestGoldenTableRowOfASeed(t *testing.T) {
family := restoreAssessment(t, integerTableInput())
for seed, wantRow := range map[VariantSeed]int32{1: 1, 2: 2, 3: 0, 12345: 2} {
variant, err := family.NewVariant(seed)
if err != nil || variant.Parameters["row"] != wantRow {
t.Fatalf("seed %d selected rows[%d], %v, want rows[%d]", seed, variant.Parameters["row"], err, wantRow)
}
}
}
func TestTableChoiceOptionsAreTheRowAnswerAndDistractorsInSeedOrder(t *testing.T) {
input := choiceTableInput()
family := restoreAssessment(t, input)
rows := input.Generator.Table.Rows
orders := make(map[string]bool)
for seed := range VariantSeed(300) {
variant, err := family.NewVariant(seed)
if err != nil {
t.Fatalf("NewVariant(%d) error = %v", seed, err)
}
again, _ := family.NewVariant(seed)
if !reflect.DeepEqual(variant, again) {
t.Fatalf("seed %d gave two different variants", seed)
}
row := rows[variant.Parameters["row"]]
var texts []string
for _, option := range variant.Options {
texts = append(texts, option.Text)
}
orders[fmt.Sprint(variant.Parameters["row"], texts)] = true
want := append([]string{row.Answer}, row.Distractors...)
slices.Sort(want)
got := slices.Clone(texts)
slices.Sort(got)
index, ok := choiceCorrectIndex(variant)
if !slices.Equal(got, want) || !ok || variant.Options[index].Text != row.Answer || variant.AnswerFormat != AnswerFormatChoice {
t.Fatalf("seed %d: options %v with the key at %d, want %v with the key on %q", seed, texts, index, want, row.Answer)
}
if !validFrozenVariant(variant) {
t.Fatalf("seed %d: the variant is not a valid frozen variant", seed)
}
}
if len(orders) < 20 {
t.Fatalf("300 seeds gave only %d different row and option orders", len(orders))
}
}
func TestTableFamilyRefusesAFormatErrorAndNamesTheRow(t *testing.T) {
long := strings.Repeat("x", maxTableValueBytes+1)
manyRows := make([]AssessmentVariantRow, maxTableRows+1)
for index := range manyRows {
manyRows[index] = AssessmentVariantRow{Values: map[string]string{"limit": strconv.Itoa(index), "window": "1"}, Answer: "1"}
}
tests := map[string]struct {
mutate func(*NewAssessmentFamilyDraftInput)
wantRow string
}{
"a missing column": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[2].Values = map[string]string{"limit": "2"}
}, "rows[2]"},
"an extra column": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[1].Values["extra"] = "1"
}, "rows[1]"},
"another column name": {func(i *NewAssessmentFamilyDraftInput) {
delete(i.Generator.Table.Rows[3].Values, "window")
i.Generator.Table.Rows[3].Values["period"] = "1"
}, "rows[3]"},
"an empty value": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[1].Values["window"] = ""
}, "rows[1]"},
"a value with surrounding blanks": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[0].Values["window"] = " 10"
}, "rows[0]"},
"an oversized value": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[2].Values["window"] = long
}, "rows[2]"},
"a bidirectional override in a value": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[3].Values["window"] = "1\u202E"
}, "rows[3]"},
"an answer with a leading zero": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[1].Answer = "05"
}, "rows[1]"},
"a fractional answer": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[2].Answer = "1.5"
}, "rows[2]"},
"a text answer": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[3].Answer = "three"
}, "rows[3]"},
"an empty answer": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[0].Answer = ""
}, "rows[0]"},
"minus zero": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[1].Answer = "-0"
}, "rows[1]"},
"an answer beyond 15 digits": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[2].Answer = "1234567890123456"
}, "rows[2]"},
"a distractor on an integer row": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[1].Distractors = []string{"4"}
}, "rows[1]"},
"a repeated row": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[3] = i.Generator.Table.Rows[1]
}, "rows[3]"},
"a statement above the size bound": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.StatementTemplate = strings.Repeat("{{.limit}} ", 9) + "{{.window}}"
i.Generator.Table.Rows[2].Values["limit"] = strings.Repeat("9", maxTableValueBytes)
}, "rows[2]"},
"a table above the text bound": {func(i *NewAssessmentFamilyDraftInput) {
// 80 rows of one maximal value are 80000 bytes; the 64 KiB bound is
// crossed at the 66th row, which index 65 names.
i.Generator.Table.Rows = nil
for index := range 80 {
i.Generator.Table.Rows = append(i.Generator.Table.Rows, AssessmentVariantRow{
Values: map[string]string{"limit": strconv.Itoa(index), "window": strings.Repeat("w", maxTableValueBytes-3)}, Answer: "1",
})
}
}, "rows[65]"},
"one row only": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows = i.Generator.Table.Rows[:1]
}, ""},
"too many rows": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows = manyRows
}, ""},
"no rows": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows = nil
}, ""},
"an invalid column name": {func(i *NewAssessmentFamilyDraftInput) {
for _, row := range i.Generator.Table.Rows {
row.Values["Limit"] = row.Values["limit"]
delete(row.Values, "limit")
}
i.Generator.StatementTemplate = "{{.Limit}} {{.window}}"
}, ""},
"a column missing from the statement": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.StatementTemplate = "Only the {{.limit}} is shown."
}, ""},
"a placeholder that is no column": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.StatementTemplate += " {{.timestamps}}"
}, ""},
"a call in the statement": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.StatementTemplate += ` {{printf "%99999999d" 1}}`
}, ""},
"a pipeline in the statement": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.StatementTemplate += " {{.limit | len}}"
}, ""},
"an algorithm beside the table": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Algorithm = "lru_hits.v1"
}, ""},
"parameters beside the table": {func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Parameters = map[string]AssessmentParameterRange{"limit": {Min: 1, Max: 2}}
}, ""},
"an answer format the table cannot carry": {func(i *NewAssessmentFamilyDraftInput) {
i.AnswerKey.AnswerFormat = AnswerFormatIntegerSequence
}, ""},
"an answer key of another format": {func(i *NewAssessmentFamilyDraftInput) {
i.AnswerKey.AnswerFormat = AnswerFormatChoice
}, "rows[0]"},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
input := integerTableInput()
test.mutate(&input)
_, err := NewAssessmentFamilyDraft(input)
if !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("NewAssessmentFamilyDraft() error = %v, want ErrInvalidAssessmentFamily", err)
}
if test.wantRow != "" && !strings.Contains(err.Error(), test.wantRow) {
t.Fatalf("NewAssessmentFamilyDraft() error = %q, want it to name %s", err, test.wantRow)
}
})
}
}
func TestTableChoiceRowsAreCheckedLikeOptions(t *testing.T) {
tests := map[string]struct {
mutate func(*AssessmentVariantRow)
wantRow string
}{
"no distractors": {func(r *AssessmentVariantRow) { r.Distractors = nil }, "rows[1]"},
"a duplicate distractor": {func(r *AssessmentVariantRow) { r.Distractors = []string{"403", "403"} }, "rows[1]"},
"a distractor repeating the answer": {func(r *AssessmentVariantRow) {
r.Distractors = []string{"403", r.Answer}
}, "rows[1]"},
"ten distractors": {func(r *AssessmentVariantRow) {
r.Distractors = []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}
}, "rows[1]"},
"a multi-line option": {func(r *AssessmentVariantRow) { r.Distractors = []string{"403\n404"} }, "rows[1]"},
"an empty distractor": {func(r *AssessmentVariantRow) { r.Distractors = []string{"403", ""} }, "rows[1]"},
"an oversized option": {func(r *AssessmentVariantRow) { r.Answer = strings.Repeat("a", maxChoiceOptionBytes+1) }, "rows[1]"},
"a multi-line answer": {func(r *AssessmentVariantRow) { r.Answer = "4\n01" }, "rows[1]"},
"a control character": {func(r *AssessmentVariantRow) { r.Distractors = []string{"40\x003"} }, "rows[1]"},
"a format character": {func(r *AssessmentVariantRow) { r.Distractors = []string{"403\u2066"} }, "rows[1]"},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
input := choiceTableInput()
test.mutate(&input.Generator.Table.Rows[1])
_, err := NewAssessmentFamilyDraft(input)
if !errors.Is(err, ErrInvalidAssessmentFamily) || !strings.Contains(err.Error(), test.wantRow) {
t.Fatalf("NewAssessmentFamilyDraft() error = %v, want ErrInvalidAssessmentFamily naming %s", err, test.wantRow)
}
})
}
// Nine distractors, the most that ten options allow, are accepted.
input := choiceTableInput()
input.Generator.Table.Rows[1].Distractors = []string{"1", "2", "3", "4", "5", "6", "7", "8", "9"}
if _, err := NewAssessmentFamilyDraft(input); err != nil {
t.Fatalf("NewAssessmentFamilyDraft(nine distractors) error = %v", err)
}
}
func TestAlgorithmicGeneratorRefusesATable(t *testing.T) {
input := testAssessmentInput()
input.Generator.Table = integerTableInput().Generator.Table
if _, err := NewAssessmentFamilyDraft(input); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("NewAssessmentFamilyDraft(algorithm and table) error = %v, want ErrInvalidAssessmentFamily", err)
}
}
// Table families hash with scheme 2, and algorithmic families keep scheme 1
// and the hash they had before tables existed.
func TestTableFamilyHashesWithSchemeTwo(t *testing.T) {
draft, err := NewAssessmentFamilyDraft(integerTableInput())
if err != nil {
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
}
if draft.HashScheme() != assessmentHashSchemeTable {
t.Fatalf("table draft scheme = %d, want %d", draft.HashScheme(), assessmentHashSchemeTable)
}
// The canonical document of scheme 2: the generator holds the statement
// template and the table, and no algorithm or parameters.
const canonical = `{"family_key":"unit-table-family","version":1,"category":"unit-category","specialization":"unit-domain","title":"Unit test family","author":"ai:unit-test","review_status":"pending","seed_generator":{"statement_template":"A limiter allows {{.limit}} requests per {{.window}} seconds. How many of the first 10 requests in the first second pass?","table":{"rows":[{"values":{"limit":"3","window":"10"},"answer":"3"},{"values":{"limit":"5","window":"10"},"answer":"5"},{"values":{"limit":"2","window":"60"},"answer":"-7"},{"values":{"limit":"8","window":"1"},"answer":"0"}]}},"answer_key":{"answer_format":"integer","reference_solution":"Simulate the cache."},"rubric":{"principle":"Compare with the reference answer.","criteria":[{"id":"correct_answer","description":"Matches the reference answer."}]}}`
want := sha256.Sum256([]byte(canonical))
if hash := draft.ContentHash(); hash != AssessmentContentHash(want) {
t.Fatalf("scheme 2 content hash = %x, want %x of the canonical document: a changed layout of scheme 2 needs a new scheme, not an edit", hash, want)
}
if got := fmt.Sprintf("%x", want[:]); got != "f4b93487a03008c72aefbe9b3fc6f19ce9f83dc0a40e719693e07c5a1e5fb8fb" {
t.Fatalf("hash of the canonical document = %s, want the pinned value", got)
}
algorithmic, err := NewAssessmentFamilyDraft(testAssessmentInput())
if err != nil || algorithmic.HashScheme() != assessmentHashSchemeAlgorithmic {
t.Fatalf("algorithmic draft scheme = %d, %v, want %d", algorithmic.HashScheme(), err, assessmentHashSchemeAlgorithmic)
}
}
func TestTableContentIsCoveredByTheHash(t *testing.T) {
base, err := NewAssessmentFamilyDraft(integerTableInput())
if err != nil {
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
}
for name, mutate := range map[string]func(*NewAssessmentFamilyDraftInput){
"an answer": func(i *NewAssessmentFamilyDraftInput) { i.Generator.Table.Rows[3].Answer = "1" },
"a value": func(i *NewAssessmentFamilyDraftInput) { i.Generator.Table.Rows[0].Values["window"] = "11" },
"the row order": func(i *NewAssessmentFamilyDraftInput) {
i.Generator.Table.Rows[0], i.Generator.Table.Rows[1] = i.Generator.Table.Rows[1], i.Generator.Table.Rows[0]
},
"a dropped row": func(i *NewAssessmentFamilyDraftInput) { i.Generator.Table.Rows = i.Generator.Table.Rows[:3] },
"the statement text": func(i *NewAssessmentFamilyDraftInput) { i.Generator.StatementTemplate += " Think." },
} {
input := integerTableInput()
mutate(&input)
draft, err := NewAssessmentFamilyDraft(input)
if err != nil {
t.Fatalf("%s: NewAssessmentFamilyDraft() error = %v", name, err)
}
if draft.ContentHash() == base.ContentHash() {
t.Errorf("changing %s did not change the content hash", name)
}
}
// A draft does not share state with the input it was built from.
input := integerTableInput()
draft, err := NewAssessmentFamilyDraft(input)
if err != nil {
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
}
input.Generator.Table.Rows[0].Answer = "99"
if draft.Core().Generator.Table.Rows[0].Answer != "3" {
t.Fatal("editing the input table changed the table of the draft")
}
}
func TestRestoreVerifiesATableFamilyWithItsScheme(t *testing.T) {
draft, err := NewAssessmentFamilyDraft(choiceTableInput())
if err != nil {
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
}
stored := storedAssessmentFrom(t, draft)
family, err := RestoreAssessmentFamily(stored)
if err != nil || family.HashScheme() != assessmentHashSchemeTable {
t.Fatalf("RestoreAssessmentFamily(table row) = scheme %d, %v, want a verified row of scheme 2", family.HashScheme(), err)
}
// The stored document is the table, and the variants of the restored
// family are those of the draft's content.
if _, err := family.NewVariant(5); err != nil {
t.Fatalf("NewVariant() error = %v", err)
}
// An edited answer in the stored document fails the hash.
var document map[string]json.RawMessage
if err := json.Unmarshal(stored.SeedGenerator, &document); err != nil {
t.Fatalf("decode stored generator: %v", err)
}
edited := stored
edited.SeedGenerator = []byte(strings.Replace(string(stored.SeedGenerator), `"answer":"404"`, `"answer":"405"`, 1))
if string(edited.SeedGenerator) == string(stored.SeedGenerator) {
t.Fatal("the test did not edit the stored table")
}
if _, err := RestoreAssessmentFamily(edited); !errors.Is(err, ErrAssessmentFamilyIntegrity) {
t.Fatalf("RestoreAssessmentFamily(edited answer) error = %v, want ErrAssessmentFamilyIntegrity", err)
}
// A table under scheme 1 would leave the table out of the hash, so it is
// refused; so is an algorithmic generator under scheme 2.
wrong := stored
wrong.HashScheme = assessmentHashSchemeAlgorithmic
if _, err := RestoreAssessmentFamily(wrong); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("RestoreAssessmentFamily(table under scheme 1) error = %v, want ErrInvalidAssessmentFamily", err)
}
algorithmic, err := NewAssessmentFamilyDraft(testAssessmentInput())
if err != nil {
t.Fatalf("NewAssessmentFamilyDraft(algorithmic) error = %v", err)
}
wrong = storedAssessmentFrom(t, algorithmic)
wrong.HashScheme = assessmentHashSchemeTable
if _, err := RestoreAssessmentFamily(wrong); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("RestoreAssessmentFamily(algorithm under scheme 2) error = %v, want ErrInvalidAssessmentFamily", err)
}
// A stored table document of another layout does not decode.
broken := stored
broken.SeedGenerator = []byte(strings.Replace(string(stored.SeedGenerator), `"answer"`, `"solution"`, 1))
if _, err := RestoreAssessmentFamily(broken); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("RestoreAssessmentFamily(unknown row field) error = %v, want ErrInvalidAssessmentFamily", err)
}
}
// The answer of a table variant is the text of the table, never the result of
// a computation: this table's answers disagree with every reading of its
// values and are still what the variant returns and what grades.
func TestTableAnswerIsNeverComputed(t *testing.T) {
family := restoreAssessment(t, integerTableInput())
variant, err := family.NewVariant(4)
if err != nil {
t.Fatalf("NewVariant() error = %v", err)
}
row := integerTableInput().Generator.Table.Rows[variant.Parameters["row"]]
_, correct, err := CanonicalAssessmentAnswerForVariant(json.RawMessage(`{"format":"number","number":`+row.Answer+`}`), variant)
if err != nil || !correct {
t.Fatalf("grading the table answer = %v, %v, want correct", correct, err)
}
}
@@ -78,3 +78,69 @@ func TestBundleRejectsInvalidDocuments(t *testing.T) {
t.Fatalf("Drafts(no families) error = %v, want ErrInvalidAssessmentFamily", err)
}
}
// tableBundleDocument is a bundle with a declarative family: the variants are
// rows of a table, and the answers are written in the rows.
const tableBundleDocument = `{
"name": "table-bundle-v1",
"category": "backend",
"author": "operator:author",
"review": {"status": "approved", "reviewer": "operator:reviewer"},
"families": [{
"key": "http-status-table",
"version": 1,
"specialization": "http",
"title": "Status codes",
"seed_generator": {
"statement_template": "Which status code does {{.situation}} return?",
"table": {"rows": [
{"values": {"situation": "a missing resource"}, "answer": "404", "distractors": ["400", "410", "500"]},
{"values": {"situation": "a request without credentials"}, "answer": "401", "distractors": ["403", "407"]}
]}
},
"answer_key": {"answer_format": "choice", "reference_solution": "Match the situation to the status code."},
"rubric": {"principle": "Compare with the key.", "criteria": [{"id": "correct_answer", "description": "Selects the key."}]}
}]
}`
func TestTableFamilyBundleIsParsedAndDrafted(t *testing.T) {
bundle, err := ParseBundle(strings.NewReader(tableBundleDocument))
if err != nil {
t.Fatalf("ParseBundle(table bundle) error = %v", err)
}
drafts, err := bundle.Drafts()
if err != nil || len(drafts) != 1 {
t.Fatalf("Drafts() = %d drafts, %v, want one", len(drafts), err)
}
if drafts[0].HashScheme() != 2 {
t.Fatalf("table family scheme = %d, want 2", drafts[0].HashScheme())
}
again, err := bundle.Drafts()
if err != nil || again[0].ContentHash() != drafts[0].ContentHash() {
t.Fatalf("Drafts() twice hashed differently: %v", err)
}
}
func TestTableFamilyBundleRefusesAFormatErrorWithTheRowIndex(t *testing.T) {
broken := strings.Replace(tableBundleDocument, `"answer": "401"`, `"answer": "403"`, 1)
bundle, err := ParseBundle(strings.NewReader(broken))
if err != nil {
t.Fatalf("ParseBundle() error = %v", err)
}
_, err = bundle.Drafts()
if !errors.Is(err, domain.ErrInvalidAssessmentFamily) || !strings.Contains(err.Error(), "rows[1]") {
t.Fatalf("Drafts(answer repeated among the distractors) error = %v, want ErrInvalidAssessmentFamily naming rows[1]", err)
}
// An unknown field of a row is a format error at parse time: the table
// holds data only, and a field that could carry code is not ignored.
for name, replacement := range map[string]string{
"a script field": `"values": {"situation": "a missing resource"}, "script": "1+1", "answer": "404"`,
"a formula field": `"values": {"situation": "a missing resource"}, "formula": "len(values)", "answer": "404"`,
} {
document := strings.Replace(tableBundleDocument, `"values": {"situation": "a missing resource"}, "answer": "404"`, replacement, 1)
if _, err := ParseBundle(strings.NewReader(document)); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
t.Fatalf("ParseBundle(%s) error = %v, want ErrInvalidAssessmentFamily", name, err)
}
}
}
+2
View File
@@ -38,3 +38,5 @@ Seed algorithms are registered in `internal/domain/assessment_algorithms.go`
under versioned names (`rate_limit_window.v1`, `dedup_window.v1`,
`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.
A family can instead declare a `table` of variants with their answers in its
`seed_generator`; this bundle uses only algorithms.