feat(assessment): add table families that pick a variant row by seed
This commit is contained in:
1 parent
f1147b1885
commit
5e1db37746
16 files changed
+1023
-56
No files matched your search
@@ -0,0 +1,37 @@
|
||||
-- +goose Up
|
||||
-- Content hash scheme 2 is the layout of a table generator: a family whose
|
||||
-- variants are rows of a table, with the answers written in the rows. A new
|
||||
-- version of such a family is stored with scheme 2. Scheme 1 stays the layout
|
||||
-- of an algorithmic generator, so existing rows and the hash of every
|
||||
-- algorithmic version are unchanged, and importing one of them again is still
|
||||
-- recognized as the same version.
|
||||
--
|
||||
-- Only the list of known schemes changes. hash_scheme stays one of the
|
||||
-- immutable columns that the guard trigger protects.
|
||||
ALTER TABLE assessment_families
|
||||
DROP CONSTRAINT assessment_families_hash_scheme_known,
|
||||
ADD CONSTRAINT assessment_families_hash_scheme_known CHECK (
|
||||
hash_scheme IN (1, 2)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
-- A stored version never changes and is never removed, so a row of scheme 2
|
||||
-- cannot be given another scheme. The down step refuses while one exists.
|
||||
-- +goose StatementBegin
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM assessment_families WHERE hash_scheme = 2) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'object_not_in_prerequisite_state',
|
||||
MESSAGE = 'table generator families are stored',
|
||||
HINT = 'A stored family version cannot be removed or rehashed; keep migration 00047 applied.';
|
||||
END IF;
|
||||
END
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
ALTER TABLE assessment_families
|
||||
DROP CONSTRAINT assessment_families_hash_scheme_known,
|
||||
ADD CONSTRAINT assessment_families_hash_scheme_known CHECK (
|
||||
hash_scheme IN (1)
|
||||
);
|
||||
@@ -478,6 +478,51 @@ func TestAssessmentBank(t *testing.T) {
|
||||
assertPgError(t, "unknown hash scheme", err, assessmentCheckSQLState, "assessment_families_hash_scheme_known")
|
||||
})
|
||||
|
||||
t.Run("a table family is stored with hash scheme 2 and imports again unchanged", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
bundle := fixture.demoBundle
|
||||
bundle.Name = "table-family-bundle"
|
||||
bundle.Families = choiceTableBankFamilies(t, bundle.Families[0])
|
||||
first, err := fixture.bank.ImportBundle(ctx, bundle)
|
||||
if err != nil || len(first.Created) != 3 || len(first.Unchanged) != 0 {
|
||||
t.Fatalf("ImportBundle(table bundle) = %+v, %v, want three created versions", first, err)
|
||||
}
|
||||
fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE hash_scheme = 2`, 2)
|
||||
fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE hash_scheme = 1`, 1)
|
||||
again, err := fixture.bank.ImportBundle(ctx, bundle)
|
||||
if err != nil || len(again.Created) != 0 || len(again.Unchanged) != 3 {
|
||||
t.Fatalf("ImportBundle(table bundle again) = %+v, %v, want three unchanged versions", again, err)
|
||||
}
|
||||
// The stored row is verified with its own scheme when it is read, and
|
||||
// the same seed gives the same variant from it.
|
||||
for _, family := range bundle.Families {
|
||||
key := domain.AssessmentFamilyKey(family.Key)
|
||||
stored, err := fixture.store.AssessmentBank().GetFamilyVersion(ctx, key, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("GetFamilyVersion(%s) error = %v", key, err)
|
||||
}
|
||||
wantScheme := int16(2)
|
||||
if family.SeedGenerator.Table == nil {
|
||||
wantScheme = 1
|
||||
}
|
||||
if stored.HashScheme() != wantScheme {
|
||||
t.Fatalf("family %s scheme = %d, want %d", key, stored.HashScheme(), wantScheme)
|
||||
}
|
||||
one, err := fixture.bank.GenerateVariant(ctx, key, 1, 77)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateVariant(%s) error = %v", key, err)
|
||||
}
|
||||
two, err := fixture.bank.GenerateVariant(ctx, key, 1, 77)
|
||||
if err != nil || one.Statement != two.Statement || one.ReferenceAnswer != two.ReferenceAnswer || !slices.Equal(one.Options, two.Options) {
|
||||
t.Fatalf("GenerateVariant(%s) twice = %+v and %+v (%v), want one variant", key, one, two, err)
|
||||
}
|
||||
}
|
||||
// A table row edited in the database fails the hash, whatever the edit
|
||||
// path: the trigger refuses the edit, and the row stays as imported.
|
||||
_, err = fixture.pool.Exec(ctx, `UPDATE assessment_families SET seed_generator = replace(seed_generator::text, '"404"', '"405"')::jsonb WHERE hash_scheme = 2`)
|
||||
assertPgError(t, "edit a table", err, assessmentIntegritySQLState, "assessment_families_immutable")
|
||||
})
|
||||
|
||||
t.Run("families are listed in pages after a cursor", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
bundle := fixture.reviewedBundle(5)
|
||||
|
||||
@@ -17,11 +17,11 @@ import (
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
// choiceBankFamilies returns the families of a bank that offers the choice
|
||||
// answer format next to the integer one: a choice family whose distractors
|
||||
// come from error models, and the first demo family. The choice family reuses
|
||||
// the rubric and the identity of the first demo family.
|
||||
func choiceBankFamilies(t *testing.T, base assessment.BundleFamily) []assessment.BundleFamily {
|
||||
// choiceTableBankFamilies returns the families of a bank that offers every new
|
||||
// answer format: a choice family whose distractors come from error models, a
|
||||
// table family with integer answers, and a table family with choice answers.
|
||||
// They reuse the rubric and the identity of the first demo family.
|
||||
func choiceTableBankFamilies(t *testing.T, base assessment.BundleFamily) []assessment.BundleFamily {
|
||||
t.Helper()
|
||||
choice := base
|
||||
choice.Key = "choice-lru-hits"
|
||||
@@ -33,7 +33,32 @@ func choiceBankFamilies(t *testing.T, base assessment.BundleFamily) []assessment
|
||||
StatementTemplate: "A cache of capacity {{.capacity}} drops its least recently used key when it is full. Keys are read in this order: {{.sequence}}. How many reads find their key in the cache?",
|
||||
}
|
||||
choice.AnswerKey = domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatChoice, ReferenceSolution: "Simulate the cache."}
|
||||
return []assessment.BundleFamily{choice, base}
|
||||
|
||||
integerTable := base
|
||||
integerTable.Key = "table-integer-limits"
|
||||
integerTable.SeedGenerator = domain.AssessmentSeedGenerator{
|
||||
StatementTemplate: "A pool opens {{.connections}} connections at most and each request holds one for {{.seconds}} seconds. How many requests per minute can it serve at most?",
|
||||
Table: &domain.AssessmentVariantTable{Rows: []domain.AssessmentVariantRow{
|
||||
{Values: map[string]string{"connections": "10", "seconds": "2"}, Answer: "300"},
|
||||
{Values: map[string]string{"connections": "4", "seconds": "3"}, Answer: "80"},
|
||||
{Values: map[string]string{"connections": "6", "seconds": "5"}, Answer: "72"},
|
||||
{Values: map[string]string{"connections": "20", "seconds": "1"}, Answer: "1200"},
|
||||
}},
|
||||
}
|
||||
integerTable.AnswerKey = domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatInteger, ReferenceSolution: "Multiply by sixty and divide by the hold time."}
|
||||
|
||||
choiceTable := base
|
||||
choiceTable.Key = "table-choice-status"
|
||||
choiceTable.SeedGenerator = domain.AssessmentSeedGenerator{
|
||||
StatementTemplate: "Which status code does an API return for {{.situation}}?",
|
||||
Table: &domain.AssessmentVariantTable{Rows: []domain.AssessmentVariantRow{
|
||||
{Values: map[string]string{"situation": "a resource that does not exist"}, Answer: "404", Distractors: []string{"400", "410", "500"}},
|
||||
{Values: map[string]string{"situation": "a call without credentials"}, Answer: "401", Distractors: []string{"403", "407", "511"}},
|
||||
{Values: map[string]string{"situation": "an update on a stale version"}, Answer: "412", Distractors: []string{"409", "422", "428"}},
|
||||
}},
|
||||
}
|
||||
choiceTable.AnswerKey = domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatChoice, ReferenceSolution: "Match the situation to the status code."}
|
||||
return []assessment.BundleFamily{choice, integerTable, choiceTable}
|
||||
}
|
||||
|
||||
// allowedItemKeys are the fields that a candidate item may carry per format.
|
||||
@@ -42,7 +67,7 @@ var allowedItemContentKeys = map[string][]string{
|
||||
"choice": {"format", "multiple", "options"},
|
||||
}
|
||||
|
||||
func TestAssessmentChoiceFamiliesAreServedAndGradedOverHTTP(t *testing.T) {
|
||||
func TestAssessmentChoiceAndTableFamiliesAreServedAndGradedOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
|
||||
defer cancel()
|
||||
@@ -53,9 +78,18 @@ func TestAssessmentChoiceFamiliesAreServedAndGradedOverHTTP(t *testing.T) {
|
||||
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
||||
|
||||
source := loadDemoBundleFile(t)
|
||||
source.Families = choiceBankFamilies(t, source.Families[0])
|
||||
source.Families = choiceTableBankFamilies(t, source.Families[0])
|
||||
seedAssessmentAttemptHTTPBankFrom(ctx, t, harness.pool, nil, source)
|
||||
|
||||
// The bank holds both kinds of generator: the table families are stored
|
||||
// with hash scheme 2 and the algorithmic family with scheme 1.
|
||||
for scheme, want := range map[int]bool{1: true, 2: true} {
|
||||
var stored int
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_families WHERE hash_scheme = $1`, scheme).Scan(&stored); err != nil || (stored > 0) != want {
|
||||
t.Fatalf("families with hash scheme %d = %d, %v, want some", scheme, stored, err)
|
||||
}
|
||||
}
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
|
||||
@@ -239,7 +239,7 @@ func ParseAssessmentLifecycle(value string) (AssessmentLifecycle, error) {
|
||||
type AssessmentAnswerKey struct {
|
||||
// AnswerFormat is the format of the reference answer: "integer",
|
||||
// "integer_sequence", or "choice". It must match the algorithm of the
|
||||
// generator.
|
||||
// generator; a table generator takes "integer" or "choice".
|
||||
AnswerFormat string `json:"answer_format"`
|
||||
// ReferenceSolution describes the reference approach in prose.
|
||||
ReferenceSolution string `json:"reference_solution"`
|
||||
@@ -289,9 +289,11 @@ func (rubric AssessmentRubric) validate(location string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (key AssessmentAnswerKey) validate(location string, algorithm assessmentAlgorithm) error {
|
||||
if key.AnswerFormat != algorithm.answerFormat {
|
||||
return invalidAssessmentFamily(location, "answer format does not match the answer format of the generator algorithm")
|
||||
// validate checks the answer key against the answer format that the
|
||||
// generator produces.
|
||||
func (key AssessmentAnswerKey) validate(location, generatorFormat string) error {
|
||||
if key.AnswerFormat != generatorFormat {
|
||||
return invalidAssessmentFamily(location, "answer format does not match the answer format of the generator")
|
||||
}
|
||||
return checkAssessmentText(location, "reference solution", key.ReferenceSolution)
|
||||
}
|
||||
@@ -379,16 +381,33 @@ func (core AssessmentFamilyCore) validate(location string, probe bool) error {
|
||||
if err := core.validateReview(location); err != nil {
|
||||
return err
|
||||
}
|
||||
algorithm, err := core.Generator.validate(location, probe)
|
||||
generatorFormat, err := core.validateGenerator(location, probe)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := core.AnswerKey.validate(location, algorithm); err != nil {
|
||||
if err := core.AnswerKey.validate(location, generatorFormat); err != nil {
|
||||
return err
|
||||
}
|
||||
return core.Rubric.validate(location)
|
||||
}
|
||||
|
||||
// validateGenerator validates the generator of either kind and returns the
|
||||
// answer format that it produces. A table generator produces the format its
|
||||
// answer key declares, after the table has been checked against it.
|
||||
func (core AssessmentFamilyCore) validateGenerator(location string, probe bool) (string, error) {
|
||||
if core.Generator.Table != nil {
|
||||
if err := core.Generator.validateTable(location, core.AnswerKey.AnswerFormat, probe); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return core.AnswerKey.AnswerFormat, nil
|
||||
}
|
||||
algorithm, err := core.Generator.validate(location, probe)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return algorithm.answerFormat, nil
|
||||
}
|
||||
|
||||
func (core AssessmentFamilyCore) validateReview(location string) error {
|
||||
if _, err := ParseAssessmentReviewStatus(string(core.ReviewStatus)); err != nil {
|
||||
return fmt.Errorf("%s - validate review status: %w", location, err)
|
||||
@@ -408,25 +427,58 @@ func (core AssessmentFamilyCore) validateReview(location string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// currentAssessmentHashScheme is the scheme that new versions are stored
|
||||
// with. A stored row keeps its own scheme in the hash_scheme column, and
|
||||
// RestoreAssessmentFamily verifies it with that scheme's function, so a later
|
||||
// scheme verifies new rows without invalidating the old ones. A change of the
|
||||
// canonical layout, of a field, or of the encoding adds a scheme here and to
|
||||
// the assessment_families_hash_scheme_known CHECK; it never edits the
|
||||
// function of an existing scheme.
|
||||
const currentAssessmentHashScheme int16 = 1
|
||||
// The hash schemes of family content. A stored row keeps its own scheme in
|
||||
// the hash_scheme column, and RestoreAssessmentFamily verifies it with that
|
||||
// scheme's function, so a later scheme verifies new rows without invalidating
|
||||
// the old ones. A change of the canonical layout, of a field, or of the
|
||||
// encoding adds a scheme here and to the assessment_families_hash_scheme_known
|
||||
// CHECK; it never edits the function of an existing scheme.
|
||||
//
|
||||
// Scheme 1 hashes the layout of an algorithmic generator. Scheme 2 is the
|
||||
// layout of a table generator, whose canonical content holds the table instead
|
||||
// of an algorithm and its parameters. A new version gets the scheme of its
|
||||
// generator kind, so the content of an algorithmic family keeps the hash it
|
||||
// had before table generators existed, and importing it again is still
|
||||
// recognized as the same version.
|
||||
const (
|
||||
assessmentHashSchemeAlgorithmic int16 = 1
|
||||
assessmentHashSchemeTable int16 = 2
|
||||
)
|
||||
|
||||
// hashScheme is the scheme that a new version of this content is stored with.
|
||||
func (core AssessmentFamilyCore) hashScheme() int16 {
|
||||
if core.Generator.Table != nil {
|
||||
return assessmentHashSchemeTable
|
||||
}
|
||||
return assessmentHashSchemeAlgorithmic
|
||||
}
|
||||
|
||||
// assessmentHashSchemes maps a scheme number to its hash function. It is a
|
||||
// variable only so that a test can register a scheme.
|
||||
var assessmentHashSchemes = map[int16]func(AssessmentFamilyCore) (AssessmentContentHash, error){
|
||||
1: contentHashV1,
|
||||
assessmentHashSchemeAlgorithmic: contentHashV1,
|
||||
assessmentHashSchemeTable: contentHashV2,
|
||||
}
|
||||
|
||||
// assessmentCanonicalContentV1 is the form that scheme 1 hashes. The bundle
|
||||
// name, the ID, and the lifecycle are not part of it: they are provenance and
|
||||
// state, not content.
|
||||
type assessmentCanonicalContentV1 struct {
|
||||
// assessmentCanonicalGeneratorV1 is the generator layout of scheme 1. It is a
|
||||
// type of its own, so that a later field of AssessmentSeedGenerator cannot
|
||||
// change what scheme 1 hashes.
|
||||
type assessmentCanonicalGeneratorV1 struct {
|
||||
Algorithm string `json:"algorithm"`
|
||||
Parameters map[string]AssessmentParameterRange `json:"parameters"`
|
||||
StatementTemplate string `json:"statement_template"`
|
||||
}
|
||||
|
||||
// assessmentCanonicalGeneratorV2 is the generator layout of scheme 2.
|
||||
type assessmentCanonicalGeneratorV2 struct {
|
||||
StatementTemplate string `json:"statement_template"`
|
||||
Table *AssessmentVariantTable `json:"table"`
|
||||
}
|
||||
|
||||
// assessmentCanonicalContent is the form that the schemes hash, with the
|
||||
// generator layout of the scheme. The bundle name, the ID, and the lifecycle
|
||||
// are not part of it: they are provenance and state, not content.
|
||||
type assessmentCanonicalContent[Generator any] struct {
|
||||
Key AssessmentFamilyKey `json:"family_key"`
|
||||
Version int32 `json:"version"`
|
||||
Category AssessmentCategory `json:"category"`
|
||||
@@ -435,7 +487,7 @@ type assessmentCanonicalContentV1 struct {
|
||||
Author AssessmentAuthor `json:"author"`
|
||||
Reviewer AssessmentOperator `json:"reviewer,omitempty"`
|
||||
ReviewStatus AssessmentReviewStatus `json:"review_status"`
|
||||
Generator AssessmentSeedGenerator `json:"seed_generator"`
|
||||
Generator Generator `json:"seed_generator"`
|
||||
AnswerKey AssessmentAnswerKey `json:"answer_key"`
|
||||
Rubric AssessmentRubric `json:"rubric"`
|
||||
}
|
||||
@@ -454,13 +506,32 @@ func (core AssessmentFamilyCore) contentHash(scheme int16) (AssessmentContentHas
|
||||
}
|
||||
|
||||
func contentHashV1(core AssessmentFamilyCore) (AssessmentContentHash, error) {
|
||||
encoded, err := json.Marshal(assessmentCanonicalContentV1{
|
||||
if core.Generator.Table != nil {
|
||||
return AssessmentContentHash{}, invalidAssessmentFamily("domain.contentHashV1", "scheme 1 does not cover a table generator")
|
||||
}
|
||||
return hashCanonicalContent("domain.contentHashV1", core, assessmentCanonicalGeneratorV1{
|
||||
Algorithm: core.Generator.Algorithm, Parameters: core.Generator.Parameters,
|
||||
StatementTemplate: core.Generator.StatementTemplate,
|
||||
})
|
||||
}
|
||||
|
||||
func contentHashV2(core AssessmentFamilyCore) (AssessmentContentHash, error) {
|
||||
if core.Generator.Table == nil || core.Generator.Algorithm != "" || len(core.Generator.Parameters) != 0 {
|
||||
return AssessmentContentHash{}, invalidAssessmentFamily("domain.contentHashV2", "scheme 2 covers only a table generator")
|
||||
}
|
||||
return hashCanonicalContent("domain.contentHashV2", core, assessmentCanonicalGeneratorV2{
|
||||
StatementTemplate: core.Generator.StatementTemplate, Table: core.Generator.Table,
|
||||
})
|
||||
}
|
||||
|
||||
func hashCanonicalContent[Generator any](location string, core AssessmentFamilyCore, generator Generator) (AssessmentContentHash, error) {
|
||||
encoded, err := json.Marshal(assessmentCanonicalContent[Generator]{
|
||||
Key: core.Key, Version: core.Version, Category: core.Category, Specialization: core.Specialization,
|
||||
Title: core.Title, Author: core.Author, Reviewer: core.Reviewer, ReviewStatus: core.ReviewStatus,
|
||||
Generator: core.Generator, AnswerKey: core.AnswerKey, Rubric: core.Rubric,
|
||||
Generator: generator, AnswerKey: core.AnswerKey, Rubric: core.Rubric,
|
||||
})
|
||||
if err != nil {
|
||||
return AssessmentContentHash{}, fmt.Errorf("domain.contentHashV1 - encode canonical content: %w", err)
|
||||
return AssessmentContentHash{}, fmt.Errorf("%s - encode canonical content: %w", location, err)
|
||||
}
|
||||
return sha256.Sum256(encoded), nil
|
||||
}
|
||||
@@ -483,7 +554,8 @@ func NewAssessmentFamilyDraft(input NewAssessmentFamilyDraftInput) (AssessmentFa
|
||||
if err := core.validate(location, true); err != nil {
|
||||
return AssessmentFamilyDraft{}, err
|
||||
}
|
||||
hash, err := core.contentHash(currentAssessmentHashScheme)
|
||||
scheme := core.hashScheme()
|
||||
hash, err := core.contentHash(scheme)
|
||||
if err != nil {
|
||||
return AssessmentFamilyDraft{}, err
|
||||
}
|
||||
@@ -491,7 +563,7 @@ func NewAssessmentFamilyDraft(input NewAssessmentFamilyDraftInput) (AssessmentFa
|
||||
if err != nil {
|
||||
return AssessmentFamilyDraft{}, fmt.Errorf("%s - assign ID: %w", location, err)
|
||||
}
|
||||
return AssessmentFamilyDraft{id: id, core: core, hash: hash, scheme: currentAssessmentHashScheme}, nil
|
||||
return AssessmentFamilyDraft{id: id, core: core, hash: hash, scheme: scheme}, nil
|
||||
}
|
||||
|
||||
func (draft AssessmentFamilyDraft) ID() AssessmentFamilyID { return draft.id }
|
||||
|
||||
@@ -314,7 +314,9 @@ func TestNewAssessmentCategoryOpeningDraftReadsCoverageFromThePolicy(t *testing.
|
||||
// A row is verified with the scheme it was stored with, so adding a scheme
|
||||
// later does not invalidate old rows or accept a hash of the wrong scheme.
|
||||
func TestRestoreVerifiesARowWithItsOwnHashScheme(t *testing.T) {
|
||||
const testScheme int16 = 2
|
||||
// A number that no real scheme uses, so that the registration cannot
|
||||
// shadow one.
|
||||
const testScheme int16 = 8
|
||||
assessmentHashSchemes[testScheme] = func(core AssessmentFamilyCore) (AssessmentContentHash, error) {
|
||||
hash, err := contentHashV1(core)
|
||||
hash[0] ^= 0xff // a different function of the same content
|
||||
@@ -326,8 +328,8 @@ func TestRestoreVerifiesARowWithItsOwnHashScheme(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
|
||||
}
|
||||
if draft.HashScheme() != currentAssessmentHashScheme {
|
||||
t.Fatalf("draft scheme = %d, want the current scheme %d", draft.HashScheme(), currentAssessmentHashScheme)
|
||||
if draft.HashScheme() != assessmentHashSchemeAlgorithmic {
|
||||
t.Fatalf("draft scheme = %d, want the algorithmic scheme %d", draft.HashScheme(), assessmentHashSchemeAlgorithmic)
|
||||
}
|
||||
old := storedAssessmentFrom(t, draft)
|
||||
if family, err := RestoreAssessmentFamily(old); err != nil || family.HashScheme() != 1 {
|
||||
@@ -337,18 +339,18 @@ func TestRestoreVerifiesARowWithItsOwnHashScheme(t *testing.T) {
|
||||
core := draft.Core()
|
||||
newer, err := core.contentHash(testScheme)
|
||||
if err != nil {
|
||||
t.Fatalf("contentHash(scheme 2) error = %v", err)
|
||||
t.Fatalf("contentHash(test scheme) error = %v", err)
|
||||
}
|
||||
row := old
|
||||
row.HashScheme, row.ContentHash = testScheme, newer[:]
|
||||
if family, err := RestoreAssessmentFamily(row); err != nil || family.HashScheme() != testScheme {
|
||||
t.Fatalf("RestoreAssessmentFamily(scheme 2 row) = scheme %d, %v, want a verified row of scheme 2", family.HashScheme(), err)
|
||||
t.Fatalf("RestoreAssessmentFamily(test scheme row) = scheme %d, %v, want a verified row of the test scheme", family.HashScheme(), err)
|
||||
}
|
||||
// The hash of one scheme under the name of the other, and an unknown
|
||||
// scheme, are refused.
|
||||
row.ContentHash = old.ContentHash
|
||||
if _, err := RestoreAssessmentFamily(row); !errors.Is(err, ErrAssessmentFamilyIntegrity) {
|
||||
t.Fatalf("RestoreAssessmentFamily(scheme 1 hash under scheme 2) error = %v, want ErrAssessmentFamilyIntegrity", err)
|
||||
t.Fatalf("RestoreAssessmentFamily(scheme 1 hash under the test scheme) error = %v, want ErrAssessmentFamilyIntegrity", err)
|
||||
}
|
||||
row.HashScheme = 9
|
||||
if _, err := RestoreAssessmentFamily(row); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
|
||||
@@ -36,23 +36,30 @@ type AssessmentParameterRange struct {
|
||||
Max int32 `json:"max"`
|
||||
}
|
||||
|
||||
// AssessmentSeedGenerator describes how seeds become variants: a named
|
||||
// algorithm, the ranges of its parameters, and the statement template. The
|
||||
// algorithm is code that is registered in this package under a versioned
|
||||
// name, so an old family version keeps its algorithm after a newer one
|
||||
// exists.
|
||||
// AssessmentSeedGenerator describes how seeds become variants. There are two
|
||||
// kinds. An algorithmic generator names an algorithm, the ranges of its
|
||||
// parameters, and the statement template; the algorithm is code that is
|
||||
// registered in this package under a versioned name, so an old family version
|
||||
// keeps its algorithm after a newer one exists. A table generator holds the
|
||||
// variants themselves as rows with their answers and the statement template;
|
||||
// the seed selects a row and no code computes the answer. A table generator
|
||||
// has no algorithm and no parameters.
|
||||
type AssessmentSeedGenerator struct {
|
||||
Algorithm string `json:"algorithm"`
|
||||
Parameters map[string]AssessmentParameterRange `json:"parameters"`
|
||||
Algorithm string `json:"algorithm,omitempty"`
|
||||
Parameters map[string]AssessmentParameterRange `json:"parameters,omitempty"`
|
||||
// StatementTemplate is plain text with {{.name}} placeholders for the
|
||||
// parameters and the generated input data of the algorithm. Nothing else
|
||||
// of the text/template language is accepted; see compileStatementTemplate.
|
||||
// parameters and the generated input data of the algorithm, or for the
|
||||
// columns of the table. Nothing else of the text/template language is
|
||||
// accepted; see compileStatementTemplate.
|
||||
StatementTemplate string `json:"statement_template"`
|
||||
// Table is set for a table generator and nil for an algorithmic one.
|
||||
Table *AssessmentVariantTable `json:"table,omitempty"`
|
||||
}
|
||||
|
||||
func (generator AssessmentSeedGenerator) clone() AssessmentSeedGenerator {
|
||||
copied := generator
|
||||
copied.Parameters = maps.Clone(generator.Parameters)
|
||||
copied.Table = generator.Table.clone()
|
||||
return copied
|
||||
}
|
||||
|
||||
@@ -63,6 +70,9 @@ func (generator AssessmentSeedGenerator) clone() AssessmentSeedGenerator {
|
||||
// proves that the content is the one that passed them. It returns the
|
||||
// algorithm.
|
||||
func (generator AssessmentSeedGenerator) validate(location string, probe bool) (assessmentAlgorithm, error) {
|
||||
if generator.Table != nil {
|
||||
return assessmentAlgorithm{}, invalidAssessmentFamily(location, "a table generator has no algorithm")
|
||||
}
|
||||
algorithm, ok := assessmentAlgorithms[generator.Algorithm]
|
||||
if !ok {
|
||||
return assessmentAlgorithm{}, invalidAssessmentFamily(location, "generator algorithm is unknown")
|
||||
@@ -187,6 +197,9 @@ func (family AssessmentFamily) NewVariant(seed VariantSeed) (AssessmentVariant,
|
||||
if family.IsZero() {
|
||||
return AssessmentVariant{}, invalidAssessmentFamily(location, "family was not built by RestoreAssessmentFamily")
|
||||
}
|
||||
if family.core.Generator.Table != nil {
|
||||
return family.newTableVariant(seed)
|
||||
}
|
||||
algorithm, ok := assessmentAlgorithms[family.core.Generator.Algorithm]
|
||||
if !ok {
|
||||
return AssessmentVariant{}, invalidAssessmentFamily(location, "generator algorithm is unknown")
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
// minTableRows: a table with one row is a fixed task, not a generator.
|
||||
minTableRows = 2
|
||||
// maxTableRows, maxTableColumns, maxTableValueBytes, and maxTableBytes
|
||||
// bound a table. The attempt service reads every published family of a
|
||||
// category when it starts an attempt, so a table stays small; a family
|
||||
// that needs more variants is a Go algorithm.
|
||||
maxTableRows = 500
|
||||
maxTableColumns = 16
|
||||
maxTableValueBytes = 1000
|
||||
maxTableBytes = 64 << 10
|
||||
// tableSelectionName separates the seed derivation of table rows from
|
||||
// that of every algorithm. The selection is part of what stored table
|
||||
// families depend on, so a different rule would be a new name.
|
||||
tableSelectionName = "table.v1"
|
||||
)
|
||||
|
||||
var (
|
||||
assessmentTableColumnPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,31}$`)
|
||||
// assessmentTableIntegerPattern is a canonical decimal integer of at most
|
||||
// 15 digits, which a JSON number carries exactly.
|
||||
assessmentTableIntegerPattern = regexp.MustCompile(`^(0|-?[1-9][0-9]{0,14})$`)
|
||||
)
|
||||
|
||||
// AssessmentVariantTable is the declarative variant source of a table
|
||||
// generator: a table of rows, each with the placeholder values of the
|
||||
// statement template and the answer. It is data, never code: the seed selects
|
||||
// a row, the statement template substitutes its values, and the answer is the
|
||||
// one written in the row. Nothing is computed from the table.
|
||||
type AssessmentVariantTable struct {
|
||||
Rows []AssessmentVariantRow `json:"rows"`
|
||||
}
|
||||
|
||||
// AssessmentVariantRow is one variant of a table.
|
||||
type AssessmentVariantRow struct {
|
||||
// Values maps each column, that is, each placeholder of the statement
|
||||
// template, to the text that replaces it. Every row has the same columns.
|
||||
Values map[string]string `json:"values"`
|
||||
// Answer is the reference answer: a canonical decimal integer for the
|
||||
// answer format integer, and the text of the correct option for choice.
|
||||
Answer string `json:"answer"`
|
||||
// Distractors are the wrong options of a choice row. A row of any other
|
||||
// format has none.
|
||||
Distractors []string `json:"distractors,omitempty"`
|
||||
}
|
||||
|
||||
func (table *AssessmentVariantTable) clone() *AssessmentVariantTable {
|
||||
if table == nil {
|
||||
return nil
|
||||
}
|
||||
copied := &AssessmentVariantTable{Rows: make([]AssessmentVariantRow, len(table.Rows))}
|
||||
for index, row := range table.Rows {
|
||||
copied.Rows[index] = AssessmentVariantRow{
|
||||
Values: maps.Clone(row.Values), Answer: row.Answer, Distractors: slices.Clone(row.Distractors),
|
||||
}
|
||||
}
|
||||
return copied
|
||||
}
|
||||
|
||||
// columns returns the column names of the table, which are the names of the
|
||||
// first row, in sorted order.
|
||||
func (table *AssessmentVariantTable) columns() []string {
|
||||
if table == nil || len(table.Rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
return slices.Sorted(maps.Keys(table.Rows[0].Values))
|
||||
}
|
||||
|
||||
// tableAlgorithm describes the placeholders of a table to the statement
|
||||
// template compiler: every column is a known placeholder, and every column
|
||||
// must appear in the statement, because a hidden column would make rows that
|
||||
// differ only there indistinguishable to the candidate.
|
||||
func tableAlgorithm(columns []string) assessmentAlgorithm {
|
||||
return assessmentAlgorithm{dataNames: columns, requiredNames: columns}
|
||||
}
|
||||
|
||||
// validateTable checks a table generator against the answer format of the
|
||||
// family. Every failure that belongs to a row names the row by its index in
|
||||
// the rows array, counted from zero, and never quotes the content. With
|
||||
// probe set it also renders the statement of every row, which an importer
|
||||
// does and the read of a stored row does not, because the content hash
|
||||
// proves that the content is the one that passed.
|
||||
func (generator AssessmentSeedGenerator) validateTable(location, answerFormat string, probe bool) error {
|
||||
table := generator.Table
|
||||
if generator.Algorithm != "" || len(generator.Parameters) != 0 {
|
||||
return invalidAssessmentFamily(location, "a table generator has no algorithm and no parameters")
|
||||
}
|
||||
if answerFormat != AnswerFormatInteger && answerFormat != AnswerFormatChoice {
|
||||
return invalidAssessmentFamily(location, "table answer format must be integer or choice")
|
||||
}
|
||||
if len(table.Rows) < minTableRows || len(table.Rows) > maxTableRows {
|
||||
return invalidAssessmentFamily(location, fmt.Sprintf("table must have %d to %d rows", minTableRows, maxTableRows))
|
||||
}
|
||||
columns := table.columns()
|
||||
if len(columns) == 0 || len(columns) > maxTableColumns {
|
||||
return invalidAssessmentFamily(location, fmt.Sprintf("table rows[0] must have 1 to %d columns", maxTableColumns))
|
||||
}
|
||||
for _, column := range columns {
|
||||
if !assessmentTableColumnPattern.MatchString(column) {
|
||||
return invalidAssessmentFamily(location, "table column names must be 1 to 32 lowercase letters, digits, or '_', starting with a letter")
|
||||
}
|
||||
}
|
||||
statement, err := compileStatementTemplate(location, generator.StatementTemplate, tableAlgorithm(columns))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return validateTableRows(location, table, columns, statement, answerFormat, probe)
|
||||
}
|
||||
|
||||
func validateTableRows(
|
||||
location string,
|
||||
table *AssessmentVariantTable,
|
||||
columns []string,
|
||||
statement statementTemplate,
|
||||
answerFormat string,
|
||||
probe bool,
|
||||
) error {
|
||||
firstRowOf := make(map[string]int, len(table.Rows))
|
||||
totalBytes := 0
|
||||
for index, row := range table.Rows {
|
||||
rowLocation := fmt.Sprintf("%s - table rows[%d]", location, index)
|
||||
if len(row.Values) != len(columns) {
|
||||
return invalidAssessmentFamily(rowLocation, "values must have exactly the columns of rows[0]")
|
||||
}
|
||||
var identity strings.Builder
|
||||
for _, column := range columns {
|
||||
value, ok := row.Values[column]
|
||||
if !ok {
|
||||
return invalidAssessmentFamily(rowLocation, "values must have exactly the columns of rows[0]")
|
||||
}
|
||||
if err := checkTableValue(rowLocation, "value of column "+column, value, maxTableValueBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
totalBytes += len(value)
|
||||
identity.WriteString(value)
|
||||
identity.WriteByte(0)
|
||||
}
|
||||
if earlier, repeated := firstRowOf[identity.String()]; repeated {
|
||||
return invalidAssessmentFamily(rowLocation, fmt.Sprintf("values repeat rows[%d]", earlier))
|
||||
}
|
||||
firstRowOf[identity.String()] = index
|
||||
if err := validateTableAnswer(rowLocation, row, answerFormat); err != nil {
|
||||
return err
|
||||
}
|
||||
totalBytes += len(row.Answer)
|
||||
for _, distractor := range row.Distractors {
|
||||
totalBytes += len(distractor)
|
||||
}
|
||||
if totalBytes > maxTableBytes {
|
||||
return invalidAssessmentFamily(rowLocation, fmt.Sprintf("table text exceeds %d bytes", maxTableBytes))
|
||||
}
|
||||
if probe {
|
||||
if _, err := statement.render(row.Values); err != nil {
|
||||
return fmt.Errorf("%s - render statement: %w", rowLocation, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkTableValue is checkAssessmentText with the table bound.
|
||||
func checkTableValue(location, field, value string, limit int) error {
|
||||
if len(value) > limit {
|
||||
return invalidAssessmentFamily(location, fmt.Sprintf("%s must be at most %d bytes", field, limit))
|
||||
}
|
||||
return checkAssessmentText(location, field, value)
|
||||
}
|
||||
|
||||
// checkTableOption accepts one line of option text.
|
||||
func checkTableOption(location, field, value string) error {
|
||||
if strings.Contains(value, "\n") {
|
||||
return invalidAssessmentFamily(location, field+" must be one line")
|
||||
}
|
||||
return checkTableValue(location, field, value, maxChoiceOptionBytes)
|
||||
}
|
||||
|
||||
// validateTableAnswer checks that the answer of a row has the format of the
|
||||
// family. For choice it requires distinct options, so that no two options
|
||||
// show the same text and the correct one is not repeated among the
|
||||
// distractors.
|
||||
func validateTableAnswer(location string, row AssessmentVariantRow, answerFormat string) error {
|
||||
if answerFormat == AnswerFormatInteger {
|
||||
if !assessmentTableIntegerPattern.MatchString(row.Answer) {
|
||||
return invalidAssessmentFamily(location, "answer must be a canonical decimal integer of at most 15 digits")
|
||||
}
|
||||
if len(row.Distractors) != 0 {
|
||||
return invalidAssessmentFamily(location, "an integer answer has no distractors")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := checkTableOption(location, "answer", row.Answer); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(row.Distractors) < 1 || len(row.Distractors) > maxChoiceOptions-1 {
|
||||
return invalidAssessmentFamily(location, fmt.Sprintf("choice row must have 1 to %d distractors", maxChoiceOptions-1))
|
||||
}
|
||||
seen := map[string]bool{row.Answer: true}
|
||||
for _, distractor := range row.Distractors {
|
||||
if err := checkTableOption(location, "distractor", distractor); err != nil {
|
||||
return err
|
||||
}
|
||||
if seen[distractor] {
|
||||
return invalidAssessmentFamily(location, "options must be distinct: a distractor repeats the answer or another distractor")
|
||||
}
|
||||
seen[distractor] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// newTableVariant selects the row of a seed and returns its variant. It is a
|
||||
// pure function of the table and the seed. The family was validated when it
|
||||
// was imported and again when it was read, so the answer of the row is not
|
||||
// examined again here.
|
||||
func (family AssessmentFamily) newTableVariant(seed VariantSeed) (AssessmentVariant, error) {
|
||||
const location = "AssessmentFamily.newTableVariant"
|
||||
generator := family.core.Generator
|
||||
table := generator.Table
|
||||
statement, err := compileStatementTemplate(location, generator.StatementTemplate, tableAlgorithm(table.columns()))
|
||||
if err != nil {
|
||||
return AssessmentVariant{}, err
|
||||
}
|
||||
random := newSeededRandom(tableSelectionName, seed)
|
||||
index := random.below(len(table.Rows))
|
||||
row := table.Rows[index]
|
||||
rendered, err := statement.render(row.Values)
|
||||
if err != nil {
|
||||
return AssessmentVariant{}, fmt.Errorf("%s - render statement of rows[%d]: %w", location, index, err)
|
||||
}
|
||||
variant := AssessmentVariant{
|
||||
FamilyID: family.id,
|
||||
FamilyKey: family.core.Key,
|
||||
FamilyVersion: family.core.Version,
|
||||
Seed: seed,
|
||||
// The row index is private provenance, kept with the frozen variant
|
||||
// like the parameters of an algorithm.
|
||||
Parameters: map[string]int32{"row": int32(index)}, //nolint:gosec // the index is below maxTableRows.
|
||||
Statement: rendered,
|
||||
ReferenceAnswer: row.Answer,
|
||||
AnswerFormat: family.core.AnswerKey.AnswerFormat,
|
||||
Rubric: family.core.Rubric.clone(),
|
||||
}
|
||||
if variant.AnswerFormat == AnswerFormatChoice {
|
||||
options, correct, err := newChoiceOptions(random, row.Answer, row.Distractors, nil, len(row.Distractors))
|
||||
if err != nil {
|
||||
return AssessmentVariant{}, fmt.Errorf("%s - build choice options of rows[%d]: %w", location, index, err)
|
||||
}
|
||||
variant.Options, variant.ReferenceAnswer = options, strconv.Itoa(correct)
|
||||
}
|
||||
return variant, nil
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const tableStatementTemplate = "A limiter allows {{.limit}} requests per {{.window}} seconds."
|
||||
|
||||
// integerTableInput is a table family whose answers are written in its rows.
|
||||
// The third answer is deliberately not what any computation of the values
|
||||
// would give: the table, not code, decides.
|
||||
func integerTableInput() NewAssessmentFamilyDraftInput {
|
||||
input := testAssessmentInput()
|
||||
input.Key = "unit-table-family"
|
||||
input.Generator = AssessmentSeedGenerator{
|
||||
StatementTemplate: tableStatementTemplate + " How many of the first 10 requests in the first second pass?",
|
||||
Table: &AssessmentVariantTable{Rows: []AssessmentVariantRow{
|
||||
{Values: map[string]string{"limit": "3", "window": "10"}, Answer: "3"},
|
||||
{Values: map[string]string{"limit": "5", "window": "10"}, Answer: "5"},
|
||||
{Values: map[string]string{"limit": "2", "window": "60"}, Answer: "-7"},
|
||||
{Values: map[string]string{"limit": "8", "window": "1"}, Answer: "0"},
|
||||
}},
|
||||
}
|
||||
input.AnswerKey.AnswerFormat = AnswerFormatInteger
|
||||
return input
|
||||
}
|
||||
|
||||
func choiceTableInput() NewAssessmentFamilyDraftInput {
|
||||
input := testAssessmentInput()
|
||||
input.Key = "unit-table-choice-family"
|
||||
input.Generator = AssessmentSeedGenerator{
|
||||
StatementTemplate: "Which status code does {{.situation}} return?",
|
||||
Table: &AssessmentVariantTable{Rows: []AssessmentVariantRow{
|
||||
{Values: map[string]string{"situation": "a missing resource"}, Answer: "404", Distractors: []string{"400", "410", "500"}},
|
||||
{Values: map[string]string{"situation": "a request without credentials"}, Answer: "401", Distractors: []string{"403", "407"}},
|
||||
{Values: map[string]string{"situation": "a conflicting update"}, Answer: "409", Distractors: []string{"412", "422", "428", "423"}},
|
||||
}},
|
||||
}
|
||||
input.AnswerKey.AnswerFormat = AnswerFormatChoice
|
||||
return input
|
||||
}
|
||||
|
||||
func TestTableFamilySelectsRowsBySeedAndTakesTheAnswerFromTheTable(t *testing.T) {
|
||||
input := integerTableInput()
|
||||
family := restoreAssessment(t, input)
|
||||
rows := input.Generator.Table.Rows
|
||||
seen := make(map[int32]bool)
|
||||
for seed := range VariantSeed(80) {
|
||||
variant, err := family.NewVariant(seed)
|
||||
if err != nil {
|
||||
t.Fatalf("NewVariant(%d) error = %v", seed, err)
|
||||
}
|
||||
again, err := family.NewVariant(seed)
|
||||
if err != nil || !reflect.DeepEqual(variant, again) {
|
||||
t.Fatalf("seed %d gave two variants: %+v and %+v (%v)", seed, variant, again, err)
|
||||
}
|
||||
index := variant.Parameters["row"]
|
||||
row := rows[index]
|
||||
want := "A limiter allows " + row.Values["limit"] + " requests per " + row.Values["window"] +
|
||||
" seconds. How many of the first 10 requests in the first second pass?"
|
||||
if variant.Statement != want || variant.ReferenceAnswer != row.Answer || variant.AnswerFormat != AnswerFormatInteger || len(variant.Options) != 0 {
|
||||
t.Fatalf("seed %d selected rows[%d]: variant %+v, want statement %q and the table answer %q", seed, index, variant, want, row.Answer)
|
||||
}
|
||||
seen[index] = true
|
||||
}
|
||||
if len(seen) != len(rows) {
|
||||
t.Fatalf("80 seeds selected %d of %d rows", len(seen), len(rows))
|
||||
}
|
||||
}
|
||||
|
||||
// The row of a seed is part of what stored table families depend on: a change
|
||||
// of the selection rule must be a new rule name, so one seed is pinned.
|
||||
func TestGoldenTableRowOfASeed(t *testing.T) {
|
||||
family := restoreAssessment(t, integerTableInput())
|
||||
for seed, wantRow := range map[VariantSeed]int32{1: 1, 2: 2, 3: 0, 12345: 2} {
|
||||
variant, err := family.NewVariant(seed)
|
||||
if err != nil || variant.Parameters["row"] != wantRow {
|
||||
t.Fatalf("seed %d selected rows[%d], %v, want rows[%d]", seed, variant.Parameters["row"], err, wantRow)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTableChoiceOptionsAreTheRowAnswerAndDistractorsInSeedOrder(t *testing.T) {
|
||||
input := choiceTableInput()
|
||||
family := restoreAssessment(t, input)
|
||||
rows := input.Generator.Table.Rows
|
||||
orders := make(map[string]bool)
|
||||
for seed := range VariantSeed(300) {
|
||||
variant, err := family.NewVariant(seed)
|
||||
if err != nil {
|
||||
t.Fatalf("NewVariant(%d) error = %v", seed, err)
|
||||
}
|
||||
again, _ := family.NewVariant(seed)
|
||||
if !reflect.DeepEqual(variant, again) {
|
||||
t.Fatalf("seed %d gave two different variants", seed)
|
||||
}
|
||||
row := rows[variant.Parameters["row"]]
|
||||
var texts []string
|
||||
for _, option := range variant.Options {
|
||||
texts = append(texts, option.Text)
|
||||
}
|
||||
orders[fmt.Sprint(variant.Parameters["row"], texts)] = true
|
||||
want := append([]string{row.Answer}, row.Distractors...)
|
||||
slices.Sort(want)
|
||||
got := slices.Clone(texts)
|
||||
slices.Sort(got)
|
||||
index, ok := choiceCorrectIndex(variant)
|
||||
if !slices.Equal(got, want) || !ok || variant.Options[index].Text != row.Answer || variant.AnswerFormat != AnswerFormatChoice {
|
||||
t.Fatalf("seed %d: options %v with the key at %d, want %v with the key on %q", seed, texts, index, want, row.Answer)
|
||||
}
|
||||
if !validFrozenVariant(variant) {
|
||||
t.Fatalf("seed %d: the variant is not a valid frozen variant", seed)
|
||||
}
|
||||
}
|
||||
if len(orders) < 20 {
|
||||
t.Fatalf("300 seeds gave only %d different row and option orders", len(orders))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTableFamilyRefusesAFormatErrorAndNamesTheRow(t *testing.T) {
|
||||
long := strings.Repeat("x", maxTableValueBytes+1)
|
||||
manyRows := make([]AssessmentVariantRow, maxTableRows+1)
|
||||
for index := range manyRows {
|
||||
manyRows[index] = AssessmentVariantRow{Values: map[string]string{"limit": strconv.Itoa(index), "window": "1"}, Answer: "1"}
|
||||
}
|
||||
tests := map[string]struct {
|
||||
mutate func(*NewAssessmentFamilyDraftInput)
|
||||
wantRow string
|
||||
}{
|
||||
"a missing column": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[2].Values = map[string]string{"limit": "2"}
|
||||
}, "rows[2]"},
|
||||
"an extra column": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[1].Values["extra"] = "1"
|
||||
}, "rows[1]"},
|
||||
"another column name": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
delete(i.Generator.Table.Rows[3].Values, "window")
|
||||
i.Generator.Table.Rows[3].Values["period"] = "1"
|
||||
}, "rows[3]"},
|
||||
"an empty value": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[1].Values["window"] = ""
|
||||
}, "rows[1]"},
|
||||
"a value with surrounding blanks": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[0].Values["window"] = " 10"
|
||||
}, "rows[0]"},
|
||||
"an oversized value": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[2].Values["window"] = long
|
||||
}, "rows[2]"},
|
||||
"a bidirectional override in a value": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[3].Values["window"] = "1\u202E"
|
||||
}, "rows[3]"},
|
||||
"an answer with a leading zero": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[1].Answer = "05"
|
||||
}, "rows[1]"},
|
||||
"a fractional answer": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[2].Answer = "1.5"
|
||||
}, "rows[2]"},
|
||||
"a text answer": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[3].Answer = "three"
|
||||
}, "rows[3]"},
|
||||
"an empty answer": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[0].Answer = ""
|
||||
}, "rows[0]"},
|
||||
"minus zero": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[1].Answer = "-0"
|
||||
}, "rows[1]"},
|
||||
"an answer beyond 15 digits": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[2].Answer = "1234567890123456"
|
||||
}, "rows[2]"},
|
||||
"a distractor on an integer row": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[1].Distractors = []string{"4"}
|
||||
}, "rows[1]"},
|
||||
"a repeated row": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[3] = i.Generator.Table.Rows[1]
|
||||
}, "rows[3]"},
|
||||
"a statement above the size bound": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.StatementTemplate = strings.Repeat("{{.limit}} ", 9) + "{{.window}}"
|
||||
i.Generator.Table.Rows[2].Values["limit"] = strings.Repeat("9", maxTableValueBytes)
|
||||
}, "rows[2]"},
|
||||
"a table above the text bound": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
// 80 rows of one maximal value are 80000 bytes; the 64 KiB bound is
|
||||
// crossed at the 66th row, which index 65 names.
|
||||
i.Generator.Table.Rows = nil
|
||||
for index := range 80 {
|
||||
i.Generator.Table.Rows = append(i.Generator.Table.Rows, AssessmentVariantRow{
|
||||
Values: map[string]string{"limit": strconv.Itoa(index), "window": strings.Repeat("w", maxTableValueBytes-3)}, Answer: "1",
|
||||
})
|
||||
}
|
||||
}, "rows[65]"},
|
||||
"one row only": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows = i.Generator.Table.Rows[:1]
|
||||
}, ""},
|
||||
"too many rows": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows = manyRows
|
||||
}, ""},
|
||||
"no rows": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows = nil
|
||||
}, ""},
|
||||
"an invalid column name": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
for _, row := range i.Generator.Table.Rows {
|
||||
row.Values["Limit"] = row.Values["limit"]
|
||||
delete(row.Values, "limit")
|
||||
}
|
||||
i.Generator.StatementTemplate = "{{.Limit}} {{.window}}"
|
||||
}, ""},
|
||||
"a column missing from the statement": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.StatementTemplate = "Only the {{.limit}} is shown."
|
||||
}, ""},
|
||||
"a placeholder that is no column": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.StatementTemplate += " {{.timestamps}}"
|
||||
}, ""},
|
||||
"a call in the statement": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.StatementTemplate += ` {{printf "%99999999d" 1}}`
|
||||
}, ""},
|
||||
"a pipeline in the statement": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.StatementTemplate += " {{.limit | len}}"
|
||||
}, ""},
|
||||
"an algorithm beside the table": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Algorithm = "lru_hits.v1"
|
||||
}, ""},
|
||||
"parameters beside the table": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Parameters = map[string]AssessmentParameterRange{"limit": {Min: 1, Max: 2}}
|
||||
}, ""},
|
||||
"an answer format the table cannot carry": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.AnswerKey.AnswerFormat = AnswerFormatIntegerSequence
|
||||
}, ""},
|
||||
"an answer key of another format": {func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.AnswerKey.AnswerFormat = AnswerFormatChoice
|
||||
}, "rows[0]"},
|
||||
}
|
||||
for name, test := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
input := integerTableInput()
|
||||
test.mutate(&input)
|
||||
_, err := NewAssessmentFamilyDraft(input)
|
||||
if !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
if test.wantRow != "" && !strings.Contains(err.Error(), test.wantRow) {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %q, want it to name %s", err, test.wantRow)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTableChoiceRowsAreCheckedLikeOptions(t *testing.T) {
|
||||
tests := map[string]struct {
|
||||
mutate func(*AssessmentVariantRow)
|
||||
wantRow string
|
||||
}{
|
||||
"no distractors": {func(r *AssessmentVariantRow) { r.Distractors = nil }, "rows[1]"},
|
||||
"a duplicate distractor": {func(r *AssessmentVariantRow) { r.Distractors = []string{"403", "403"} }, "rows[1]"},
|
||||
"a distractor repeating the answer": {func(r *AssessmentVariantRow) {
|
||||
r.Distractors = []string{"403", r.Answer}
|
||||
}, "rows[1]"},
|
||||
"ten distractors": {func(r *AssessmentVariantRow) {
|
||||
r.Distractors = []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}
|
||||
}, "rows[1]"},
|
||||
"a multi-line option": {func(r *AssessmentVariantRow) { r.Distractors = []string{"403\n404"} }, "rows[1]"},
|
||||
"an empty distractor": {func(r *AssessmentVariantRow) { r.Distractors = []string{"403", ""} }, "rows[1]"},
|
||||
"an oversized option": {func(r *AssessmentVariantRow) { r.Answer = strings.Repeat("a", maxChoiceOptionBytes+1) }, "rows[1]"},
|
||||
"a multi-line answer": {func(r *AssessmentVariantRow) { r.Answer = "4\n01" }, "rows[1]"},
|
||||
"a control character": {func(r *AssessmentVariantRow) { r.Distractors = []string{"40\x003"} }, "rows[1]"},
|
||||
"a format character": {func(r *AssessmentVariantRow) { r.Distractors = []string{"403\u2066"} }, "rows[1]"},
|
||||
}
|
||||
for name, test := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
input := choiceTableInput()
|
||||
test.mutate(&input.Generator.Table.Rows[1])
|
||||
_, err := NewAssessmentFamilyDraft(input)
|
||||
if !errors.Is(err, ErrInvalidAssessmentFamily) || !strings.Contains(err.Error(), test.wantRow) {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v, want ErrInvalidAssessmentFamily naming %s", err, test.wantRow)
|
||||
}
|
||||
})
|
||||
}
|
||||
// Nine distractors, the most that ten options allow, are accepted.
|
||||
input := choiceTableInput()
|
||||
input.Generator.Table.Rows[1].Distractors = []string{"1", "2", "3", "4", "5", "6", "7", "8", "9"}
|
||||
if _, err := NewAssessmentFamilyDraft(input); err != nil {
|
||||
t.Fatalf("NewAssessmentFamilyDraft(nine distractors) error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlgorithmicGeneratorRefusesATable(t *testing.T) {
|
||||
input := testAssessmentInput()
|
||||
input.Generator.Table = integerTableInput().Generator.Table
|
||||
if _, err := NewAssessmentFamilyDraft(input); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("NewAssessmentFamilyDraft(algorithm and table) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Table families hash with scheme 2, and algorithmic families keep scheme 1
|
||||
// and the hash they had before tables existed.
|
||||
func TestTableFamilyHashesWithSchemeTwo(t *testing.T) {
|
||||
draft, err := NewAssessmentFamilyDraft(integerTableInput())
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
|
||||
}
|
||||
if draft.HashScheme() != assessmentHashSchemeTable {
|
||||
t.Fatalf("table draft scheme = %d, want %d", draft.HashScheme(), assessmentHashSchemeTable)
|
||||
}
|
||||
// The canonical document of scheme 2: the generator holds the statement
|
||||
// template and the table, and no algorithm or parameters.
|
||||
const canonical = `{"family_key":"unit-table-family","version":1,"category":"unit-category","specialization":"unit-domain","title":"Unit test family","author":"ai:unit-test","review_status":"pending","seed_generator":{"statement_template":"A limiter allows {{.limit}} requests per {{.window}} seconds. How many of the first 10 requests in the first second pass?","table":{"rows":[{"values":{"limit":"3","window":"10"},"answer":"3"},{"values":{"limit":"5","window":"10"},"answer":"5"},{"values":{"limit":"2","window":"60"},"answer":"-7"},{"values":{"limit":"8","window":"1"},"answer":"0"}]}},"answer_key":{"answer_format":"integer","reference_solution":"Simulate the cache."},"rubric":{"principle":"Compare with the reference answer.","criteria":[{"id":"correct_answer","description":"Matches the reference answer."}]}}`
|
||||
want := sha256.Sum256([]byte(canonical))
|
||||
if hash := draft.ContentHash(); hash != AssessmentContentHash(want) {
|
||||
t.Fatalf("scheme 2 content hash = %x, want %x of the canonical document: a changed layout of scheme 2 needs a new scheme, not an edit", hash, want)
|
||||
}
|
||||
if got := fmt.Sprintf("%x", want[:]); got != "f4b93487a03008c72aefbe9b3fc6f19ce9f83dc0a40e719693e07c5a1e5fb8fb" {
|
||||
t.Fatalf("hash of the canonical document = %s, want the pinned value", got)
|
||||
}
|
||||
algorithmic, err := NewAssessmentFamilyDraft(testAssessmentInput())
|
||||
if err != nil || algorithmic.HashScheme() != assessmentHashSchemeAlgorithmic {
|
||||
t.Fatalf("algorithmic draft scheme = %d, %v, want %d", algorithmic.HashScheme(), err, assessmentHashSchemeAlgorithmic)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTableContentIsCoveredByTheHash(t *testing.T) {
|
||||
base, err := NewAssessmentFamilyDraft(integerTableInput())
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
|
||||
}
|
||||
for name, mutate := range map[string]func(*NewAssessmentFamilyDraftInput){
|
||||
"an answer": func(i *NewAssessmentFamilyDraftInput) { i.Generator.Table.Rows[3].Answer = "1" },
|
||||
"a value": func(i *NewAssessmentFamilyDraftInput) { i.Generator.Table.Rows[0].Values["window"] = "11" },
|
||||
"the row order": func(i *NewAssessmentFamilyDraftInput) {
|
||||
i.Generator.Table.Rows[0], i.Generator.Table.Rows[1] = i.Generator.Table.Rows[1], i.Generator.Table.Rows[0]
|
||||
},
|
||||
"a dropped row": func(i *NewAssessmentFamilyDraftInput) { i.Generator.Table.Rows = i.Generator.Table.Rows[:3] },
|
||||
"the statement text": func(i *NewAssessmentFamilyDraftInput) { i.Generator.StatementTemplate += " Think." },
|
||||
} {
|
||||
input := integerTableInput()
|
||||
mutate(&input)
|
||||
draft, err := NewAssessmentFamilyDraft(input)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: NewAssessmentFamilyDraft() error = %v", name, err)
|
||||
}
|
||||
if draft.ContentHash() == base.ContentHash() {
|
||||
t.Errorf("changing %s did not change the content hash", name)
|
||||
}
|
||||
}
|
||||
// A draft does not share state with the input it was built from.
|
||||
input := integerTableInput()
|
||||
draft, err := NewAssessmentFamilyDraft(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
|
||||
}
|
||||
input.Generator.Table.Rows[0].Answer = "99"
|
||||
if draft.Core().Generator.Table.Rows[0].Answer != "3" {
|
||||
t.Fatal("editing the input table changed the table of the draft")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreVerifiesATableFamilyWithItsScheme(t *testing.T) {
|
||||
draft, err := NewAssessmentFamilyDraft(choiceTableInput())
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
|
||||
}
|
||||
stored := storedAssessmentFrom(t, draft)
|
||||
family, err := RestoreAssessmentFamily(stored)
|
||||
if err != nil || family.HashScheme() != assessmentHashSchemeTable {
|
||||
t.Fatalf("RestoreAssessmentFamily(table row) = scheme %d, %v, want a verified row of scheme 2", family.HashScheme(), err)
|
||||
}
|
||||
// The stored document is the table, and the variants of the restored
|
||||
// family are those of the draft's content.
|
||||
if _, err := family.NewVariant(5); err != nil {
|
||||
t.Fatalf("NewVariant() error = %v", err)
|
||||
}
|
||||
|
||||
// An edited answer in the stored document fails the hash.
|
||||
var document map[string]json.RawMessage
|
||||
if err := json.Unmarshal(stored.SeedGenerator, &document); err != nil {
|
||||
t.Fatalf("decode stored generator: %v", err)
|
||||
}
|
||||
edited := stored
|
||||
edited.SeedGenerator = []byte(strings.Replace(string(stored.SeedGenerator), `"answer":"404"`, `"answer":"405"`, 1))
|
||||
if string(edited.SeedGenerator) == string(stored.SeedGenerator) {
|
||||
t.Fatal("the test did not edit the stored table")
|
||||
}
|
||||
if _, err := RestoreAssessmentFamily(edited); !errors.Is(err, ErrAssessmentFamilyIntegrity) {
|
||||
t.Fatalf("RestoreAssessmentFamily(edited answer) error = %v, want ErrAssessmentFamilyIntegrity", err)
|
||||
}
|
||||
|
||||
// A table under scheme 1 would leave the table out of the hash, so it is
|
||||
// refused; so is an algorithmic generator under scheme 2.
|
||||
wrong := stored
|
||||
wrong.HashScheme = assessmentHashSchemeAlgorithmic
|
||||
if _, err := RestoreAssessmentFamily(wrong); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("RestoreAssessmentFamily(table under scheme 1) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
algorithmic, err := NewAssessmentFamilyDraft(testAssessmentInput())
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentFamilyDraft(algorithmic) error = %v", err)
|
||||
}
|
||||
wrong = storedAssessmentFrom(t, algorithmic)
|
||||
wrong.HashScheme = assessmentHashSchemeTable
|
||||
if _, err := RestoreAssessmentFamily(wrong); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("RestoreAssessmentFamily(algorithm under scheme 2) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
|
||||
// A stored table document of another layout does not decode.
|
||||
broken := stored
|
||||
broken.SeedGenerator = []byte(strings.Replace(string(stored.SeedGenerator), `"answer"`, `"solution"`, 1))
|
||||
if _, err := RestoreAssessmentFamily(broken); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("RestoreAssessmentFamily(unknown row field) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The answer of a table variant is the text of the table, never the result of
|
||||
// a computation: this table's answers disagree with every reading of its
|
||||
// values and are still what the variant returns and what grades.
|
||||
func TestTableAnswerIsNeverComputed(t *testing.T) {
|
||||
family := restoreAssessment(t, integerTableInput())
|
||||
variant, err := family.NewVariant(4)
|
||||
if err != nil {
|
||||
t.Fatalf("NewVariant() error = %v", err)
|
||||
}
|
||||
row := integerTableInput().Generator.Table.Rows[variant.Parameters["row"]]
|
||||
_, correct, err := CanonicalAssessmentAnswerForVariant(json.RawMessage(`{"format":"number","number":`+row.Answer+`}`), variant)
|
||||
if err != nil || !correct {
|
||||
t.Fatalf("grading the table answer = %v, %v, want correct", correct, err)
|
||||
}
|
||||
}
|
||||
@@ -78,3 +78,69 @@ func TestBundleRejectsInvalidDocuments(t *testing.T) {
|
||||
t.Fatalf("Drafts(no families) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
}
|
||||
|
||||
// tableBundleDocument is a bundle with a declarative family: the variants are
|
||||
// rows of a table, and the answers are written in the rows.
|
||||
const tableBundleDocument = `{
|
||||
"name": "table-bundle-v1",
|
||||
"category": "backend",
|
||||
"author": "operator:author",
|
||||
"review": {"status": "approved", "reviewer": "operator:reviewer"},
|
||||
"families": [{
|
||||
"key": "http-status-table",
|
||||
"version": 1,
|
||||
"specialization": "http",
|
||||
"title": "Status codes",
|
||||
"seed_generator": {
|
||||
"statement_template": "Which status code does {{.situation}} return?",
|
||||
"table": {"rows": [
|
||||
{"values": {"situation": "a missing resource"}, "answer": "404", "distractors": ["400", "410", "500"]},
|
||||
{"values": {"situation": "a request without credentials"}, "answer": "401", "distractors": ["403", "407"]}
|
||||
]}
|
||||
},
|
||||
"answer_key": {"answer_format": "choice", "reference_solution": "Match the situation to the status code."},
|
||||
"rubric": {"principle": "Compare with the key.", "criteria": [{"id": "correct_answer", "description": "Selects the key."}]}
|
||||
}]
|
||||
}`
|
||||
|
||||
func TestTableFamilyBundleIsParsedAndDrafted(t *testing.T) {
|
||||
bundle, err := ParseBundle(strings.NewReader(tableBundleDocument))
|
||||
if err != nil {
|
||||
t.Fatalf("ParseBundle(table bundle) error = %v", err)
|
||||
}
|
||||
drafts, err := bundle.Drafts()
|
||||
if err != nil || len(drafts) != 1 {
|
||||
t.Fatalf("Drafts() = %d drafts, %v, want one", len(drafts), err)
|
||||
}
|
||||
if drafts[0].HashScheme() != 2 {
|
||||
t.Fatalf("table family scheme = %d, want 2", drafts[0].HashScheme())
|
||||
}
|
||||
again, err := bundle.Drafts()
|
||||
if err != nil || again[0].ContentHash() != drafts[0].ContentHash() {
|
||||
t.Fatalf("Drafts() twice hashed differently: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTableFamilyBundleRefusesAFormatErrorWithTheRowIndex(t *testing.T) {
|
||||
broken := strings.Replace(tableBundleDocument, `"answer": "401"`, `"answer": "403"`, 1)
|
||||
bundle, err := ParseBundle(strings.NewReader(broken))
|
||||
if err != nil {
|
||||
t.Fatalf("ParseBundle() error = %v", err)
|
||||
}
|
||||
_, err = bundle.Drafts()
|
||||
if !errors.Is(err, domain.ErrInvalidAssessmentFamily) || !strings.Contains(err.Error(), "rows[1]") {
|
||||
t.Fatalf("Drafts(answer repeated among the distractors) error = %v, want ErrInvalidAssessmentFamily naming rows[1]", err)
|
||||
}
|
||||
|
||||
// An unknown field of a row is a format error at parse time: the table
|
||||
// holds data only, and a field that could carry code is not ignored.
|
||||
for name, replacement := range map[string]string{
|
||||
"a script field": `"values": {"situation": "a missing resource"}, "script": "1+1", "answer": "404"`,
|
||||
"a formula field": `"values": {"situation": "a missing resource"}, "formula": "len(values)", "answer": "404"`,
|
||||
} {
|
||||
document := strings.Replace(tableBundleDocument, `"values": {"situation": "a missing resource"}, "answer": "404"`, replacement, 1)
|
||||
if _, err := ParseBundle(strings.NewReader(document)); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("ParseBundle(%s) error = %v, want ErrInvalidAssessmentFamily", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,3 +38,5 @@ Seed algorithms are registered in `internal/domain/assessment_algorithms.go`
|
||||
under versioned names (`rate_limit_window.v1`, `dedup_window.v1`,
|
||||
`lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`); the statement
|
||||
templates use the parameter names and the data names of the chosen algorithm.
|
||||
A family can instead declare a `table` of variants with their answers in its
|
||||
`seed_generator`; this bundle uses only algorithms.
|
||||
@@ -667,8 +667,9 @@ Implemented as storage and a loader, not as a candidate-facing feature: migratio
|
||||
- Family version. One `assessment_families` row is one version of one family (`family_key`, `version`): category, specialization (the domain inside the category), title, author (`ai:<name>` or `operator:<handle>`), reviewer (`operator:<handle>` or NULL), `review_status` (`pending`, `approved`, `rejected`), the seed generator, the answer key, the rubric, a content hash with its `hash_scheme`, a lifecycle (`draft`, `published`, `retired`), and the operators and times of publication and retirement. The reviewer is never the author, and a review is pending exactly while there is no reviewer (CHECK constraints; the domain applies the same rules). The reviewer in a bundle and the operator of a publication are declared values, not authenticated identities, until reviewer and operator accounts exist.
|
||||
- Immutability. The content of a stored version never changes: the trigger `assessment_families_guard_update` refuses every UPDATE that changes a column other than the lifecycle columns (`lifecycle`, `published_at`, `published_by`, `retired_at`, `retired_by`), and `assessment_families_refuse_removal` refuses DELETE and TRUNCATE, all with SQLSTATE 23000 and the constraint name `assessment_families_immutable`, which the adapter maps to `outbound.ErrAssessmentFamilyImmutable`. The lifecycle moves only forward (draft, published, retired), the trigger sets the times and keeps the publisher through a retirement, and a version is published only with an approved review by a reviewer (`assessment_families_published_requires_review`). A change is a new version with the next number; the loader accepts only version 1 for a new family and the successor of the latest version otherwise. A pending draft is never approved in place: its review is recorded by importing a new version of the family that carries the review, and the pending version stays an unpublished draft. The domain recomputes the content hash when it reads a row and returns `ErrAssessmentFamilyIntegrity` for a row changed outside the application. The hash is the SHA-256 of a canonical JSON document that holds the content without the bundle name, ID, lifecycle, and publication fields. The `hash_scheme` column (a smallint with a CHECK of the known values, one of the immutable columns) names the layout: the domain verifies a row with the hash function of the scheme the row was stored with, so a later scheme (a new function and a new CHECK value, never an edit of scheme 1) verifies new rows without invalidating old ones, and a row with an unknown scheme is refused; tests verify a row with its own scheme and pin the scheme 1 hash of a fixed input. As for `policy_versions`, a role that owns the table can still disable the triggers.
|
||||
- One published version per family. A partial unique index (`assessment_families_one_published_key`) allows at most one published version of a key. `Bank.PublishFamily` retires the published older version in the same transaction and refuses with `newer_version_published` when a newer version of the key exists in any state, a draft or a retired one included, so superseded content is never put back in the bank (earlier content is published again by importing it as a new version); `Bank.ActiveFamily` reads the single published version. Coverage counts each family once.
|
||||
- Seed generator and variants. A generator names a registered algorithm with a versioned name (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`), the ranges of its parameters, and a statement template. A seed selects a variant: the same version and seed always give the same statement and reference answer (the pseudo-random source is SplitMix64 written out in the domain, so variants stay reproducible across Go releases; golden tests pin one statement and answer per algorithm), and the rubric is a property of the family, so no seed changes it. The reference answer comes from the algorithm's solver, which has unit tests with hand-computed cases. The registry only grows: a changed algorithm gets a new name, because stored versions refer to the old one.
|
||||
- Seed generator and variants. A generator is either algorithmic or a table (see "Table generators" below). An algorithmic generator names a registered algorithm with a versioned name (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`), the ranges of its parameters, and a statement template. A seed selects a variant: the same version and seed always give the same statement and reference answer (the pseudo-random source is SplitMix64 written out in the domain, so variants stay reproducible across Go releases; golden tests pin one statement and answer per algorithm), and the rubric is a property of the family, so no seed changes it. The reference answer comes from the algorithm's solver, which has unit tests with hand-computed cases. The registry only grows: a changed algorithm gets a new name, because stored versions refer to the old one.
|
||||
- Choice answer format. The answer format `choice` offers options instead of asking for a value. A choice variant stores its options and the key on the server: the frozen variant holds the options in presentation order, each with an opaque ID and a text, and the reference answer is the decimal index of the correct one. The candidate receives the option IDs and texts in that order (`ChoiceItemContent` of the public contract, `multiple` false) and nothing else: not the index, not the seed, and not how a distractor was made (the allowlisted projection and the response snapshot are checked for this). The seed decides the order of the options and the IDs: the order is a seeded Fisher-Yates shuffle, and each ID is drawn after the shuffle, so an ID says nothing about the position or the correctness of its option; the same family version and seed give the same options in the same order. A choice answer names the selected option IDs (`{"format":"choice","option_ids":[...]}`); the server grades it against the key. An ID that is not an option of the item, a second option, or an answer of another format is an invalid answer (400), not a wrong one. Distractors come from the algorithm, not from chance: a choice algorithm returns the correct value and the wrong values of known error models, and the shared code removes duplicates and the correct value, lets the seed choose among the mistakes, and tops up from plausible nearby values only when the mistakes give too few distinct ones. The registered `lru_hits_choice.v1` asks for the number of cache hits and offers wrong counts from an off-by-one count in either direction, counting misses instead of hits, a cache where a hit does not renew a key (FIFO), a cache that evicts the most recently used key, and a capacity off by one in either direction; its parameter bounds guarantee enough distinct values. The signals observe a choice answer as an answer of a small answer space, like an integer (`domain.SignalAnswerFormat`), so the observation column keeps its two classes. A choice variant is stored with an `Options` field in the frozen variant document, which is omitted for the other formats, so stored attempts keep decoding.
|
||||
- Table generators. A family can declare its variants as data instead of naming an algorithm: `seed_generator.table.rows` is a list of rows, each with `values` (the text of every placeholder), an `answer`, and for the answer format `choice` the `distractors`. The seed selects one row (SplitMix64 under the fixed name `table.v1`, so the selection is reproducible and changes only with a new name), the statement template substitutes the row values exactly as it does for an algorithm (the same text and `{{.name}}` whitelist, so a table cannot carry code), and the answer is the one written in the row: nothing is computed from the table. The table is validated at import, and a failure names the row by its zero-based index in the array (`rows[2]`) without quoting content: 2 to 500 rows, 1 to 16 columns with lowercase names, the same columns in every row, values of 1 to 1000 bytes without control or format characters, no repeated row, every column present in the template and no other placeholder, a rendered statement of at most 8 KiB for every row, at most 64 KiB of text in all, an answer format of `integer` (a canonical decimal integer of at most 15 digits, so a JSON number carries it exactly, and no distractors) or `choice` (a one-line answer of at most 500 bytes and 1 to 9 distinct distractors that do not repeat the answer). The answer key must name the same format. A table family has no algorithm and no parameters, is hashed with scheme 2, and is as immutable as any version. Algorithms in Go remain for tasks whose answer must be computed. The variant keeps the row index as a private parameter `row`.
|
||||
- Statement templates. A template is plain text with `{{.name}}` placeholders and nothing else: the text/template parser reads it without functions, and a whitelist walk refuses every node except text and a single field action (so `define`, `template`, `block`, `range`, `with`, `if`, variables, pipelines, and calls such as `printf` are refused). The loader renders the placeholders itself, never runs the template engine, and caps the template at 2000 bytes and the rendered statement at 8 KiB. Every placeholder must belong to the algorithm, and the template must contain the placeholders the answer depends on (the input data and the answer-relevant parameters), so a statement always shows the input. A bundle is validated fully at import, with probe renders at the lowest parameter values and, for eight seeds each, at the highest values (the largest inputs) and at drawn values, so a template close to the size cap cannot pass on one lucky seed; reading a stored row does not repeat the probes, because the content hash proves the content is the one that passed them. Titles, templates, and rubric texts refuse control characters, Unicode format characters (for example bidirectional overrides), and the line and paragraph separators U+2028 and U+2029; the title CHECK constraint also refuses the common ones.
|
||||
- Rubric. A rubric holds a principle and a list of criteria. It has no points, weights, or pass mark; how criteria become a grade is not decided in the bank.
|
||||
- Lifecycle and the loader. `Bank.ImportBundle` stores every family of a bundle as a draft in one transaction and never publishes, whatever the review says; importing the same bundle again, also concurrently, reports the versions as unchanged. `Bank.PublishFamily` and `Bank.RetireFamily` take the operator, and refuse with a reason (`reviewer_missing`, `review_not_approved`, `not_draft`, `not_published`, `newer_version_published`); the refusal is a `*domain.AssessmentRefusalError` that carries the reason, and the sentinels of a race that the database decided (a lifecycle step that lost to another, a missing approved review, insufficient coverage) become the same refusals. Publishing, retiring, and opening take a transaction-scoped advisory lock of the category first, so they run one after another per category; `LockCategory` works only inside a transaction (the repository of a unit of work takes it, the standalone store returns `ErrAssessmentLockOutsideTransaction`).
|
||||
|
||||
@@ -183,7 +183,7 @@ A record that depends on policy values adds `policy_version_id uuid NOT NULL REF
|
||||
|
||||
### Assessment bank
|
||||
|
||||
Migration `00011_create_assessment_bank.sql` creates `assessment_families` (immutable family versions) and `assessment_category_openings`; the queries are in `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` is available through `UnitOfWork.AssessmentBank()` and `postgres.AssessmentBankStore` outside a transaction; `assessment.Bank` imports a `Bundle`, publishes a version as an operator (retiring the published older one), retires it, opens a category under the policy version in force, reports live availability, and generates a variant of a seed. To change a family, import a new version; a stored version is never edited, and a pending draft is approved by importing a new version that carries the review. A new seed algorithm gets a new versioned name in `domain/assessment_algorithms.go`, its required placeholders, a solver test with hand-computed cases, and a golden test; never change a registered algorithm. An algorithm with the answer format `choice` sets `generateChoice` instead of `generate` and returns the correct value with the wrong values of named error models (`lru_hits_choice.v1` is the example); its tests recompute the error models from the statement. The demo bundle in `backend/testdata/assessment/` is an unreviewed AI draft: do not fill in its reviewer to open the category. See [ARCHITECTURE.md](ARCHITECTURE.md#assessment-bank).
|
||||
Migration `00011_create_assessment_bank.sql` creates `assessment_families` (immutable family versions) and `assessment_category_openings`; the queries are in `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` is available through `UnitOfWork.AssessmentBank()` and `postgres.AssessmentBankStore` outside a transaction; `assessment.Bank` imports a `Bundle`, publishes a version as an operator (retiring the published older one), retires it, opens a category under the policy version in force, reports live availability, and generates a variant of a seed. To change a family, import a new version; a stored version is never edited, and a pending draft is approved by importing a new version that carries the review. A new seed algorithm gets a new versioned name in `domain/assessment_algorithms.go`, its required placeholders, a solver test with hand-computed cases, and a golden test; never change a registered algorithm. An algorithm with the answer format `choice` sets `generateChoice` instead of `generate` and returns the correct value with the wrong values of named error models (`lru_hits_choice.v1` is the example); its tests recompute the error models from the statement. A family whose variants are fixed data uses a table generator instead of an algorithm: `seed_generator.table.rows` with `values`, `answer`, and for `choice` the `distractors`, validated at import with the row index in the error and stored with hash scheme 2; use a Go algorithm when the answer must be computed. Migration `00047_allow_table_hash_scheme.sql` allows scheme 2. Statement templates are plain text with `{{.name}}` placeholders only. The demo bundle in `backend/testdata/assessment/` is an unreviewed AI draft: do not fill in its reviewer to open the category. See [ARCHITECTURE.md](ARCHITECTURE.md#assessment-bank).
|
||||
|
||||
### Outbox relay
|
||||
|
||||
|
||||
+3
-2
@@ -498,7 +498,7 @@ Unit tests (`make -C backend test`) check the visibility rules without a databas
|
||||
|
||||
## Assessment bank tests
|
||||
|
||||
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go`, and `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) check without a database: invalid family content is refused (review rules, unknown algorithm, parameter bounds, answer format mismatch, rubric shape, Unicode format characters); statement templates accept only text and `{{.name}}` placeholders, and a nested `define` bomb, a `printf` width bomb, a `range` over a number, and a recursive `block` are refused within a second without being run; a template without the placeholders its answer depends on is refused; the rendered statement size is bounded; a changed stored document fails the hash check; each publication refusal names its reason; one seed gives one variant while the rubric stays the same across seeds; golden tests pin the exact statement and reference answer of a fixed seed for each of the four algorithms and the scheme 1 content hash of a fixed input; a row is verified with the hash scheme it was stored with (a test registers a second scheme, and a hash of one scheme under the name of the other, or an unknown scheme, is refused); a template whose statement reaches the size bound for one probe seed only is refused at import, because the highest parameter values are rendered for eight seeds; the line and paragraph separators are refused like format characters; the four solvers match hand-computed cases; the coverage required for an opening is `max_scored_items` plus `seed_items` of the policy; and the demo bundle parses as an AI draft with a pending review and no reviewer. `assessment_choice_test.go` covers the choice format without a database: the same seed gives identical options, IDs, and order, and across 400 seeds the correct option appears at every position; every distractor of `lru_hits_choice.v1` is recomputed from the statement as the result of a named error model (and the nearby fill-in is used only when the models give fewer than three distinct values), the options never repeat a text, the cache models match hand-computed cases and the LRU model equals the solver of `lru_hits.v1`, and a golden test pins the options, their IDs, and the key of one seed; the correct option, a wrong option, an option of no item, two options, a number answer for a choice item, and a choice answer for an integer item are graded or refused as stated, the candidate projection holds only the opaque IDs and texts, and a broken key or repeated option of a frozen variant is refused.
|
||||
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go`, and `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) check without a database: invalid family content is refused (review rules, unknown algorithm, parameter bounds, answer format mismatch, rubric shape, Unicode format characters); statement templates accept only text and `{{.name}}` placeholders, and a nested `define` bomb, a `printf` width bomb, a `range` over a number, and a recursive `block` are refused within a second without being run; a template without the placeholders its answer depends on is refused; the rendered statement size is bounded; a changed stored document fails the hash check; each publication refusal names its reason; one seed gives one variant while the rubric stays the same across seeds; golden tests pin the exact statement and reference answer of a fixed seed for each of the four algorithms and the scheme 1 content hash of a fixed input; a row is verified with the hash scheme it was stored with (a test registers a second scheme, and a hash of one scheme under the name of the other, or an unknown scheme, is refused); a template whose statement reaches the size bound for one probe seed only is refused at import, because the highest parameter values are rendered for eight seeds; the line and paragraph separators are refused like format characters; the four solvers match hand-computed cases; the coverage required for an opening is `max_scored_items` plus `seed_items` of the policy; and the demo bundle parses as an AI draft with a pending review and no reviewer. `assessment_choice_test.go` covers the choice format without a database: the same seed gives identical options, IDs, and order, and across 400 seeds the correct option appears at every position; every distractor of `lru_hits_choice.v1` is recomputed from the statement as the result of a named error model (and the nearby fill-in is used only when the models give fewer than three distinct values), the options never repeat a text, the cache models match hand-computed cases and the LRU model equals the solver of `lru_hits.v1`, and a golden test pins the options, their IDs, and the key of one seed; the correct option, a wrong option, an option of no item, two options, a number answer for a choice item, and a choice answer for an integer item are graded or refused as stated, the candidate projection holds only the opaque IDs and texts, and a broken key or repeated option of a frozen variant is refused. `assessment_table_test.go` covers table families: rows are selected by seed, the answer is the written one, the selection of fixed seeds is pinned, each of 39 format errors (missing column, repeated row, bad answer, duplicate distractor, oversized statement, a call or pipeline in the template, an algorithm beside a table, and so on) is refused with the index of the row, the scheme 2 hash of a fixed table is pinned against its canonical document, any change of the table changes the hash, scheme 1 and scheme 2 each refuse the other kind of generator, and an edited stored table fails the integrity check. `bundle_test.go` reads a table bundle and refuses a row with an unknown field. With in-memory fakes of the repository and the unit of work, the usecase tests prove that a concurrent identical import reports the version as unchanged and a concurrent import with other content is refused, that the sentinels of database races become refusals with the matching reason, that publishing retires the older published version after taking the category lock and is refused when a newer one is published, that opening requires the policy version in force, that availability is refused when the published count falls below the opening's requirement or when the opening's policy version is no longer in force, and that an older approved draft is refused while a newer version exists as a draft, a published, or a retired one. `internal/adapter/secondary/postgres/assessment_bank_test.go` checks that the bank constraints map to their sentinels without the failing row, that a list page outside its limit fails before any statement, and that the category lock is refused outside a transaction.
|
||||
|
||||
`TestAssessmentBank` in `backend/integration_test/assessment_bank_test.go` uses `bootstrap(t, postgresService)` and gives every case its own migrated database:
|
||||
|
||||
@@ -510,7 +510,8 @@ Unit tests (`make -C backend test`) check the visibility rules without a databas
|
||||
- Publishing a later version of a family retires the published older version and records both operators; publishing an older version while a newer one is published is refused; the table allows one published version per family and refuses a rewrite of the recorded publisher.
|
||||
- A transaction that holds the category lock makes an opening wait until the deadline, and the opening succeeds after the lock is released.
|
||||
- An older approved draft cannot be published once a newer version exists, also when that version is retired. Policy-in-force checks use the database clock, with no clock offset in the test.
|
||||
- `TestAssessmentChoiceFamiliesAreServedAndGradedOverHTTP` in `backend/integration_test/assessment_choice_http_test.go` runs a real attempt over a bank of a choice algorithm and an integer algorithm: every item the candidate receives has only the allowlisted fields (for a choice the option IDs and texts in the stored order, and no key, seed, or distractor field), an option of no item and two options are refused with 400, a wrong choice scores nothing and a right one scores through the key, the result matches the expected points, and every answer left a signal observation.
|
||||
- A bundle with a table family and a choice family is imported with hash scheme 2 for the tables and scheme 1 for the algorithm, imported again as unchanged, and the stored rows generate the same variants twice; a raw edit of a stored table is refused as an edit of a stored version.
|
||||
- `TestAssessmentChoiceAndTableFamiliesAreServedAndGradedOverHTTP` in `backend/integration_test/assessment_choice_http_test.go` runs a real attempt over a bank of a choice algorithm, an integer table, and a choice table: every item the candidate receives has only the allowlisted fields (for a choice the option IDs and texts in the stored order, and no key, seed, or distractor field), an option of no item and two options are refused with 400, a wrong choice scores nothing and a right one scores through the key, the result matches the expected points, and every answer left a signal observation.
|
||||
- Raw policy rows whose document lacks the scored item bounds or holds them as text, as an oversized, fractional, or negative number, or without the seed items are refused by the opening trigger with the thresholds refusal, not with a cast error; a stored hash scheme outside the CHECK list is refused, and the scheme cannot be edited.
|
||||
- Written around the usecase, an opening that claims a lower requirement, an opening below the coverage, an opening under an unknown policy version, and a title with a bidirectional override are refused by the table.
|
||||
- Families are listed in pages of two after a cursor, each once and in order.
|
||||
|
||||
@@ -667,8 +667,9 @@ contact_grant относится к паре кандидат-компания
|
||||
- Версия семейства. Одна строка `assessment_families` - одна версия одного семейства (`family_key`, `version`): категория, специализация (область внутри категории), название, автор (`ai:<name>` или `operator:<handle>`), рецензент (`operator:<handle>` или NULL), `review_status` (`pending`, `approved`, `rejected`), генератор по seed, ключ ответа, рубрика, хеш содержимого с его `hash_scheme`, жизненный цикл (`draft`, `published`, `retired`) и операторы и время публикации и вывода из обращения. Рецензент не бывает автором, а рецензия остается `pending`, пока рецензента нет (CHECK-ограничения; домен применяет те же правила). Рецензент в пакете и оператор публикации - заявленные значения, а не аутентифицированные личности, пока нет учетных записей рецензентов и операторов.
|
||||
- Неизменяемость. Содержимое сохраненной версии не меняется: триггер `assessment_families_guard_update` отклоняет любой UPDATE, который меняет колонки кроме колонок жизненного цикла (`lifecycle`, `published_at`, `published_by`, `retired_at`, `retired_by`), а `assessment_families_refuse_removal` отклоняет DELETE и TRUNCATE, все с SQLSTATE 23000 и именем ограничения `assessment_families_immutable`, которое адаптер преобразует в `outbound.ErrAssessmentFamilyImmutable`. Жизненный цикл идет только вперед (draft, published, retired), время ставит триггер и он же сохраняет публикатора при выводе из обращения, а версия публикуется только с одобренной рецензией рецензента (`assessment_families_published_requires_review`). Изменение - это новая версия со следующим номером: загрузчик принимает версию 1 для нового семейства и преемника последней версии для существующего. Черновик с рецензией `pending` никогда не одобряется на месте: рецензия записывается импортом новой версии семейства, которая ее несет, а версия `pending` остается неопубликованным черновиком. Домен пересчитывает хеш содержимого при чтении строки и возвращает `ErrAssessmentFamilyIntegrity`, если строку изменили вне приложения. Хеш - это SHA-256 канонического JSON-документа, который содержит содержимое без имени пакета, ID, жизненного цикла и полей публикации. Колонка `hash_scheme` (smallint с CHECK известных значений, одна из неизменяемых колонок) называет формат: домен проверяет строку хеш-функцией той схемы, с которой строка сохранена, поэтому следующая схема (новая функция и новое значение CHECK, а не правка схемы 1) проверяет новые строки и не ломает старые, а строка с неизвестной схемой отклоняется; тесты проверяют строку ее собственной схемой и фиксируют хеш схемы 1 для заданного входа. Как и для `policy_versions`, роль-владелец таблицы все еще может отключить триггеры.
|
||||
- Одна опубликованная версия на семейство. Частичный уникальный индекс (`assessment_families_one_published_key`) допускает не более одной опубликованной версии ключа. `Bank.PublishFamily` в той же транзакции выводит из обращения опубликованную более старую версию и отказывает с `newer_version_published`, если существует более новая версия ключа в любом состоянии, включая черновик и выведенную из обращения, поэтому устаревшее содержимое не возвращается в банк (прежнее содержимое публикуется снова импортом как новая версия); `Bank.ActiveFamily` читает единственную опубликованную версию. Покрытие считает каждое семейство один раз.
|
||||
- Генератор и варианты. Генератор называет зарегистрированный алгоритм с версионным именем (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`), диапазоны его параметров и шаблон условия. Seed выбирает вариант: одинаковые версия и seed всегда дают одинаковые условие и эталонный ответ (источник псевдослучайных чисел - SplitMix64, записанный в домене, поэтому варианты воспроизводимы между версиями Go; golden-тесты фиксируют по одному условию и ответу на алгоритм), а рубрика - свойство семейства, поэтому seed ее не меняет. Эталонный ответ считает решатель алгоритма; для него есть unit-тесты с посчитанными вручную случаями. Реестр только растет: измененный алгоритм получает новое имя, потому что сохраненные версии ссылаются на старое.
|
||||
- Генератор и варианты. Генератор бывает алгоритмическим или табличным (см. "Табличные генераторы" ниже). Алгоритмический генератор называет зарегистрированный алгоритм с версионным именем (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`), диапазоны его параметров и шаблон условия. Seed выбирает вариант: одинаковые версия и seed всегда дают одинаковые условие и эталонный ответ (источник псевдослучайных чисел - SplitMix64, записанный в домене, поэтому варианты воспроизводимы между версиями Go; golden-тесты фиксируют по одному условию и ответу на алгоритм), а рубрика - свойство семейства, поэтому seed ее не меняет. Эталонный ответ считает решатель алгоритма; для него есть unit-тесты с посчитанными вручную случаями. Реестр только растет: измененный алгоритм получает новое имя, потому что сохраненные версии ссылаются на старое.
|
||||
- Формат ответа с выбором. Формат ответа `choice` предлагает варианты вместо ввода значения. Вариант с выбором хранит варианты ответа и ключ на сервере: замороженный вариант содержит варианты в порядке показа, у каждого непрозрачный ID и текст, а эталонный ответ - десятичный индекс правильного. Кандидат получает ID и тексты вариантов в этом порядке (`ChoiceItemContent` публичного контракта, `multiple` равно false) и ничего больше: ни индекса, ни seed, ни того, как сделан отвлекающий вариант (для этого проверяются проекция по белому списку и снимок ответа). Seed определяет порядок вариантов и ID: порядок - перемешивание Фишера-Йетса по seed, а каждый ID выбирается после перемешивания, поэтому ID ничего не говорит о позиции и правильности варианта; одинаковые версия семейства и seed дают одинаковые варианты в одинаковом порядке. Ответ с выбором называет выбранные ID (`{"format":"choice","option_ids":[...]}`), сервер оценивает его по ключу. ID, которого нет среди вариантов задания, второй вариант или ответ другого формата - это некорректный ответ (400), а не неверный. Отвлекающие варианты дает алгоритм, а не случай: алгоритм с выбором возвращает правильное значение и неверные значения известных моделей ошибок, а общий код убирает повторы и правильное значение, дает seed выбрать среди ошибок и добирает правдоподобными соседними значениями, только если ошибки дали слишком мало различных. Зарегистрированный `lru_hits_choice.v1` спрашивает число попаданий в кэш и предлагает неверные числа из ошибки на единицу в обе стороны, подсчета промахов вместо попаданий, кэша, где попадание не обновляет ключ (FIFO), кэша, вытесняющего самый недавний ключ, и емкости, неверной на единицу в обе стороны; границы его параметров гарантируют достаточно различных значений. Сигналы наблюдают ответ с выбором как ответ с малым пространством ответов, как целое число (`domain.SignalAnswerFormat`), поэтому колонка наблюдений сохраняет свои два класса. Вариант с выбором хранится с полем `Options` в документе замороженного варианта; для других форматов поле опускается, поэтому сохраненные попытки продолжают читаться.
|
||||
- Табличные генераторы. Семейство может задать варианты данными вместо имени алгоритма: `seed_generator.table.rows` - список строк, в каждой `values` (текст каждой подстановки), `answer` и для формата ответа `choice` еще `distractors`. Seed выбирает одну строку (SplitMix64 под фиксированным именем `table.v1`, поэтому выбор воспроизводим и меняется только вместе с новым именем), шаблон условия подставляет значения строки так же, как для алгоритма (тот же текст и белый список `{{.name}}`, так что таблица не может нести код), а ответ - тот, что записан в строке: из таблицы ничего не вычисляется. Таблица проверяется при импорте, и ошибка называет строку ее индексом в массиве от нуля (`rows[2]`) без цитирования содержимого: от 2 до 500 строк, от 1 до 16 столбцов со строчными именами, одинаковые столбцы в каждой строке, значения от 1 до 1000 байт без управляющих символов и символов формата, нет повторяющихся строк, каждый столбец есть в шаблоне и других подстановок нет, готовое условие каждой строки не больше 8 КиБ, всего не больше 64 КиБ текста, формат ответа `integer` (каноническое десятичное целое не длиннее 15 цифр, которое JSON-число передает точно, и без отвлекающих вариантов) или `choice` (ответ в одну строку не длиннее 500 байт и от 1 до 9 различных отвлекающих вариантов, не повторяющих ответ). Ключ ответа должен называть тот же формат. У табличного семейства нет алгоритма и параметров, оно хешируется схемой 2 и неизменяемо, как любая версия. Алгоритмы на Go остаются для заданий, ответ которых нужно вычислять. Вариант хранит индекс строки как закрытый параметр `row`.
|
||||
- Шаблоны условий. Шаблон - обычный текст с подстановками `{{.name}}` и ничем больше: парсер text/template читает его без функций, а обход по белому списку отклоняет любой узел кроме текста и одного обращения к полю (то есть `define`, `template`, `block`, `range`, `with`, `if`, переменные, конвейеры и вызовы вроде `printf` отклоняются). Загрузчик подставляет значения сам и не запускает движок шаблонов, ограничивает шаблон 2000 байтами, а готовое условие 8 КиБ. Каждая подстановка должна принадлежать алгоритму, а шаблон обязан содержать подстановки, от которых зависит ответ (входные данные и параметры, влияющие на ответ), поэтому условие всегда показывает вход. Пакет проверяется полностью при импорте, с пробными подстановками на наименьших значениях параметров и, по восемь seed каждая, на наибольших значениях (самые большие входы) и на выбранных значениях, поэтому шаблон у границы размера не пройдет из-за одного удачного seed; чтение сохраненной строки проб не повторяет, потому что хеш содержимого доказывает, что это то самое содержимое, которое их прошло. Названия, шаблоны и тексты рубрики отклоняют управляющие символы, символы формата Unicode (например, переопределения направления текста) и разделители строки и абзаца U+2028 и U+2029; CHECK-ограничение названия отклоняет самые распространенные из них.
|
||||
- Рубрика. Рубрика содержит принцип и список критериев. В ней нет баллов, весов и проходного порога; как критерии превращаются в грейд, банк не решает.
|
||||
- Жизненный цикл и загрузчик. `Bank.ImportBundle` сохраняет все семейства пакета как черновики в одной транзакции и никогда не публикует, что бы ни говорила рецензия; повторный импорт того же пакета, в том числе одновременный, сообщает версии как неизмененные. `Bank.PublishFamily` и `Bank.RetireFamily` принимают оператора и отказывают с причиной (`reviewer_missing`, `review_not_approved`, `not_draft`, `not_published`, `newer_version_published`); отказ - это `*domain.AssessmentRefusalError` с причиной, а sentinel-ошибки гонки, которую решила база (шаг жизненного цикла проиграл другому, нет одобренной рецензии, недостаточное покрытие), становятся теми же отказами. Публикация, вывод из обращения и открытие сначала берут транзакционную advisory-блокировку категории, поэтому выполняются по очереди в пределах категории; `LockCategory` работает только внутри транзакции (репозиторий единицы работы берет блокировку, автономное хранилище возвращает `ErrAssessmentLockOutsideTransaction`).
|
||||
|
||||
@@ -183,7 +183,7 @@ goose выполняет каждую миграцию в отдельной т
|
||||
|
||||
### Банк заданий оценки
|
||||
|
||||
Миграция `00011_create_assessment_bank.sql` создает `assessment_families` (неизменяемые версии семейств) и `assessment_category_openings`; запросы лежат в `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` доступен через `UnitOfWork.AssessmentBank()` и через `postgres.AssessmentBankStore` вне транзакции; `assessment.Bank` импортирует `Bundle`, публикует версию от имени оператора (выводя из обращения опубликованную более старую), выводит ее из обращения, открывает категорию под действующей версией политики, сообщает живую доступность и генерирует вариант по seed. Чтобы изменить семейство, импортируйте новую версию; сохраненная версия не редактируется, а черновик `pending` одобряется импортом новой версии с рецензией. Новый алгоритм seed получает новое версионное имя в `domain/assessment_algorithms.go`, обязательные подстановки, тест решателя с посчитанными вручную случаями и golden-тест; зарегистрированный алгоритм не меняйте. Алгоритм с форматом ответа `choice` задает `generateChoice` вместо `generate` и возвращает правильное значение вместе с неверными значениями именованных моделей ошибок (пример - `lru_hits_choice.v1`); его тесты пересчитывают модели ошибок по условию. Демонстрационный пакет в `backend/testdata/assessment/` - непроверенный черновик ИИ: не заполняйте в нем рецензента, чтобы открыть категорию. См. [ARCHITECTURE.md](ARCHITECTURE.md#банк-заданий-оценки).
|
||||
Миграция `00011_create_assessment_bank.sql` создает `assessment_families` (неизменяемые версии семейств) и `assessment_category_openings`; запросы лежат в `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` доступен через `UnitOfWork.AssessmentBank()` и через `postgres.AssessmentBankStore` вне транзакции; `assessment.Bank` импортирует `Bundle`, публикует версию от имени оператора (выводя из обращения опубликованную более старую), выводит ее из обращения, открывает категорию под действующей версией политики, сообщает живую доступность и генерирует вариант по seed. Чтобы изменить семейство, импортируйте новую версию; сохраненная версия не редактируется, а черновик `pending` одобряется импортом новой версии с рецензией. Новый алгоритм seed получает новое версионное имя в `domain/assessment_algorithms.go`, обязательные подстановки, тест решателя с посчитанными вручную случаями и golden-тест; зарегистрированный алгоритм не меняйте. Алгоритм с форматом ответа `choice` задает `generateChoice` вместо `generate` и возвращает правильное значение вместе с неверными значениями именованных моделей ошибок (пример - `lru_hits_choice.v1`); его тесты пересчитывают модели ошибок по условию. Семейство, варианты которого - фиксированные данные, использует табличный генератор вместо алгоритма: `seed_generator.table.rows` с `values`, `answer` и для `choice` еще `distractors`; при импорте таблица проверяется, ошибка называет индекс строки, а версия хранится со схемой хеша 2. Если ответ нужно вычислять, используйте алгоритм на Go. Схему 2 разрешает миграция `00047_allow_table_hash_scheme.sql`. Шаблоны условий - обычный текст только с подстановками `{{.name}}`. Демонстрационный пакет в `backend/testdata/assessment/` - непроверенный черновик ИИ: не заполняйте в нем рецензента, чтобы открыть категорию. См. [ARCHITECTURE.md](ARCHITECTURE.md#банк-заданий-оценки).
|
||||
|
||||
### Relay outbox
|
||||
|
||||
|
||||
+3
-2
@@ -498,7 +498,7 @@ Spec не проверяет запланированные переходы б
|
||||
|
||||
## Тесты банка заданий
|
||||
|
||||
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go` и `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) проверяют без базы: отклоняется некорректное содержимое семейства (правила рецензии, неизвестный алгоритм, границы параметров, несоответствие формата ответа, форма рубрики, символы формата Unicode); шаблоны условий принимают только текст и подстановки `{{.name}}`, а бомба из вложенных `define`, бомба ширины `printf`, `range` по числу и рекурсивный `block` отклоняются быстрее секунды и не запускаются; шаблон без подстановок, от которых зависит ответ, отклоняется; размер готового условия ограничен; измененный сохраненный документ не проходит проверку хеша; каждый отказ в публикации называет причину; один seed дает один вариант, а рубрика одинакова для всех seed; golden-тесты фиксируют точное условие и эталонный ответ для заданного seed у каждого из четырех алгоритмов и хеш содержимого схемы 1 для заданного входа; строка проверяется схемой хеша, с которой она сохранена (тест регистрирует вторую схему, а хеш одной схемы под именем другой и неизвестная схема отклоняются); шаблон, чье условие достигает границы размера только для одного пробного seed, отклоняется при импорте, потому что наибольшие значения параметров подставляются для восьми seed; разделители строки и абзаца отклоняются как символы формата; четыре решателя совпадают с посчитанными вручную случаями; покрытие для открытия равно `max_scored_items` плюс `seed_items` политики; демонстрационный пакет читается как черновик ИИ с рецензией `pending` и без рецензента. `assessment_choice_test.go` проверяет формат с выбором без базы: один seed дает одинаковые варианты, ID и порядок, а по 400 seed правильный вариант встречается на каждой позиции; каждый отвлекающий вариант `lru_hits_choice.v1` пересчитывается по условию как результат именованной модели ошибки (а добор соседними значениями используется, только если модели дали меньше трех различных значений), варианты не повторяют текст, модели кэша совпадают с посчитанными вручную случаями, а модель LRU равна решателю `lru_hits.v1`, golden-тест фиксирует варианты, их ID и ключ одного seed; правильный вариант, неверный вариант, вариант чужого задания, два варианта, числовой ответ на задание с выбором и ответ с выбором на целочисленное задание оцениваются или отклоняются, как описано, проекция для кандидата содержит только непрозрачные ID и тексты, а поврежденный ключ или повторяющийся вариант замороженного варианта отклоняются.
|
||||
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go` и `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) проверяют без базы: отклоняется некорректное содержимое семейства (правила рецензии, неизвестный алгоритм, границы параметров, несоответствие формата ответа, форма рубрики, символы формата Unicode); шаблоны условий принимают только текст и подстановки `{{.name}}`, а бомба из вложенных `define`, бомба ширины `printf`, `range` по числу и рекурсивный `block` отклоняются быстрее секунды и не запускаются; шаблон без подстановок, от которых зависит ответ, отклоняется; размер готового условия ограничен; измененный сохраненный документ не проходит проверку хеша; каждый отказ в публикации называет причину; один seed дает один вариант, а рубрика одинакова для всех seed; golden-тесты фиксируют точное условие и эталонный ответ для заданного seed у каждого из четырех алгоритмов и хеш содержимого схемы 1 для заданного входа; строка проверяется схемой хеша, с которой она сохранена (тест регистрирует вторую схему, а хеш одной схемы под именем другой и неизвестная схема отклоняются); шаблон, чье условие достигает границы размера только для одного пробного seed, отклоняется при импорте, потому что наибольшие значения параметров подставляются для восьми seed; разделители строки и абзаца отклоняются как символы формата; четыре решателя совпадают с посчитанными вручную случаями; покрытие для открытия равно `max_scored_items` плюс `seed_items` политики; демонстрационный пакет читается как черновик ИИ с рецензией `pending` и без рецензента. `assessment_choice_test.go` проверяет формат с выбором без базы: один seed дает одинаковые варианты, ID и порядок, а по 400 seed правильный вариант встречается на каждой позиции; каждый отвлекающий вариант `lru_hits_choice.v1` пересчитывается по условию как результат именованной модели ошибки (а добор соседними значениями используется, только если модели дали меньше трех различных значений), варианты не повторяют текст, модели кэша совпадают с посчитанными вручную случаями, а модель LRU равна решателю `lru_hits.v1`, golden-тест фиксирует варианты, их ID и ключ одного seed; правильный вариант, неверный вариант, вариант чужого задания, два варианта, числовой ответ на задание с выбором и ответ с выбором на целочисленное задание оцениваются или отклоняются, как описано, проекция для кандидата содержит только непрозрачные ID и тексты, а поврежденный ключ или повторяющийся вариант замороженного варианта отклоняются. `assessment_table_test.go` проверяет табличные семейства: строки выбираются по seed, ответ - записанный, выбор для фиксированных seed зафиксирован, каждая из 39 ошибок формата (нет столбца, повтор строки, неверный ответ, повторяющийся отвлекающий вариант, слишком большое условие, вызов или конвейер в шаблоне, алгоритм рядом с таблицей и другие) отклоняется с индексом строки, хеш схемы 2 Line truncated
|
||||
|
||||
`TestAssessmentBank` в `backend/integration_test/assessment_bank_test.go` использует `bootstrap(t, postgresService)` и дает каждому случаю свою мигрированную базу:
|
||||
|
||||
@@ -510,7 +510,8 @@ Spec не проверяет запланированные переходы б
|
||||
- Публикация более поздней версии семейства выводит из обращения опубликованную более старую и записывает обоих операторов; публикация более старой версии при опубликованной более новой отклоняется; таблица допускает одну опубликованную версию на семейство и отклоняет перезапись записанного публикатора.
|
||||
- Транзакция, держащая блокировку категории, заставляет открытие ждать до срока, а после освобождения блокировки открытие проходит.
|
||||
- Более старый одобренный черновик нельзя опубликовать, когда существует более новая версия, в том числе выведенная из обращения. Проверки действующей политики используют часы базы данных, без сдвига часов в тесте.
|
||||
- `TestAssessmentChoiceFamiliesAreServedAndGradedOverHTTP` в `backend/integration_test/assessment_choice_http_test.go` проходит настоящую попытку по банку из алгоритма с выбором и целочисленного алгоритма: каждое задание, которое получает кандидат, содержит только разрешенные поля (для выбора - ID и тексты вариантов в сохраненном порядке, без поля ключа, seed или отвлекающего варианта), вариант чужого задания и два варианта отклоняются с 400, неверный выбор не дает баллов, а верный дает их по ключу, результат совпадает с ожидаемым числом баллов, и каждый ответ оставил наблюдение сигналов.
|
||||
- Пакет с табличным семейством и семейством с выбором импортируется: таблицы со схемой хеша 2, алгоритм со схемой 1; повторный импорт сообщает их как неизмененные, а сохраненные строки дважды дают одинаковые варианты; прямая правка сохраненной таблицы отклоняется как правка сохраненной версии.
|
||||
- `TestAssessmentChoiceAndTableFamiliesAreServedAndGradedOverHTTP` в `backend/integration_test/assessment_choice_http_test.go` проходит настоящую попытку по банку из алгоритма с выбором, целочисленной таблицы и таблицы с выбором: каждое задание, которое получает кандидат, содержит только разрешенные поля (для выбора - ID и тексты вариантов в сохраненном порядке, без поля ключа, seed или отвлекающего варианта), вариант чужого задания и два варианта отклоняются с 400, неверный выбор не дает баллов, а верный дает их по ключу, результат совпадает с ожидаемым числом баллов, и каждый ответ оставил наблюдение сигналов.
|
||||
- Сырые строки политики, в документе которых нет границ оцениваемых заданий, они заданы текстом, слишком большим, дробным или отрицательным числом или нет seed-заданий, отклоняются триггером открытия отказом по порогам, а не ошибкой приведения типа; сохраненная схема хеша вне списка CHECK отклоняется, а саму схему изменить нельзя.
|
||||
- В обход usecase таблица отклоняет открытие с заниженным требованием, открытие ниже покрытия, открытие под неизвестной версией политики и название с переопределением направления текста.
|
||||
- Семейства выводятся страницами по две после курсора, каждое один раз и по порядку.
|
||||
|
||||
Reference in new issue
Block a user