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

375 lines
14 KiB
Go

package domain
import (
"crypto/sha256"
"encoding/binary"
"fmt"
"maps"
"strconv"
"text/template/parse"
)
// Answer formats of reference answers.
const (
// AnswerFormatInteger is a single decimal integer.
AnswerFormatInteger = "integer"
// AnswerFormatIntegerSequence is decimal integers separated by single
// spaces.
AnswerFormatIntegerSequence = "integer_sequence"
)
// variantSeedDomain separates the seed derivation of variants from any other
// use of SHA-256 in the system.
const variantSeedDomain = "lincodex.assessment.variant.v1"
// VariantSeed selects one variant of a family. The same family version and
// the same seed always produce the same statement and reference answer.
type VariantSeed uint64
// AssessmentParameterRange is the inclusive range of one generator
// parameter.
type AssessmentParameterRange struct {
Min int32 `json:"min"`
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.
type AssessmentSeedGenerator struct {
Algorithm string `json:"algorithm"`
Parameters map[string]AssessmentParameterRange `json:"parameters"`
// 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.
StatementTemplate string `json:"statement_template"`
}
func (generator AssessmentSeedGenerator) clone() AssessmentSeedGenerator {
copied := generator
copied.Parameters = maps.Clone(generator.Parameters)
return copied
}
// validate checks the algorithm, the parameter ranges against the bounds the
// algorithm accepts, and the template. With probe set it also renders the
// template at both ends of the ranges and at one seed, which an importer does
// once; reading a stored row skips the probes, because the content hash
// proves that the content is the one that passed them. It returns the
// algorithm.
func (generator AssessmentSeedGenerator) validate(location string, probe bool) (assessmentAlgorithm, error) {
algorithm, ok := assessmentAlgorithms[generator.Algorithm]
if !ok {
return assessmentAlgorithm{}, invalidAssessmentFamily(location, "generator algorithm is unknown")
}
if len(generator.Parameters) != len(algorithm.parameters) {
return assessmentAlgorithm{}, invalidAssessmentFamily(location, "generator parameters must be exactly the parameters of the algorithm")
}
lowest, highest := make(map[string]int32, len(algorithm.parameters)), make(map[string]int32, len(algorithm.parameters))
for _, spec := range algorithm.parameters {
parameterRange, ok := generator.Parameters[spec.name]
if !ok {
return assessmentAlgorithm{}, invalidAssessmentFamily(location, "generator parameters must be exactly the parameters of the algorithm")
}
if parameterRange.Min < spec.lowest || parameterRange.Max > spec.highest || parameterRange.Min > parameterRange.Max {
return assessmentAlgorithm{}, invalidAssessmentFamily(location,
fmt.Sprintf("generator parameter %s must be a range inside %d to %d", spec.name, spec.lowest, spec.highest))
}
lowest[spec.name], highest[spec.name] = parameterRange.Min, parameterRange.Max
}
statement, err := compileStatementTemplate(location, generator.StatementTemplate, algorithm)
if err != nil {
return assessmentAlgorithm{}, err
}
if !probe {
return algorithm, nil
}
if _, err := generator.instantiate(algorithm, statement, lowest, 0); err != nil {
return assessmentAlgorithm{}, fmt.Errorf("%s - probe generator at the lowest values: %w", location, err)
}
// The highest values give the largest inputs, and drawn values give the
// usual ones; the size of an input varies with its numbers, so each is
// rendered for several seeds.
for seed := range VariantSeed(probeSeedCount) {
for _, fixed := range []map[string]int32{highest, nil} {
if _, err := generator.instantiate(algorithm, statement, fixed, seed); err != nil {
return assessmentAlgorithm{}, fmt.Errorf("%s - probe generator with seed %d: %w", location, seed, err)
}
}
}
return algorithm, nil
}
// instantiate builds one variant body. A nil fixed map draws every parameter
// from its range with the seed; otherwise the fixed values are used.
func (generator AssessmentSeedGenerator) instantiate(
algorithm assessmentAlgorithm,
statement statementTemplate,
fixed map[string]int32,
seed VariantSeed,
) (variantBody, error) {
random := newSeededRandom(generator.Algorithm, seed)
values := make(map[string]int32, len(algorithm.parameters))
// Parameters are drawn in the declared order, so a seed always meets the
// same draws.
for _, spec := range algorithm.parameters {
parameterRange := generator.Parameters[spec.name]
if fixed != nil {
values[spec.name] = fixed[spec.name]
continue
}
values[spec.name] = random.between(parameterRange.Min, parameterRange.Max)
}
data, answer := algorithm.generate(random, values)
for name, value := range values {
data[name] = strconv.Itoa(int(value))
}
rendered, err := statement.render(data)
if err != nil {
return variantBody{}, err
}
return variantBody{parameters: values, statement: rendered, answer: answer}, nil
}
type variantBody struct {
parameters map[string]int32
statement string
answer string
}
// 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
ReferenceAnswer string
AnswerFormat string
Rubric AssessmentRubric
}
// NewVariant generates the variant of a seed. It is a pure function of the
// family content and the seed.
func (family AssessmentFamily) NewVariant(seed VariantSeed) (AssessmentVariant, error) {
const location = "AssessmentFamily.NewVariant"
if family.IsZero() {
return AssessmentVariant{}, invalidAssessmentFamily(location, "family was not built by RestoreAssessmentFamily")
}
algorithm, ok := assessmentAlgorithms[family.core.Generator.Algorithm]
if !ok {
return AssessmentVariant{}, invalidAssessmentFamily(location, "generator algorithm is unknown")
}
statement, err := compileStatementTemplate(location, family.core.Generator.StatementTemplate, algorithm)
if err != nil {
return AssessmentVariant{}, err
}
body, err := family.core.Generator.instantiate(algorithm, statement, nil, seed)
if err != nil {
return AssessmentVariant{}, fmt.Errorf("%s - generate variant: %w", location, err)
}
return AssessmentVariant{
FamilyID: family.id,
FamilyKey: family.core.Key,
FamilyVersion: family.core.Version,
Seed: seed,
Parameters: body.parameters,
Statement: body.statement,
ReferenceAnswer: body.answer,
AnswerFormat: algorithm.answerFormat,
Rubric: family.core.Rubric.clone(),
}, nil
}
// seededRandom is SplitMix64. It is written out here instead of taken from
// math/rand so that the variants of a stored family stay reproducible across
// Go releases.
type seededRandom struct {
state uint64
}
func newSeededRandom(algorithm string, seed VariantSeed) *seededRandom {
material := make([]byte, 0, len(variantSeedDomain)+len(algorithm)+10)
material = append(material, variantSeedDomain...)
material = append(material, 0)
material = append(material, algorithm...)
material = append(material, 0)
material = binary.BigEndian.AppendUint64(material, uint64(seed))
digest := sha256.Sum256(material)
return &seededRandom{state: binary.BigEndian.Uint64(digest[:8])}
}
func (random *seededRandom) next() uint64 {
random.state += 0x9e3779b97f4a7c15
value := random.state
value = (value ^ (value >> 30)) * 0xbf58476d1ce4e5b9
value = (value ^ (value >> 27)) * 0x94d049bb133111eb
return value ^ (value >> 31)
}
// below returns a value in [0, bound). The bias of the modulo is below
// 2^-50 for the small bounds used here.
func (random *seededRandom) below(bound int) int {
return int(random.next() % uint64(bound)) //nolint:gosec // callers pass a positive bound that the parameter bounds keep small.
}
func (random *seededRandom) between(lowest, highest int32) int32 {
return lowest + int32(random.below(int(highest-lowest)+1)) //nolint:gosec // the draw is below highest-lowest+1, which fits int32.
}
// assessmentParameterSpec names a generator parameter and the bounds that
// every family range must lie in. The bounds keep statements small and the
// reference solvers fast; they are not product thresholds.
type assessmentParameterSpec struct {
name string
lowest, highest int32
}
// assessmentAlgorithm is a registered seed algorithm. The registry is
// append-only: a changed algorithm gets a new versioned name, because stored
// family versions refer to the old name.
type assessmentAlgorithm struct {
answerFormat string
// parameters in the order in which a seed draws them.
parameters []assessmentParameterSpec
// dataNames lists the generated input data that generate returns.
dataNames []string
// requiredNames lists the placeholders that a statement template must
// contain, because the reference answer depends on them: without them
// the candidate would not see the input.
requiredNames []string
// generate returns the input data for the statement template and the
// reference answer.
generate func(random *seededRandom, parameters map[string]int32) (data map[string]string, answer string)
}
// probeSeedCount is the number of seeds that an importer renders at the
// highest parameter values and at drawn values. A template whose statement is
// close to maxStatementBytes must not pass because one lucky seed rendered
// short.
const probeSeedCount = 8
const (
// maxStatementTemplateBytes bounds the template text.
maxStatementTemplateBytes = 2000
// maxStatementBytes bounds a rendered statement. The largest input of any
// algorithm fits with the template text; a larger result means a
// template or an algorithm that outgrew its bounds, and is refused.
maxStatementBytes = 8 << 10
)
// statementPart is a literal text, or a placeholder when field is set.
type statementPart struct {
literal string
field string
}
// statementTemplate is a statement template that passed the whitelist below.
type statementTemplate []statementPart
// compileStatementTemplate accepts plain text with {{.name}} placeholders and
// nothing else. The text/template parser reads it with no functions, and the
// walk below rejects every node other than text and a single field action:
// define, template, block, range, with, if, variables, pipelines, and
// calls. A statement therefore cannot loop, recurse, or ask for a width, and
// its size is bounded by the template and the data. The names must belong to
// the algorithm, and the template must use every name that the reference
// answer depends on.
func compileStatementTemplate(location, text string, algorithm assessmentAlgorithm) (statementTemplate, error) {
if len(text) > maxStatementTemplateBytes {
return nil, invalidAssessmentFamily(location, fmt.Sprintf("statement template must be at most %d bytes", maxStatementTemplateBytes))
}
if err := checkAssessmentText(location, "statement template", text); err != nil {
return nil, err
}
trees, err := parse.Parse("statement", text, "{{", "}}")
if err != nil {
return nil, fmt.Errorf("%w: parse statement template: %w", ErrInvalidAssessmentFamily, err)
}
tree, ok := trees["statement"]
if !ok || len(trees) != 1 || tree.Root == nil {
return nil, invalidAssessmentFamily(location, "statement template must not define other templates")
}
parts, used, err := statementParts(location, tree, algorithm)
if err != nil {
return nil, err
}
for _, name := range algorithm.requiredNames {
if !used[name] {
return nil, invalidAssessmentFamily(location, "statement template must contain the placeholder {{."+name+"}}")
}
}
return parts, nil
}
// placeholderName returns the name of an action that is exactly {{.name}}.
func placeholderName(action *parse.ActionNode) (string, bool) {
pipe := action.Pipe
if pipe == nil || len(pipe.Decl) != 0 || pipe.IsAssign || len(pipe.Cmds) != 1 {
return "", false
}
command := pipe.Cmds[0]
if len(command.Args) != 1 {
return "", false
}
field, ok := command.Args[0].(*parse.FieldNode)
if !ok || len(field.Ident) != 1 {
return "", false
}
return field.Ident[0], true
}
// render fills the placeholders and refuses a statement above the size
// bound.
func (statement statementTemplate) render(data map[string]string) (string, error) {
var rendered []byte
for _, part := range statement {
text := part.literal
if part.field != "" {
text = data[part.field]
}
if len(rendered)+len(text) > maxStatementBytes {
return "", fmt.Errorf("%w: rendered statement exceeds %d bytes", ErrInvalidAssessmentFamily, maxStatementBytes)
}
rendered = append(rendered, text...)
}
return string(rendered), nil
}
// statementParts walks the parsed template and returns its parts and the set
// of placeholders it uses.
func statementParts(location string, tree *parse.Tree, algorithm assessmentAlgorithm) (statementTemplate, map[string]bool, error) {
allowed := make(map[string]bool)
for _, spec := range algorithm.parameters {
allowed[spec.name] = true
}
for _, name := range algorithm.dataNames {
allowed[name] = true
}
used := make(map[string]bool)
var parts statementTemplate
for _, node := range tree.Root.Nodes {
switch typed := node.(type) {
case *parse.TextNode:
parts = append(parts, statementPart{literal: string(typed.Text)})
case *parse.ActionNode:
field, ok := placeholderName(typed)
if !ok {
return nil, nil, invalidAssessmentFamily(location, "statement template allows only {{.name}} placeholders")
}
if !allowed[field] {
return nil, nil, invalidAssessmentFamily(location, "statement template names an unknown placeholder")
}
used[field] = true
parts = append(parts, statementPart{field: field})
default:
return nil, nil, invalidAssessmentFamily(location, "statement template allows only text and {{.name}} placeholders")
}
}
return parts, used, nil
}