feat(assessment): add immutable family versions and the demo bank loader

This commit is contained in:
shira committed 2026-10-06 20:34:06 +03:00
1 parent 94488e2b57
commit 204c6bae62
28 files changed
+6269 -9

No files matched your search

@@ -0,0 +1,246 @@
package domain
import (
"strconv"
"strings"
)
// Registered seed algorithms. Each one draws an input from the seed and
// computes the reference answer with its solver. The names carry a version;
// see assessmentAlgorithm.
var assessmentAlgorithms = map[string]assessmentAlgorithm{
"rate_limit_window.v1": {
answerFormat: AnswerFormatInteger,
parameters: []assessmentParameterSpec{
{name: "requests", lowest: 1, highest: 500},
{name: "window", lowest: 1, highest: 1000},
{name: "limit", lowest: 1, highest: 100},
{name: "max_gap", lowest: 0, highest: 100},
},
dataNames: []string{"timestamps"},
requiredNames: []string{"timestamps", "window", "limit"},
generate: generateRateLimitWindow,
},
"dedup_window.v1": {
answerFormat: AnswerFormatInteger,
parameters: []assessmentParameterSpec{
{name: "events", lowest: 1, highest: 500},
{name: "keys", lowest: 1, highest: 26},
{name: "ttl", lowest: 1, highest: 1000},
{name: "max_gap", lowest: 0, highest: 100},
},
dataNames: []string{"stream"},
requiredNames: []string{"stream", "ttl"},
generate: generateDedupWindow,
},
"lru_hits.v1": {
answerFormat: AnswerFormatInteger,
parameters: []assessmentParameterSpec{
{name: "accesses", lowest: 1, highest: 500},
{name: "keys", lowest: 1, highest: 100},
{name: "capacity", lowest: 1, highest: 50},
},
dataNames: []string{"sequence"},
requiredNames: []string{"sequence", "capacity"},
generate: generateLRUHits,
},
"dependency_order.v1": {
answerFormat: AnswerFormatIntegerSequence,
parameters: []assessmentParameterSpec{
{name: "tasks", lowest: 2, highest: 20},
{name: "links", lowest: 0, highest: 60},
},
dataNames: []string{"dependencies"},
requiredNames: []string{"dependencies", "tasks"},
generate: generateDependencyOrder,
},
}
// keyLetters names the keys of the duplicate-window stream; the algorithm
// allows at most this many keys.
const keyLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
// ascendingTimes returns count non-decreasing times. The first is a draw from
// 0 to maxGap and every next one adds another such draw to its predecessor.
func ascendingTimes(random *seededRandom, count, maxGap int32) []int {
times := make([]int, count)
current := 0
for index := range times {
current += int(random.between(0, maxGap))
times[index] = current
}
return times
}
// joinInts writes values as decimal numbers separated by single spaces.
func joinInts(values []int) string {
parts := make([]string, len(values))
for index, value := range values {
parts[index] = strconv.Itoa(value)
}
return strings.Join(parts, " ")
}
// Data names: timestamps.
func generateRateLimitWindow(random *seededRandom, parameters map[string]int32) (map[string]string, string) {
times := ascendingTimes(random, parameters["requests"], parameters["max_gap"])
rejected := rateLimitRejected(times, int(parameters["window"]), int(parameters["limit"]))
return map[string]string{"timestamps": joinInts(times)}, strconv.Itoa(rejected)
}
// rateLimitRejected counts requests that a sliding-window limiter rejects. A
// request at time t is accepted when fewer than limit accepted requests lie
// in the half-open interval (t-window, t]; rejected requests are not
// remembered. Times are non-decreasing.
func rateLimitRejected(times []int, window, limit int) int {
accepted := make([]int, 0, len(times))
oldest, rejected := 0, 0
for _, moment := range times {
for oldest < len(accepted) && accepted[oldest] <= moment-window {
oldest++
}
if len(accepted)-oldest < limit {
accepted = append(accepted, moment)
} else {
rejected++
}
}
return rejected
}
// Data names: stream.
func generateDedupWindow(random *seededRandom, parameters map[string]int32) (map[string]string, string) {
times := ascendingTimes(random, parameters["events"], parameters["max_gap"])
keys := make([]int, len(times))
events := make([]string, len(times))
for index, moment := range times {
keys[index] = random.below(int(parameters["keys"]))
events[index] = keyLetters[keys[index]:keys[index]+1] + "@" + strconv.Itoa(moment)
}
processed := dedupProcessed(keys, times, int(parameters["ttl"]))
return map[string]string{"stream": strings.Join(events, " ")}, strconv.Itoa(processed)
}
// dedupProcessed counts events that an idempotent consumer processes. An
// event is dropped as a duplicate when its key was processed less than ttl
// time units earlier; a dropped event does not extend that period. Times are
// non-decreasing.
func dedupProcessed(keys, times []int, ttl int) int {
lastProcessed := make(map[int]int, len(keys))
processed := 0
for index, key := range keys {
last, seen := lastProcessed[key]
if seen && times[index]-last < ttl {
continue
}
lastProcessed[key] = times[index]
processed++
}
return processed
}
// Data names: sequence.
func generateLRUHits(random *seededRandom, parameters map[string]int32) (map[string]string, string) {
accesses := make([]int, parameters["accesses"])
for index := range accesses {
accesses[index] = 1 + random.below(int(parameters["keys"]))
}
hits := lruHits(accesses, int(parameters["capacity"]))
return map[string]string{"sequence": joinInts(accesses)}, strconv.Itoa(hits)
}
// lruHits counts the accesses that find their key in a least-recently-used
// cache of the given capacity. A hit and a miss both make the key the most
// recently used one; a miss on a full cache evicts the least recently used
// key first.
func lruHits(accesses []int, capacity int) int {
// recent holds the cached keys from least to most recently used.
recent := make([]int, 0, capacity)
hits := 0
for _, key := range accesses {
position := -1
for index, cached := range recent {
if cached == key {
position = index
break
}
}
switch {
case position >= 0:
hits++
recent = append(recent[:position], recent[position+1:]...)
case len(recent) == capacity:
recent = recent[1:]
}
recent = append(recent, key)
}
return hits
}
// Data names: dependencies.
func generateDependencyOrder(random *seededRandom, parameters map[string]int32) (map[string]string, string) {
tasks := int(parameters["tasks"])
// A hidden shuffle fixes a valid order; links only point forward in it,
// so the graph never has a cycle.
hidden := make([]int, tasks)
for index := range hidden {
hidden[index] = index + 1
}
for index := tasks - 1; index > 0; index-- {
swap := random.below(index + 1)
hidden[index], hidden[swap] = hidden[swap], hidden[index]
}
seen := make(map[[2]int]bool)
var links [][2]int
var described []string
for range parameters["links"] {
first, second := random.below(tasks), random.below(tasks)
if first == second {
continue
}
if first > second {
first, second = second, first
}
link := [2]int{hidden[first], hidden[second]}
if seen[link] {
continue
}
seen[link] = true
links = append(links, link)
described = append(described, strconv.Itoa(link[0])+"->"+strconv.Itoa(link[1]))
}
dependencies := "none"
if len(described) > 0 {
dependencies = strings.Join(described, " ")
}
return map[string]string{"dependencies": dependencies}, joinInts(smallestDependencyOrder(tasks, links))
}
// smallestDependencyOrder returns the lexicographically smallest order of
// tasks 1..tasks in which every link {before, after} has before first. The
// links must not contain a cycle.
func smallestDependencyOrder(tasks int, links [][2]int) []int {
pending := make([]int, tasks+1)
for _, link := range links {
pending[link[1]]++
}
done := make([]bool, tasks+1)
order := make([]int, 0, tasks)
for len(order) < tasks {
next := 0
for task := 1; task <= tasks; task++ {
if !done[task] && pending[task] == 0 {
next = task
break
}
}
done[next] = true
order = append(order, next)
for _, link := range links {
if link[0] == next {
pending[link[1]]--
}
}
}
return order
}
@@ -0,0 +1,847 @@
package domain
import (
"bytes"
"crypto/sha256"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
"time"
"unicode"
"github.com/google/uuid"
)
const (
maxAssessmentTitleLength = 200
maxAssessmentIdentityLength = 128
maxAssessmentTextLength = 4000
maxAssessmentRubricCriteria = 20
maxAssessmentCriterionIDSize = 64
)
var (
// ErrInvalidAssessmentFamily reports a family version, bundle value, or
// opening that is missing, malformed, or inconsistent.
ErrInvalidAssessmentFamily = errors.New("invalid assessment family")
// ErrAssessmentFamilyIntegrity reports a stored family whose canonical
// content no longer matches the stored SHA-256. The row was changed
// outside the application.
ErrAssessmentFamilyIntegrity = errors.New("assessment family does not match its hash")
// ErrAssessmentRefused reports an operation that the bank rules refuse:
// publishing a family or opening a category. errors.As with
// *AssessmentRefusalError yields the machine-readable reason.
ErrAssessmentRefused = errors.New("assessment bank operation refused")
assessmentCategoryPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{1,47}$`)
assessmentFamilyKeyPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{2,63}$`)
assessmentSpecializationPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{1,63}$`)
assessmentBundleNamePattern = regexp.MustCompile(`^[a-z][a-z0-9._-]{2,63}$`)
assessmentAuthorPattern = regexp.MustCompile(`^(ai|operator):[a-z0-9][a-z0-9._-]*$`)
assessmentOperatorPattern = regexp.MustCompile(`^operator:[a-z0-9][a-z0-9._-]*$`)
assessmentCriterionIDPattern = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
)
// AssessmentRefusalReason names why the bank refused an operation.
type AssessmentRefusalReason string
const (
// RefusalReviewerMissing: the family has no reviewer.
RefusalReviewerMissing AssessmentRefusalReason = "reviewer_missing"
// RefusalReviewNotApproved: the review of the family is not approved.
RefusalReviewNotApproved AssessmentRefusalReason = "review_not_approved"
// RefusalNotDraft: the family is not a draft any more.
RefusalNotDraft AssessmentRefusalReason = "not_draft"
// RefusalNotPublished: the family is not published.
RefusalNotPublished AssessmentRefusalReason = "not_published"
// RefusalCoverageInsufficient: the category has fewer published families
// than the grading policy requires.
RefusalCoverageInsufficient AssessmentRefusalReason = "coverage_insufficient"
// RefusalGradingPolicyMissing: no versioned grading policy was
// referenced, or the reference does not resolve to a stored version.
RefusalGradingPolicyMissing AssessmentRefusalReason = "grading_policy_missing"
// RefusalVersionConflict: a version with the same number but different
// content is already stored.
RefusalVersionConflict AssessmentRefusalReason = "version_conflict"
// RefusalVersionGap: the version is not the next one of its family.
RefusalVersionGap AssessmentRefusalReason = "version_gap"
// RefusalCategoryChanged: a new version moves the family to another
// category.
RefusalCategoryChanged AssessmentRefusalReason = "category_changed"
// RefusalNewerVersionPublished: a newer version of the family is already
// published, so an older one cannot be published.
RefusalNewerVersionPublished AssessmentRefusalReason = "newer_version_published"
// RefusalGradingPolicyNotCurrent: the referenced grading policy version
// is stored but is not the version in force.
RefusalGradingPolicyNotCurrent AssessmentRefusalReason = "grading_policy_not_current"
)
// AssessmentRefusalError is the error of a refused operation. It carries the
// reason for callers and a detail for operators. The detail never quotes
// task content.
type AssessmentRefusalError struct {
Reason AssessmentRefusalReason
Detail string
}
func (refusal *AssessmentRefusalError) Error() string {
return fmt.Sprintf("assessment bank refused: %s: %s", refusal.Reason, refusal.Detail)
}
func (refusal *AssessmentRefusalError) Unwrap() error { return ErrAssessmentRefused }
// NewAssessmentRefusalError builds the error of a refused operation.
func NewAssessmentRefusal(reason AssessmentRefusalReason, detail string) *AssessmentRefusalError {
return &AssessmentRefusalError{Reason: reason, Detail: detail}
}
func invalidAssessmentFamily(location, reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidAssessmentFamily)
}
// AssessmentFamilyID identifies one stored version of a family.
type AssessmentFamilyID uuid.UUID
// NewAssessmentFamilyID returns a time-ordered UUIDv7.
func NewAssessmentFamilyID() (AssessmentFamilyID, error) {
id, err := uuid.NewV7()
if err != nil {
return AssessmentFamilyID{}, fmt.Errorf("domain.NewAssessmentFamilyID - generate ID: %w", err)
}
return AssessmentFamilyID(id), nil
}
func (id AssessmentFamilyID) UUID() uuid.UUID { return uuid.UUID(id) }
func (id AssessmentFamilyID) String() string { return uuid.UUID(id).String() }
func (id AssessmentFamilyID) IsZero() bool { return uuid.UUID(id) == uuid.Nil }
// AssessmentCategory is a category of the bank, for example "backend". A
// category is available to candidates only after an opening.
type AssessmentCategory string
func ParseAssessmentCategory(value string) (AssessmentCategory, error) {
if !assessmentCategoryPattern.MatchString(value) {
return "", invalidAssessmentFamily("domain.ParseAssessmentCategory", "category must be 2 to 48 lowercase letters, digits, or '-', starting with a letter")
}
return AssessmentCategory(value), nil
}
// AssessmentFamilyKey is the stable name of a family across its versions.
type AssessmentFamilyKey string
func ParseAssessmentFamilyKey(value string) (AssessmentFamilyKey, error) {
if !assessmentFamilyKeyPattern.MatchString(value) {
return "", invalidAssessmentFamily("domain.ParseAssessmentFamilyKey", "family key must be 3 to 64 lowercase letters, digits, or '-', starting with a letter")
}
return AssessmentFamilyKey(value), nil
}
// AssessmentSpecialization is the specialization or domain of a family
// inside its category.
type AssessmentSpecialization string
func ParseAssessmentSpecialization(value string) (AssessmentSpecialization, error) {
if !assessmentSpecializationPattern.MatchString(value) {
return "", invalidAssessmentFamily("domain.ParseAssessmentSpecialization", "specialization must be 2 to 64 lowercase letters, digits, or '-', starting with a letter")
}
return AssessmentSpecialization(value), nil
}
// AssessmentBundleName names the bundle a version was imported from.
type AssessmentBundleName string
func ParseAssessmentBundleName(value string) (AssessmentBundleName, error) {
if !assessmentBundleNamePattern.MatchString(value) {
return "", invalidAssessmentFamily("domain.ParseAssessmentBundleName", "bundle name must be 3 to 64 lowercase letters, digits, '.', '_', or '-', starting with a letter")
}
return AssessmentBundleName(value), nil
}
// AssessmentAuthor identifies who wrote a family: "ai:<name>" for a
// generated draft or "operator:<handle>" for a person. Never contact data.
type AssessmentAuthor string
func ParseAssessmentAuthor(value string) (AssessmentAuthor, error) {
if len(value) > maxAssessmentIdentityLength || !assessmentAuthorPattern.MatchString(value) {
return "", invalidAssessmentFamily("domain.ParseAssessmentAuthor", "author must be ai:<name> or operator:<handle> of at most 128 bytes in lowercase letters, digits, '.', '_', or '-'")
}
return AssessmentAuthor(value), nil
}
// AssessmentOperator identifies a person who reviews a family or opens a
// category: "operator:<handle>". An AI draft cannot review itself or open a
// category, so no "ai:" identity parses here.
type AssessmentOperator string
func ParseAssessmentOperator(value string) (AssessmentOperator, error) {
if len(value) > maxAssessmentIdentityLength || !assessmentOperatorPattern.MatchString(value) {
return "", invalidAssessmentFamily("domain.ParseAssessmentOperator", "operator must be operator:<handle> of at most 128 bytes in lowercase letters, digits, '.', '_', or '-'")
}
return AssessmentOperator(value), nil
}
// AssessmentReviewStatus is the state of the independent review of one
// family version.
type AssessmentReviewStatus string
const (
// AssessmentReviewPending means no reviewer has judged the version yet.
AssessmentReviewPending AssessmentReviewStatus = "pending"
// AssessmentReviewApproved means an independent reviewer approved it.
AssessmentReviewApproved AssessmentReviewStatus = "approved"
// AssessmentReviewRejected means the reviewer did not approve it.
AssessmentReviewRejected AssessmentReviewStatus = "rejected"
)
func ParseAssessmentReviewStatus(value string) (AssessmentReviewStatus, error) {
status := AssessmentReviewStatus(value)
switch status {
case AssessmentReviewPending, AssessmentReviewApproved, AssessmentReviewRejected:
return status, nil
default:
return "", invalidAssessmentFamily("domain.ParseAssessmentReviewStatus", "review status must be pending, approved, or rejected")
}
}
// AssessmentLifecycle is the publication state of a family version.
type AssessmentLifecycle string
const (
// AssessmentLifecycleDraft is an imported version that candidates never
// see.
AssessmentLifecycleDraft AssessmentLifecycle = "draft"
// AssessmentLifecyclePublished is a reviewed version that counts for
// coverage.
AssessmentLifecyclePublished AssessmentLifecycle = "published"
// AssessmentLifecycleRetired is a version withdrawn from the bank.
AssessmentLifecycleRetired AssessmentLifecycle = "retired"
)
func ParseAssessmentLifecycle(value string) (AssessmentLifecycle, error) {
lifecycle := AssessmentLifecycle(value)
switch lifecycle {
case AssessmentLifecycleDraft, AssessmentLifecyclePublished, AssessmentLifecycleRetired:
return lifecycle, nil
default:
return "", invalidAssessmentFamily("domain.ParseAssessmentLifecycle", "lifecycle must be draft, published, or retired")
}
}
// AssessmentAnswerKey is the reference answer description of a family. The
// reference answer of a variant itself comes from the family's algorithm.
type AssessmentAnswerKey struct {
// AnswerFormat is the format of the reference answer: "integer" or
// "integer_sequence". It must match the algorithm of the generator.
AnswerFormat string `json:"answer_format"`
// ReferenceSolution describes the reference approach in prose.
ReferenceSolution string `json:"reference_solution"`
}
// AssessmentRubricCriterion is one thing a reviewer or grader looks for.
// A criterion has no points: how criteria become a grade is a matter of the
// versioned grading policy, not of the family.
type AssessmentRubricCriterion struct {
ID string `json:"id"`
Description string `json:"description"`
}
// AssessmentRubric is the rubric of a family. Its principle does not depend
// on the seed of a variant.
type AssessmentRubric struct {
Principle string `json:"principle"`
Criteria []AssessmentRubricCriterion `json:"criteria"`
}
func (rubric AssessmentRubric) clone() AssessmentRubric {
copied := rubric
copied.Criteria = append([]AssessmentRubricCriterion(nil), rubric.Criteria...)
return copied
}
func (rubric AssessmentRubric) validate(location string) error {
if err := checkAssessmentText(location, "rubric principle", rubric.Principle); err != nil {
return err
}
if len(rubric.Criteria) == 0 || len(rubric.Criteria) > maxAssessmentRubricCriteria {
return invalidAssessmentFamily(location, fmt.Sprintf("rubric must have 1 to %d criteria", maxAssessmentRubricCriteria))
}
seen := make(map[string]bool, len(rubric.Criteria))
for _, criterion := range rubric.Criteria {
if len(criterion.ID) > maxAssessmentCriterionIDSize || !assessmentCriterionIDPattern.MatchString(criterion.ID) {
return invalidAssessmentFamily(location, "rubric criterion ID must be lowercase letters, digits, or '_', starting with a letter")
}
if seen[criterion.ID] {
return invalidAssessmentFamily(location, "rubric criterion IDs must be unique")
}
seen[criterion.ID] = true
if err := checkAssessmentText(location, "rubric criterion description", criterion.Description); err != nil {
return err
}
}
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")
}
return checkAssessmentText(location, "reference solution", key.ReferenceSolution)
}
// checkAssessmentText accepts non-empty text without surrounding blanks, and
// without control characters other than line breaks and without Unicode
// format characters (category Cf) and line and paragraph separators (Zl, Zp).
func checkAssessmentText(location, field, value string) error {
trimmed := strings.TrimSpace(value)
if trimmed == "" || trimmed != value || len(value) > maxAssessmentTextLength {
return invalidAssessmentFamily(location, fmt.Sprintf("%s must be 1 to %d bytes without surrounding blanks", field, maxAssessmentTextLength))
}
for _, character := range value {
if unicode.IsControl(character) && character != '\n' {
return invalidAssessmentFamily(location, field+" must not contain control characters")
}
// Format characters, such as the bidirectional overrides, change how
// text is displayed without being visible, and the line and
// paragraph separators U+2028 and U+2029 break lines in ways that
// plain text does not expect.
if unicode.In(character, unicode.Cf, unicode.Zl, unicode.Zp) {
return invalidAssessmentFamily(location, field+" must not contain invisible format characters or line and paragraph separators")
}
}
return nil
}
// AssessmentFamilyCore holds the immutable content of one family version as
// the importer supplies it.
type AssessmentFamilyCore struct {
Key AssessmentFamilyKey
Version int32
Category AssessmentCategory
Specialization AssessmentSpecialization
Title string
BundleName AssessmentBundleName
Author AssessmentAuthor
// Reviewer is empty while the review is pending.
Reviewer AssessmentOperator
ReviewStatus AssessmentReviewStatus
Generator AssessmentSeedGenerator
AnswerKey AssessmentAnswerKey
Rubric AssessmentRubric
}
// NewAssessmentFamilyDraftInput is the input of NewAssessmentFamilyDraft.
type NewAssessmentFamilyDraftInput = AssessmentFamilyCore
func (core AssessmentFamilyCore) clone() AssessmentFamilyCore {
copied := core
copied.Generator = core.Generator.clone()
copied.Rubric = core.Rubric.clone()
return copied
}
// validate checks every field and the rules between them. probe asks the
// generator to render probe variants, which an importer does and a read of a
// stored row does not. The review rules
// mirror the CHECK constraints of assessment_families: a review is pending
// exactly while no reviewer is recorded, and the reviewer is never the
// author.
func (core AssessmentFamilyCore) validate(location string, probe bool) error {
if _, err := ParseAssessmentFamilyKey(string(core.Key)); err != nil {
return fmt.Errorf("%s - validate key: %w", location, err)
}
if core.Version <= 0 {
return invalidAssessmentFamily(location, "version must be positive")
}
if _, err := ParseAssessmentCategory(string(core.Category)); err != nil {
return fmt.Errorf("%s - validate category: %w", location, err)
}
if _, err := ParseAssessmentSpecialization(string(core.Specialization)); err != nil {
return fmt.Errorf("%s - validate specialization: %w", location, err)
}
if _, err := ParseAssessmentBundleName(string(core.BundleName)); err != nil {
return fmt.Errorf("%s - validate bundle name: %w", location, err)
}
if _, err := ParseAssessmentAuthor(string(core.Author)); err != nil {
return fmt.Errorf("%s - validate author: %w", location, err)
}
if len(core.Title) > maxAssessmentTitleLength || strings.Contains(core.Title, "\n") ||
checkAssessmentText(location, "title", core.Title) != nil {
return invalidAssessmentFamily(location, "title must be one line of 1 to 200 bytes without surrounding blanks")
}
if err := core.validateReview(location); err != nil {
return err
}
algorithm, err := core.Generator.validate(location, probe)
if err != nil {
return err
}
if err := core.AnswerKey.validate(location, algorithm); err != nil {
return err
}
return core.Rubric.validate(location)
}
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)
}
if core.ReviewStatus == AssessmentReviewPending {
if core.Reviewer != "" {
return invalidAssessmentFamily(location, "a pending review has no reviewer")
}
return nil
}
if _, err := ParseAssessmentOperator(string(core.Reviewer)); err != nil {
return fmt.Errorf("%s - validate reviewer: %w", location, err)
}
if string(core.Reviewer) == string(core.Author) {
return invalidAssessmentFamily(location, "the reviewer must not be the author")
}
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
// 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,
}
// 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 {
Key AssessmentFamilyKey `json:"family_key"`
Version int32 `json:"version"`
Category AssessmentCategory `json:"category"`
Specialization AssessmentSpecialization `json:"specialization"`
Title string `json:"title"`
Author AssessmentAuthor `json:"author"`
Reviewer AssessmentOperator `json:"reviewer,omitempty"`
ReviewStatus AssessmentReviewStatus `json:"review_status"`
Generator AssessmentSeedGenerator `json:"seed_generator"`
AnswerKey AssessmentAnswerKey `json:"answer_key"`
Rubric AssessmentRubric `json:"rubric"`
}
// AssessmentContentHash is the SHA-256 of the canonical content.
type AssessmentContentHash [sha256.Size]byte
// contentHash hashes the content with the named scheme, or returns
// ErrInvalidAssessmentFamily for a scheme that this code does not know.
func (core AssessmentFamilyCore) contentHash(scheme int16) (AssessmentContentHash, error) {
hashContent, ok := assessmentHashSchemes[scheme]
if !ok {
return AssessmentContentHash{}, invalidAssessmentFamily("AssessmentFamilyCore.contentHash", "hash scheme is unknown")
}
return hashContent(core)
}
func contentHashV1(core AssessmentFamilyCore) (AssessmentContentHash, error) {
encoded, err := json.Marshal(assessmentCanonicalContentV1{
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,
})
if err != nil {
return AssessmentContentHash{}, fmt.Errorf("domain.contentHashV1 - encode canonical content: %w", err)
}
return sha256.Sum256(encoded), nil
}
// AssessmentFamilyDraft is a version that is not stored yet. It has an ID, a
// validated content, and its hash, but no creation time: the database sets
// that. Every stored version starts as a draft, whatever its review says.
type AssessmentFamilyDraft struct {
id AssessmentFamilyID
core AssessmentFamilyCore
hash AssessmentContentHash
scheme int16
}
// NewAssessmentFamilyDraft validates the content, hashes it, and assigns a
// UUIDv7. The family can be generated for review before it is published.
func NewAssessmentFamilyDraft(input NewAssessmentFamilyDraftInput) (AssessmentFamilyDraft, error) {
const location = "domain.NewAssessmentFamilyDraft"
core := input.clone()
if err := core.validate(location, true); err != nil {
return AssessmentFamilyDraft{}, err
}
hash, err := core.contentHash(currentAssessmentHashScheme)
if err != nil {
return AssessmentFamilyDraft{}, err
}
id, err := NewAssessmentFamilyID()
if err != nil {
return AssessmentFamilyDraft{}, fmt.Errorf("%s - assign ID: %w", location, err)
}
return AssessmentFamilyDraft{id: id, core: core, hash: hash, scheme: currentAssessmentHashScheme}, nil
}
func (draft AssessmentFamilyDraft) ID() AssessmentFamilyID { return draft.id }
// Core returns a copy of the content.
func (draft AssessmentFamilyDraft) Core() AssessmentFamilyCore { return draft.core.clone() }
func (draft AssessmentFamilyDraft) ContentHash() AssessmentContentHash { return draft.hash }
// HashScheme is the scheme of ContentHash, stored beside it.
func (draft AssessmentFamilyDraft) HashScheme() int16 { return draft.scheme }
// IsZero reports a draft not built by NewAssessmentFamilyDraft.
func (draft AssessmentFamilyDraft) IsZero() bool { return draft.id.IsZero() }
// SeedGeneratorJSON returns the canonical document stored in the
// seed_generator column.
func (draft AssessmentFamilyDraft) SeedGeneratorJSON() ([]byte, error) {
return marshalAssessmentDocument("AssessmentFamilyDraft.SeedGeneratorJSON", draft.core.Generator)
}
// AnswerKeyJSON returns the canonical document stored in the answer_key
// column.
func (draft AssessmentFamilyDraft) AnswerKeyJSON() ([]byte, error) {
return marshalAssessmentDocument("AssessmentFamilyDraft.AnswerKeyJSON", draft.core.AnswerKey)
}
// RubricJSON returns the canonical document stored in the rubric column.
func (draft AssessmentFamilyDraft) RubricJSON() ([]byte, error) {
return marshalAssessmentDocument("AssessmentFamilyDraft.RubricJSON", draft.core.Rubric)
}
func marshalAssessmentDocument(location string, value any) ([]byte, error) {
encoded, err := json.Marshal(value)
if err != nil {
return nil, fmt.Errorf("%s - encode document: %w", location, err)
}
return encoded, nil
}
// StoredAssessmentFamily is an assessment_families row as storage reads it.
// Reviewer, PublishedBy, and RetiredBy are empty for a NULL column, and a
// zero PublishedAt or RetiredAt means NULL.
type StoredAssessmentFamily struct {
ID AssessmentFamilyID
FamilyKey string
Version int32
Category string
Specialization string
Title string
BundleName string
Author string
Reviewer string
ReviewStatus string
SeedGenerator []byte
AnswerKey []byte
Rubric []byte
ContentHash []byte
HashScheme int16
Lifecycle string
CreatedAt time.Time
PublishedAt time.Time
PublishedBy string
RetiredAt time.Time
RetiredBy string
}
// AssessmentFamily is one stored, immutable version of a family. Only
// RestoreAssessmentFamily builds it; accessors return copies.
type AssessmentFamily struct {
id AssessmentFamilyID
core AssessmentFamilyCore
hash AssessmentContentHash
scheme int16
lifecycle AssessmentLifecycle
createdAt time.Time
publishedAt time.Time
publishedBy AssessmentOperator
retiredAt time.Time
retiredBy AssessmentOperator
}
// RestoreAssessmentFamily rebuilds a stored version. It decodes every
// document strictly, validates the content like NewAssessmentFamilyDraft,
// and requires the SHA-256 of the canonical content, built with the scheme
// that the row names, to equal the stored hash; otherwise it returns
// ErrAssessmentFamilyIntegrity, and an unknown scheme returns
// ErrInvalidAssessmentFamily. jsonb normalizes
// stored text, so the hash is never compared with stored bytes directly.
func RestoreAssessmentFamily(stored StoredAssessmentFamily) (AssessmentFamily, error) {
const location = "domain.RestoreAssessmentFamily"
if stored.ID.IsZero() {
return AssessmentFamily{}, invalidAssessmentFamily(location, "ID must not be nil")
}
lifecycle, err := ParseAssessmentLifecycle(stored.Lifecycle)
if err != nil {
return AssessmentFamily{}, fmt.Errorf("%s - parse lifecycle: %w", location, err)
}
if stored.CreatedAt.IsZero() {
return AssessmentFamily{}, invalidAssessmentFamily(location, "creation time must be set")
}
core := AssessmentFamilyCore{
Key: AssessmentFamilyKey(stored.FamilyKey),
Version: stored.Version,
Category: AssessmentCategory(stored.Category),
Specialization: AssessmentSpecialization(stored.Specialization),
Title: stored.Title,
BundleName: AssessmentBundleName(stored.BundleName),
Author: AssessmentAuthor(stored.Author),
Reviewer: AssessmentOperator(stored.Reviewer),
ReviewStatus: AssessmentReviewStatus(stored.ReviewStatus),
}
if err := decodeAssessmentDocument(stored.SeedGenerator, &core.Generator); err != nil {
return AssessmentFamily{}, fmt.Errorf("%s - decode seed generator: %w", location, err)
}
if err := decodeAssessmentDocument(stored.AnswerKey, &core.AnswerKey); err != nil {
return AssessmentFamily{}, fmt.Errorf("%s - decode answer key: %w", location, err)
}
if err := decodeAssessmentDocument(stored.Rubric, &core.Rubric); err != nil {
return AssessmentFamily{}, fmt.Errorf("%s - decode rubric: %w", location, err)
}
if err := core.validate(location, false); err != nil {
return AssessmentFamily{}, err
}
hash, err := core.contentHash(stored.HashScheme)
if err != nil {
return AssessmentFamily{}, fmt.Errorf("%s - hash content: %w", location, err)
}
if len(stored.ContentHash) != len(hash) || subtle.ConstantTimeCompare(stored.ContentHash, hash[:]) != 1 {
return AssessmentFamily{}, fmt.Errorf("%s - verify content hash: %w", location, ErrAssessmentFamilyIntegrity)
}
if err := checkLifecycleStamps(location, lifecycle, core, stored); err != nil {
return AssessmentFamily{}, err
}
for _, actor := range []string{stored.PublishedBy, stored.RetiredBy} {
if actor == "" {
continue
}
if _, err := ParseAssessmentOperator(actor); err != nil {
return AssessmentFamily{}, fmt.Errorf("%s - parse publishing operator: %w", location, err)
}
}
return AssessmentFamily{
id: stored.ID,
core: core,
hash: hash,
scheme: stored.HashScheme,
lifecycle: lifecycle,
createdAt: stored.CreatedAt,
publishedAt: stored.PublishedAt,
publishedBy: AssessmentOperator(stored.PublishedBy),
retiredAt: stored.RetiredAt,
retiredBy: AssessmentOperator(stored.RetiredBy),
}, nil
}
func checkLifecycleStamps(location string, lifecycle AssessmentLifecycle, core AssessmentFamilyCore, stored StoredAssessmentFamily) error {
published, retired := !stored.PublishedAt.IsZero(), !stored.RetiredAt.IsZero()
if published != (stored.PublishedBy != "") || retired != (stored.RetiredBy != "") {
return invalidAssessmentFamily(location, "a publication or retirement time comes with the operator who made it, and only with it")
}
switch {
case lifecycle == AssessmentLifecycleDraft && (published || retired):
return invalidAssessmentFamily(location, "a draft has no publication or retirement time")
case lifecycle == AssessmentLifecyclePublished && (!published || retired):
return invalidAssessmentFamily(location, "a published version has a publication time and no retirement time")
case lifecycle == AssessmentLifecycleRetired && (!published || !retired):
return invalidAssessmentFamily(location, "a retired version has publication and retirement times")
case lifecycle != AssessmentLifecycleDraft && core.ReviewStatus != AssessmentReviewApproved:
return invalidAssessmentFamily(location, "a published or retired version needs an approved review")
}
return nil
}
// decodeAssessmentDocument decodes one JSON document strictly: an unknown
// field or trailing data is an error, so a document of a different layout
// never decodes into a partly empty value.
func decodeAssessmentDocument(document []byte, target any) error {
decoder := json.NewDecoder(bytes.NewReader(document))
decoder.DisallowUnknownFields()
if err := decoder.Decode(target); err != nil {
return fmt.Errorf("%w: %w", ErrInvalidAssessmentFamily, err)
}
if decoder.More() {
return fmt.Errorf("%w: trailing data after the document", ErrInvalidAssessmentFamily)
}
return nil
}
func (family AssessmentFamily) ID() AssessmentFamilyID { return family.id }
// Core returns a copy of the content.
func (family AssessmentFamily) Core() AssessmentFamilyCore { return family.core.clone() }
func (family AssessmentFamily) Key() AssessmentFamilyKey { return family.core.Key }
func (family AssessmentFamily) Version() int32 { return family.core.Version }
func (family AssessmentFamily) Category() AssessmentCategory { return family.core.Category }
func (family AssessmentFamily) Author() AssessmentAuthor { return family.core.Author }
// Reviewer is empty while the review is pending.
func (family AssessmentFamily) Reviewer() AssessmentOperator { return family.core.Reviewer }
func (family AssessmentFamily) ReviewStatus() AssessmentReviewStatus { return family.core.ReviewStatus }
func (family AssessmentFamily) AnswerKey() AssessmentAnswerKey { return family.core.AnswerKey }
// Rubric returns a copy of the rubric.
func (family AssessmentFamily) Rubric() AssessmentRubric { return family.core.Rubric.clone() }
func (family AssessmentFamily) ContentHash() AssessmentContentHash { return family.hash }
// HashScheme is the scheme that ContentHash was verified with.
func (family AssessmentFamily) HashScheme() int16 { return family.scheme }
func (family AssessmentFamily) Lifecycle() AssessmentLifecycle { return family.lifecycle }
func (family AssessmentFamily) CreatedAt() time.Time { return family.createdAt }
// PublishedAt returns the publication time, or false for a draft.
func (family AssessmentFamily) PublishedAt() (time.Time, bool) {
return family.publishedAt, !family.publishedAt.IsZero()
}
// PublishedBy is the operator who published the version, or empty for a
// draft. It is a declared value of the caller, not an authenticated identity,
// until operator accounts exist.
func (family AssessmentFamily) PublishedBy() AssessmentOperator { return family.publishedBy }
// RetiredBy is the operator who retired the version, or empty.
func (family AssessmentFamily) RetiredBy() AssessmentOperator { return family.retiredBy }
// IsZero reports an AssessmentFamily not built by RestoreAssessmentFamily.
func (family AssessmentFamily) IsZero() bool { return family.id.IsZero() }
// CheckPublishable reports why the version cannot be published, or nil. A
// version is published only while it is a draft and only with an approved
// review by a reviewer who is not its author. The database enforces the same
// rules.
func (family AssessmentFamily) CheckPublishable() error {
switch {
case family.lifecycle != AssessmentLifecycleDraft:
return NewAssessmentRefusal(RefusalNotDraft, "only a draft version can be published")
case family.core.Reviewer == "":
return NewAssessmentRefusal(RefusalReviewerMissing, "the version has no independent reviewer")
case family.core.ReviewStatus != AssessmentReviewApproved:
return NewAssessmentRefusal(RefusalReviewNotApproved, "the review of the version is not approved")
default:
return nil
}
}
// CheckRetirable reports why the version cannot be retired, or nil.
func (family AssessmentFamily) CheckRetirable() error {
if family.lifecycle != AssessmentLifecyclePublished {
return NewAssessmentRefusal(RefusalNotPublished, "only a published version can be retired")
}
return nil
}
// RequiredPublishedAssessmentFamilies returns how many distinct published
// families a category needs under a grading policy: max_scored_items plus
// seed_items of the stop rule. The owner accepted this rule on 2026-10-06.
// The reason: a family gives at most one item to an attempt, so a full
// adaptive attempt, which can run to the maximum of scored items and also
// carries the seed items, cannot run out of families. Both numbers are read
// from the policy; the bank defines no threshold of its own, and a policy
// without them is refused with RefusalGradingPolicyMissing. The trigger of
// assessment_category_openings reads the same two document paths; an
// integration test keeps them equal.
func RequiredPublishedAssessmentFamilies(policy ProductPolicy) (int32, error) {
rule := policy.Assessment.StopRule
if rule.MaxScoredItems <= 0 || rule.SeedItems < 0 {
return 0, NewAssessmentRefusal(RefusalGradingPolicyMissing, "the grading policy has no maximum of scored items")
}
return rule.MaxScoredItems + rule.SeedItems, nil
}
// AssessmentCategoryOpeningDraft is an opening that is not stored yet.
type AssessmentCategoryOpeningDraft struct {
id uuid.UUID
category AssessmentCategory
policyVersionID PolicyVersionID
openedBy AssessmentOperator
requiredFamilies int32
}
// NewAssessmentCategoryOpeningDraft checks that a category can open under the
// referenced grading policy version and returns the opening to store. It
// refuses with RefusalGradingPolicyMissing without a policy version and with
// RefusalCoverageInsufficient when the published families do not reach the
// policy's requirement. publishedFamilies is the count of distinct families
// with a published version.
func NewAssessmentCategoryOpeningDraft(
category AssessmentCategory,
policy PolicyVersion,
publishedFamilies int32,
openedBy AssessmentOperator,
) (AssessmentCategoryOpeningDraft, error) {
const location = "domain.NewAssessmentCategoryOpeningDraft"
if _, err := ParseAssessmentCategory(string(category)); err != nil {
return AssessmentCategoryOpeningDraft{}, fmt.Errorf("%s - validate category: %w", location, err)
}
if _, err := ParseAssessmentOperator(string(openedBy)); err != nil {
return AssessmentCategoryOpeningDraft{}, fmt.Errorf("%s - validate operator: %w", location, err)
}
if policy.IsZero() {
return AssessmentCategoryOpeningDraft{}, NewAssessmentRefusal(RefusalGradingPolicyMissing, "a category opens only under a versioned grading policy")
}
required, err := RequiredPublishedAssessmentFamilies(policy.Policy())
if err != nil {
return AssessmentCategoryOpeningDraft{}, err
}
if publishedFamilies < required {
return AssessmentCategoryOpeningDraft{}, NewAssessmentRefusal(RefusalCoverageInsufficient,
fmt.Sprintf("category has %d published families, grading policy version %d requires %d", publishedFamilies, policy.Version(), required))
}
id, err := uuid.NewV7()
if err != nil {
return AssessmentCategoryOpeningDraft{}, fmt.Errorf("%s - assign ID: %w", location, err)
}
return AssessmentCategoryOpeningDraft{
id: id, category: category, policyVersionID: policy.ID(), openedBy: openedBy, requiredFamilies: required,
}, nil
}
func (draft AssessmentCategoryOpeningDraft) ID() uuid.UUID { return draft.id }
func (draft AssessmentCategoryOpeningDraft) Category() AssessmentCategory { return draft.category }
func (draft AssessmentCategoryOpeningDraft) PolicyVersionID() PolicyVersionID {
return draft.policyVersionID
}
func (draft AssessmentCategoryOpeningDraft) OpenedBy() AssessmentOperator { return draft.openedBy }
func (draft AssessmentCategoryOpeningDraft) RequiredFamilies() int32 { return draft.requiredFamilies }
// IsZero reports a draft not built by NewAssessmentCategoryOpeningDraft.
func (draft AssessmentCategoryOpeningDraft) IsZero() bool { return draft.id == uuid.Nil }
// AssessmentCategoryOpening is a stored opening: the proof that a category
// was available at OpenedAt under one policy version.
type AssessmentCategoryOpening struct {
ID uuid.UUID
Category AssessmentCategory
PolicyVersionID PolicyVersionID
OpenedBy AssessmentOperator
RequiredFamilies int32
PublishedFamilies int32
OpenedAt time.Time
}
@@ -0,0 +1,357 @@
package domain
import (
"errors"
"slices"
"strings"
"testing"
"time"
)
var testAssessmentCreatedAt = time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
func testAssessmentInput() NewAssessmentFamilyDraftInput {
return NewAssessmentFamilyDraftInput{
Key: "unit-test-family",
Version: 1,
Category: "unit-category",
Specialization: "unit-domain",
Title: "Unit test family",
BundleName: "unit-test-bundle",
Author: "ai:unit-test",
ReviewStatus: AssessmentReviewPending,
Generator: AssessmentSeedGenerator{
Algorithm: "lru_hits.v1",
Parameters: map[string]AssessmentParameterRange{
"accesses": {Min: 10, Max: 30},
"keys": {Min: 3, Max: 8},
"capacity": {Min: 2, Max: 4},
},
StatementTemplate: "Capacity {{.capacity}}, reads {{.sequence}}.",
},
AnswerKey: AssessmentAnswerKey{AnswerFormat: AnswerFormatInteger, ReferenceSolution: "Simulate the cache."},
Rubric: AssessmentRubric{
Principle: "Compare with the reference answer.",
Criteria: []AssessmentRubricCriterion{{ID: "correct_answer", Description: "Matches the reference answer."}},
},
}
}
func storedAssessmentFrom(t *testing.T, draft AssessmentFamilyDraft) StoredAssessmentFamily {
t.Helper()
generator, err := draft.SeedGeneratorJSON()
if err != nil {
t.Fatalf("SeedGeneratorJSON() error = %v", err)
}
key, err := draft.AnswerKeyJSON()
if err != nil {
t.Fatalf("AnswerKeyJSON() error = %v", err)
}
rubric, err := draft.RubricJSON()
if err != nil {
t.Fatalf("RubricJSON() error = %v", err)
}
core, hash := draft.Core(), draft.ContentHash()
return StoredAssessmentFamily{
ID: draft.ID(), FamilyKey: string(core.Key), Version: core.Version, Category: string(core.Category),
Specialization: string(core.Specialization), Title: core.Title, BundleName: string(core.BundleName),
Author: string(core.Author), Reviewer: string(core.Reviewer), ReviewStatus: string(core.ReviewStatus),
SeedGenerator: generator, AnswerKey: key, Rubric: rubric, ContentHash: hash[:], HashScheme: draft.HashScheme(),
Lifecycle: string(AssessmentLifecycleDraft), CreatedAt: testAssessmentCreatedAt,
}
}
func restoreAssessment(t *testing.T, input NewAssessmentFamilyDraftInput) AssessmentFamily {
t.Helper()
draft, err := NewAssessmentFamilyDraft(input)
if err != nil {
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
}
family, err := RestoreAssessmentFamily(storedAssessmentFrom(t, draft))
if err != nil {
t.Fatalf("RestoreAssessmentFamily() error = %v", err)
}
return family
}
func TestNewAssessmentFamilyDraftRejectsInvalidContent(t *testing.T) {
tests := map[string]func(*NewAssessmentFamilyDraftInput){
"zero version": func(input *NewAssessmentFamilyDraftInput) { input.Version = 0 },
"bad family key": func(input *NewAssessmentFamilyDraftInput) { input.Key = "Bad Key" },
"bad category": func(input *NewAssessmentFamilyDraftInput) { input.Category = "x" },
"AI author cannot be reviewer": func(input *NewAssessmentFamilyDraftInput) {
input.Reviewer, input.ReviewStatus = "ai:unit-test", AssessmentReviewApproved
},
"pending review with reviewer": func(input *NewAssessmentFamilyDraftInput) { input.Reviewer = "operator:reviewer" },
"approved review without person": func(input *NewAssessmentFamilyDraftInput) { input.ReviewStatus = AssessmentReviewApproved },
"reviewer is the author": func(input *NewAssessmentFamilyDraftInput) {
input.Author, input.Reviewer, input.ReviewStatus = "operator:same", "operator:same", AssessmentReviewApproved
},
"unknown review status": func(input *NewAssessmentFamilyDraftInput) { input.ReviewStatus = "done" },
"unknown algorithm": func(input *NewAssessmentFamilyDraftInput) { input.Generator.Algorithm = "nope.v1" },
"missing parameter": func(input *NewAssessmentFamilyDraftInput) { delete(input.Generator.Parameters, "keys") },
"parameter out of bounds": func(input *NewAssessmentFamilyDraftInput) {
input.Generator.Parameters["capacity"] = AssessmentParameterRange{Min: 1, Max: 51}
},
"inverted parameter range": func(input *NewAssessmentFamilyDraftInput) {
input.Generator.Parameters["capacity"] = AssessmentParameterRange{Min: 4, Max: 2}
},
"template names unknown data": func(input *NewAssessmentFamilyDraftInput) { input.Generator.StatementTemplate = "{{.missing}}" },
"answer format mismatch": func(input *NewAssessmentFamilyDraftInput) { input.AnswerKey.AnswerFormat = AnswerFormatIntegerSequence },
"empty rubric": func(input *NewAssessmentFamilyDraftInput) { input.Rubric.Criteria = nil },
"duplicate criterion": func(input *NewAssessmentFamilyDraftInput) {
input.Rubric.Criteria = append(input.Rubric.Criteria, input.Rubric.Criteria[0])
},
"multi-line title": func(input *NewAssessmentFamilyDraftInput) { input.Title = "a\nb" },
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
input := testAssessmentInput()
mutate(&input)
if _, err := NewAssessmentFamilyDraft(input); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("NewAssessmentFamilyDraft() error = %v, want ErrInvalidAssessmentFamily", err)
}
})
}
}
func TestNewAssessmentFamilyDraftDoesNotShareInputMaps(t *testing.T) {
input := testAssessmentInput()
draft, err := NewAssessmentFamilyDraft(input)
if err != nil {
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
}
input.Generator.Parameters["capacity"] = AssessmentParameterRange{Min: 1, Max: 1}
if got := draft.Core().Generator.Parameters["capacity"]; got.Min != 2 || got.Max != 4 {
t.Fatalf("draft capacity range = %+v after the input changed, want 2 to 4", got)
}
}
func TestRestoreAssessmentFamilyDetectsChangedContent(t *testing.T) {
draft, err := NewAssessmentFamilyDraft(testAssessmentInput())
if err != nil {
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
}
stored := storedAssessmentFrom(t, draft)
stored.AnswerKey = []byte(strings.Replace(string(stored.AnswerKey), "Simulate the cache.", "Guess.", 1))
if _, err := RestoreAssessmentFamily(stored); !errors.Is(err, ErrAssessmentFamilyIntegrity) {
t.Fatalf("RestoreAssessmentFamily() error = %v, want ErrAssessmentFamilyIntegrity", err)
}
stored = storedAssessmentFrom(t, draft)
stored.Rubric = []byte(`{"principle":"x","criteria":[],"extra":1}`)
if _, err := RestoreAssessmentFamily(stored); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("RestoreAssessmentFamily(unknown field) error = %v, want ErrInvalidAssessmentFamily", err)
}
stored = storedAssessmentFrom(t, draft)
stored.Lifecycle = string(AssessmentLifecyclePublished)
stored.PublishedAt = testAssessmentCreatedAt
if _, err := RestoreAssessmentFamily(stored); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("RestoreAssessmentFamily(published without review) error = %v, want ErrInvalidAssessmentFamily", err)
}
}
func TestCheckPublishableNamesTheReason(t *testing.T) {
approved := testAssessmentInput()
approved.Reviewer, approved.ReviewStatus = "operator:reviewer", AssessmentReviewApproved
rejected := approved
rejected.ReviewStatus = AssessmentReviewRejected
tests := []struct {
name string
input NewAssessmentFamilyDraftInput
want AssessmentRefusalReason
}{
{name: "pending review has no reviewer", input: testAssessmentInput(), want: RefusalReviewerMissing},
{name: "rejected review", input: rejected, want: RefusalReviewNotApproved},
{name: "approved review", input: approved},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := restoreAssessment(t, test.input).CheckPublishable()
if test.want == "" {
if err != nil {
t.Fatalf("CheckPublishable() error = %v, want nil", err)
}
return
}
var refusal *AssessmentRefusalError
if !errors.Is(err, ErrAssessmentRefused) || !errors.As(err, &refusal) || refusal.Reason != test.want {
t.Fatalf("CheckPublishable() error = %v, want refusal %s", err, test.want)
}
})
}
}
func TestNewVariantIsDeterministicAndKeepsTheRubric(t *testing.T) {
family := restoreAssessment(t, testAssessmentInput())
first, err := family.NewVariant(7)
if err != nil {
t.Fatalf("NewVariant(7) error = %v", err)
}
second, err := family.NewVariant(7)
if err != nil {
t.Fatalf("NewVariant(7) again error = %v", err)
}
if first.Statement != second.Statement || first.ReferenceAnswer != second.ReferenceAnswer {
t.Fatalf("variants of seed 7 differ:\n%q %q\n%q %q", first.Statement, first.ReferenceAnswer, second.Statement, second.ReferenceAnswer)
}
statements := map[string]bool{}
for seed := VariantSeed(0); seed < 20; seed++ {
variant, err := family.NewVariant(seed)
if err != nil {
t.Fatalf("NewVariant(%d) error = %v", seed, err)
}
statements[variant.Statement] = true
if !slices.Equal(variant.Rubric.Criteria, first.Rubric.Criteria) || variant.Rubric.Principle != first.Rubric.Principle {
t.Fatalf("rubric of seed %d differs from the rubric of seed 7", seed)
}
}
if len(statements) < 15 {
t.Fatalf("20 seeds produced %d distinct statements, want a spread of variants", len(statements))
}
}
func TestEveryRegisteredAlgorithmBuildsVariantsInsideItsBounds(t *testing.T) {
for name, algorithm := range assessmentAlgorithms {
t.Run(name, func(t *testing.T) {
parameters := map[string]AssessmentParameterRange{}
var template strings.Builder
for _, spec := range algorithm.parameters {
parameters[spec.name] = AssessmentParameterRange{Min: spec.lowest, Max: spec.highest}
template.WriteString("{{." + spec.name + "}} ")
}
for _, data := range algorithm.dataNames {
template.WriteString("{{." + data + "}} ")
}
generator := AssessmentSeedGenerator{Algorithm: name, Parameters: parameters, StatementTemplate: strings.TrimSpace(template.String())}
for seed := VariantSeed(0); seed < 5; seed++ {
statement, err := compileStatementTemplate("test", generator.StatementTemplate, algorithm)
if err != nil {
t.Fatalf("compileStatementTemplate() error = %v", err)
}
body, err := generator.instantiate(algorithm, statement, nil, seed)
if err != nil {
t.Fatalf("instantiate(seed %d) error = %v", seed, err)
}
if body.answer == "" {
t.Fatalf("seed %d produced an empty reference answer", seed)
}
}
})
}
}
func TestReferenceSolvers(t *testing.T) {
t.Run("rate limiter", func(t *testing.T) {
// Limit 2 per half-open window of 5 seconds. Accepted: 0, 1; 2, 3, 4
// rejected; 5 is accepted because 0 left the window (5-5 = 0 is not
// in (0, 5]); 6 is accepted because 1 left; 7 is rejected.
got := rateLimitRejected([]int{0, 1, 2, 3, 4, 5, 6, 7}, 5, 2)
if got != 4 {
t.Fatalf("rateLimitRejected() = %d, want 4", got)
}
if got := rateLimitRejected([]int{3, 3, 3}, 1, 3); got != 0 {
t.Fatalf("rateLimitRejected(burst within the limit) = %d, want 0", got)
}
})
t.Run("duplicate window", func(t *testing.T) {
// Key 0 at 0 is processed; at 2 it is dropped (2 < 3); at 3 it is
// processed again because the dropped one did not extend the period.
got := dedupProcessed([]int{0, 0, 0, 1}, []int{0, 2, 3, 3}, 3)
if got != 3 {
t.Fatalf("dedupProcessed() = %d, want 3", got)
}
})
t.Run("lru cache", func(t *testing.T) {
// Capacity 2: 1 miss, 2 miss, 1 hit (now 1 is recent), 3 miss evicts
// 2, 2 miss evicts 1, 1 miss evicts 3.
got := lruHits([]int{1, 2, 1, 3, 2, 1}, 2)
if got != 1 {
t.Fatalf("lruHits() = %d, want 1", got)
}
})
t.Run("dependency order", func(t *testing.T) {
// 3 before 1, 4 before 2: ready first are 3 and 4, so 3 starts; then
// 1 and 4 are ready, so 1; then 4; then 2.
got := joinInts(smallestDependencyOrder(4, [][2]int{{3, 1}, {4, 2}}))
if got != "3 1 4 2" {
t.Fatalf("smallestDependencyOrder() = %q, want %q", got, "3 1 4 2")
}
})
}
func TestNewAssessmentCategoryOpeningDraftReadsCoverageFromThePolicy(t *testing.T) {
policy := mustRestore(t, storedFrom(mustDraft(t, testDraftInput(), 1)))
required, err := RequiredPublishedAssessmentFamilies(policy.Policy())
if err != nil {
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
}
rule := policy.Policy().Assessment.StopRule
if required != rule.MaxScoredItems+rule.SeedItems {
t.Fatalf("required families = %d, want max_scored_items %d + seed_items %d", required, rule.MaxScoredItems, rule.SeedItems)
}
if _, err := RequiredPublishedAssessmentFamilies(ProductPolicy{}); !errors.Is(err, ErrAssessmentRefused) {
t.Fatalf("RequiredPublishedAssessmentFamilies(no stop rule) error = %v, want a refusal", err)
}
if _, err := NewAssessmentCategoryOpeningDraft("unit-category", policy, required, "operator:opener"); err != nil {
t.Fatalf("NewAssessmentCategoryOpeningDraft(enough coverage) error = %v", err)
}
var refusal *AssessmentRefusalError
_, err = NewAssessmentCategoryOpeningDraft("unit-category", policy, required-1, "operator:opener")
if !errors.As(err, &refusal) || refusal.Reason != RefusalCoverageInsufficient {
t.Fatalf("NewAssessmentCategoryOpeningDraft(too few) error = %v, want coverage refusal", err)
}
_, err = NewAssessmentCategoryOpeningDraft("unit-category", PolicyVersion{}, required, "operator:opener")
if !errors.As(err, &refusal) || refusal.Reason != RefusalGradingPolicyMissing {
t.Fatalf("NewAssessmentCategoryOpeningDraft(no policy) error = %v, want policy refusal", err)
}
if _, err := NewAssessmentCategoryOpeningDraft("unit-category", policy, required, "ai:draft"); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("NewAssessmentCategoryOpeningDraft(AI operator) error = %v, want ErrInvalidAssessmentFamily", err)
}
}
// 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
assessmentHashSchemes[testScheme] = func(core AssessmentFamilyCore) (AssessmentContentHash, error) {
hash, err := contentHashV1(core)
hash[0] ^= 0xff // a different function of the same content
return hash, err
}
t.Cleanup(func() { delete(assessmentHashSchemes, testScheme) })
draft, err := NewAssessmentFamilyDraft(testAssessmentInput())
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)
}
old := storedAssessmentFrom(t, draft)
if family, err := RestoreAssessmentFamily(old); err != nil || family.HashScheme() != 1 {
t.Fatalf("RestoreAssessmentFamily(scheme 1 row) = scheme %d, %v, want a verified row of scheme 1", family.HashScheme(), err)
}
core := draft.Core()
newer, err := core.contentHash(testScheme)
if err != nil {
t.Fatalf("contentHash(scheme 2) 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)
}
// 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)
}
row.HashScheme = 9
if _, err := RestoreAssessmentFamily(row); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("RestoreAssessmentFamily(unknown scheme) error = %v, want ErrInvalidAssessmentFamily", err)
}
}
@@ -0,0 +1,374 @@
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
}
@@ -0,0 +1,273 @@
package domain
import (
"errors"
"fmt"
"strings"
"testing"
"time"
)
// maxRejectionTime is a generous bound for refusing a hostile template. The
// refusal reads at most a few kilobytes and never runs the template, so it
// takes microseconds; a template that was executed would not finish.
const maxRejectionTime = time.Second
func TestStatementTemplateAllowsOnlyPlaceholders(t *testing.T) {
algorithm := assessmentAlgorithms["lru_hits.v1"]
const complete = "{{.capacity}} {{.sequence}}"
tests := map[string]string{
"define": complete + `{{define "x"}}y{{end}}`,
"template call": complete + `{{template "x"}}`,
"block": complete + `{{block "x" .}}y{{end}}`,
"range": complete + `{{range .}}x{{end}}`,
"with": complete + `{{with .capacity}}x{{end}}`,
"if": complete + `{{if .capacity}}x{{end}}`,
"variable": complete + `{{$x := .capacity}}`,
"printf call": complete + `{{printf "%d" 1}}`,
"pipeline": complete + `{{.capacity | len}}`,
"nested field": complete + `{{.capacity.x}}`,
"dot": complete + `{{.}}`,
"string literal": complete + `{{"x"}}`,
"unknown placeholder": complete + `{{.nothing}}`,
"placeholder of another": complete + `{{.timestamps}}`,
"unclosed action": complete + `{{.keys`,
"template above size cap": complete + strings.Repeat("x", maxStatementTemplateBytes),
}
for name, text := range tests {
t.Run(name, func(t *testing.T) {
if _, err := compileStatementTemplate("test", text, algorithm); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("compileStatementTemplate() error = %v, want ErrInvalidAssessmentFamily", err)
}
})
}
if _, err := compileStatementTemplate("test", "Capacity {{.capacity}}; reads {{.sequence}}; keys 1..{{.keys}}.", algorithm); err != nil {
t.Fatalf("compileStatementTemplate(plain placeholders) error = %v", err)
}
}
func TestStatementTemplateBombsAreRefusedFast(t *testing.T) {
algorithm := assessmentAlgorithms["lru_hits.v1"]
// Each template calls the one below it twice: executed, the last of 20
// levels would run about a million bodies.
var nested strings.Builder
nested.WriteString(`{{define "t0"}}x{{end}}`)
for level := 1; level < 20; level++ {
fmt.Fprintf(&nested, `{{define "t%d"}}{{template "t%d"}}{{template "t%d"}}{{end}}`, level, level-1, level-1)
}
nested.WriteString(`{{template "t19"}}`)
// A width of a hundred million spaces from a few bytes of template.
widthBomb := `{{.capacity}} {{.sequence}}{{printf "%99999999d" 1}}`
for name, text := range map[string]string{
"nested define bomb": nested.String(),
"printf width bomb": widthBomb,
"small nested define": `{{.capacity}} {{.sequence}}{{define "a"}}{{template "a"}}{{end}}{{template "a"}}`,
"range over a number": `{{.capacity}} {{.sequence}}{{range 100000000}}x{{end}}`,
"recursive block call": `{{.capacity}} {{.sequence}}{{block "b" .}}{{template "b" .}}{{end}}`,
} {
t.Run(name, func(t *testing.T) {
started := time.Now()
_, err := compileStatementTemplate("test", text, algorithm)
if !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("compileStatementTemplate() error = %v, want ErrInvalidAssessmentFamily", err)
}
if elapsed := time.Since(started); elapsed > maxRejectionTime {
t.Fatalf("compileStatementTemplate() took %s, want a refusal within %s", elapsed, maxRejectionTime)
}
})
}
}
func TestStatementTemplateMustShowTheInput(t *testing.T) {
for name, algorithm := range assessmentAlgorithms {
t.Run(name, func(t *testing.T) {
var all strings.Builder
for _, required := range algorithm.requiredNames {
all.WriteString("{{." + required + "}} ")
}
if _, err := compileStatementTemplate("test", strings.TrimSpace(all.String()), algorithm); err != nil {
t.Fatalf("compileStatementTemplate(all required names) error = %v", err)
}
for index, missing := range algorithm.requiredNames {
var partial strings.Builder
for other, required := range algorithm.requiredNames {
if other != index {
partial.WriteString("{{." + required + "}} ")
}
}
partial.WriteString("Compute the answer.")
if _, err := compileStatementTemplate("test", partial.String(), algorithm); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("compileStatementTemplate(without %s) error = %v, want ErrInvalidAssessmentFamily", missing, err)
}
}
})
}
}
func TestStatementRenderIsBounded(t *testing.T) {
statement := statementTemplate{{literal: strings.Repeat("x", maxStatementBytes)}, {field: "name"}}
if _, err := statement.render(map[string]string{"name": "y"}); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("render(above the bound) error = %v, want ErrInvalidAssessmentFamily", err)
}
if got, err := (statementTemplate{{literal: "a"}, {field: "name"}}).render(map[string]string{"name": "b"}); err != nil || got != "ab" {
t.Fatalf("render() = %q, %v, want %q", got, err, "ab")
}
}
func TestInvisibleFormatCharactersAreRefused(t *testing.T) {
for name, mutate := range map[string]func(*NewAssessmentFamilyDraftInput){
"bidi override in the title": func(input *NewAssessmentFamilyDraftInput) { input.Title = "Cache \u202Etest" },
"zero width space in the title": func(input *NewAssessmentFamilyDraftInput) { input.Title = "Cache\u200Btest" },
"bidi override in the template": func(input *NewAssessmentFamilyDraftInput) { input.Generator.StatementTemplate += "\u202E" },
"format character in the rubric": func(input *NewAssessmentFamilyDraftInput) { input.Rubric.Principle = "Compare\u2066 it." },
"line separator in the title": func(input *NewAssessmentFamilyDraftInput) { input.Title = "Cache\u2028test" },
"paragraph separator in the rubric": func(input *NewAssessmentFamilyDraftInput) {
input.Rubric.Criteria[0].Description = "Matches\u2029the answer."
},
"line separator in the template": func(input *NewAssessmentFamilyDraftInput) { input.Generator.StatementTemplate += "\u2028" },
} {
t.Run(name, func(t *testing.T) {
input := testAssessmentInput()
mutate(&input)
if _, err := NewAssessmentFamilyDraft(input); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("NewAssessmentFamilyDraft() error = %v, want ErrInvalidAssessmentFamily", err)
}
})
}
}
// goldenVariant is one fixed seed of one algorithm with its exact output.
// The statements and answers are the contract that stored families depend
// on: a change of an algorithm that moves any of them must be a new
// versioned algorithm, not an edit.
type goldenVariant struct {
algorithm string
parameters map[string]AssessmentParameterRange
template string
seed VariantSeed
statement string
answer string
}
func TestGoldenVariantsOfEveryAlgorithm(t *testing.T) {
golden := []goldenVariant{
{
algorithm: "rate_limit_window.v1",
parameters: map[string]AssessmentParameterRange{"requests": {Min: 8, Max: 8}, "window": {Min: 4, Max: 4}, "limit": {Min: 2, Max: 2}, "max_gap": {Min: 0, Max: 3}},
template: "n={{.requests}} w={{.window}} l={{.limit}} t={{.timestamps}}",
seed: 12345,
statement: "n=8 w=4 l=2 t=0 0 1 2 2 3 4 6",
answer: "4",
},
{
algorithm: "dedup_window.v1",
parameters: map[string]AssessmentParameterRange{"events": {Min: 8, Max: 8}, "keys": {Min: 3, Max: 3}, "ttl": {Min: 5, Max: 5}, "max_gap": {Min: 1, Max: 3}},
template: "n={{.events}} k={{.keys}} ttl={{.ttl}} s={{.stream}}",
seed: 12345,
statement: "n=8 k=3 ttl=5 s=C@2 A@4 A@6 C@6 C@8 C@9 A@12 A@12",
answer: "4",
},
{
algorithm: "lru_hits.v1",
parameters: map[string]AssessmentParameterRange{"accesses": {Min: 10, Max: 10}, "keys": {Min: 4, Max: 4}, "capacity": {Min: 2, Max: 2}},
template: "n={{.accesses}} k={{.keys}} c={{.capacity}} s={{.sequence}}",
seed: 12345,
statement: "n=10 k=4 c=2 s=4 1 1 1 4 3 4 2 4 2",
answer: "6",
},
{
algorithm: "dependency_order.v1",
parameters: map[string]AssessmentParameterRange{"tasks": {Min: 6, Max: 6}, "links": {Min: 5, Max: 5}},
template: "n={{.tasks}} l={{.links}} d={{.dependencies}}",
seed: 12345,
statement: "n=6 l=5 d=3->4 1->3 2->5 2->3",
answer: "1 2 3 4 5 6",
},
}
for _, want := range golden {
t.Run(want.algorithm, func(t *testing.T) {
input := testAssessmentInput()
input.Generator = AssessmentSeedGenerator{Algorithm: want.algorithm, Parameters: want.parameters, StatementTemplate: want.template}
input.AnswerKey.AnswerFormat = assessmentAlgorithms[want.algorithm].answerFormat
variant, err := restoreAssessment(t, input).NewVariant(want.seed)
if err != nil {
t.Fatalf("NewVariant() error = %v", err)
}
if variant.Statement != want.statement || variant.ReferenceAnswer != want.answer {
t.Fatalf("seed %d of %s:\nstatement %q\nanswer %q\nwant\nstatement %q\nanswer %q",
want.seed, want.algorithm, variant.Statement, variant.ReferenceAnswer, want.statement, want.answer)
}
})
}
}
func TestContentHashOfSchemeOneIsPinned(t *testing.T) {
draft, err := NewAssessmentFamilyDraft(testAssessmentInput())
if err != nil {
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
}
const want = "398d109255623c6bdadfa10974b523ca2f661913061746f0862ffaf1bca5a9d3"
hash := draft.ContentHash()
if got := fmt.Sprintf("%x", hash[:]); got != want {
t.Fatalf("content hash = %s, want %s: a changed canonical layout of scheme 1 needs a new scheme, not an edit", got, want)
}
}
// A template close to the size bound must be judged on the largest inputs
// and on several seeds: here the highest parameter values render within the
// bound for the shortest seed and beyond it for another, and the importer
// refuses the template.
func TestImportProbesSeveralSeedsAtTheLargestInputs(t *testing.T) {
const algorithmName = "dedup_window.v1"
algorithm := assessmentAlgorithms[algorithmName]
parameters := map[string]AssessmentParameterRange{}
highest := map[string]int32{}
for _, spec := range algorithm.parameters {
parameters[spec.name] = AssessmentParameterRange{Min: spec.lowest, Max: spec.highest}
highest[spec.name] = spec.highest
}
generator := AssessmentSeedGenerator{Algorithm: algorithmName, Parameters: parameters}
// The stream placeholder twice, the ttl placeholder once, and a literal
// that is sized below so that the shortest probe seed renders exactly at
// the bound.
body := "{{.stream}} {{.stream}} {{.ttl}}"
statement, err := compileStatementTemplate("test", body, algorithm)
if err != nil {
t.Fatalf("compileStatementTemplate() error = %v", err)
}
shortest, longest := maxStatementBytes*2, 0
for seed := range VariantSeed(probeSeedCount) {
rendered, err := generator.instantiate(algorithm, statement, highest, seed)
if err != nil {
t.Fatalf("instantiate(seed %d) error = %v", seed, err)
}
shortest, longest = min(shortest, len(rendered.statement)), max(longest, len(rendered.statement))
}
if shortest == longest {
t.Skip("every probe seed renders the same size, so the boundary cannot be placed between them")
}
padding := maxStatementBytes - shortest
if padding < 0 || padding+len(body) > maxStatementTemplateBytes {
t.Fatalf("padding %d does not fit the template bound: the test needs another shape", padding)
}
generator.StatementTemplate = strings.Repeat("x", padding) + body
input := testAssessmentInput()
input.Generator = generator
input.AnswerKey.AnswerFormat = algorithm.answerFormat
if _, err := NewAssessmentFamilyDraft(input); !errors.Is(err, ErrInvalidAssessmentFamily) {
t.Fatalf("NewAssessmentFamilyDraft(template at the bound for one seed only) error = %v, want ErrInvalidAssessmentFamily", err)
}
// Rendered with the shortest probe seed alone it would have passed.
for seed := range VariantSeed(probeSeedCount) {
compiled, err := compileStatementTemplate("test", generator.StatementTemplate, algorithm)
if err != nil {
t.Fatalf("compileStatementTemplate(padded) error = %v", err)
}
if rendered, err := generator.instantiate(algorithm, compiled, highest, seed); err == nil && len(rendered.statement) == maxStatementBytes {
return
}
}
t.Fatal("no probe seed renders the padded template exactly at the bound: the boundary test is not exercising the edge")
}