Files
lincodex/backend/internal/domain/assessment_table.go
T

262 lines
10 KiB
Go

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
}