403 lines
15 KiB
Go
403 lines
15 KiB
Go
//go:build e2e
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/binary"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"lincodex/backend/internal/adapter/secondary/postgres"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/usecase/assessment"
|
|
"lincodex/backend/internal/usecase/policy"
|
|
)
|
|
|
|
const (
|
|
fixtureEnabledName = "E2E_QUESTIONNAIRE_FIXTURE"
|
|
fixtureTimeout = 90 * time.Second
|
|
maxFixtureFamilies = 200
|
|
|
|
fixtureBundleName = "e2e-questionnaire-bank"
|
|
fixtureAuthor = "operator:questionnaire-fixture-author"
|
|
fixtureReviewer = "operator:questionnaire-fixture-reviewer"
|
|
fixturePublisher = domain.AssessmentOperator("operator:questionnaire-fixture-publisher")
|
|
fixtureOpener = domain.AssessmentOperator("operator:questionnaire-fixture-opener")
|
|
fixtureFamilyStem = "e2e-questionnaire-family-"
|
|
fixtureCategory = domain.AssessmentCategory("backend")
|
|
trainingFamilyStem = "e2e-express-family-"
|
|
trainingCategory = "e2e-express"
|
|
)
|
|
|
|
func main() {
|
|
if err := run(context.Background(), os.Args[1:], os.LookupEnv); err != nil {
|
|
if _, writeErr := fmt.Fprintln(os.Stderr, err); writeErr != nil {
|
|
os.Exit(1)
|
|
}
|
|
os.Exit(1)
|
|
}
|
|
if _, err := fmt.Fprintln(os.Stdout, "Questionnaire bank fixture is ready."); err != nil {
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
func run(
|
|
parent context.Context,
|
|
args []string,
|
|
lookupEnv func(string) (string, bool),
|
|
) error {
|
|
if len(args) != 0 {
|
|
return errors.New("questionnaire fixture accepts no arguments")
|
|
}
|
|
enabled, _ := lookupEnv(fixtureEnabledName)
|
|
if enabled != "1" {
|
|
return errors.New("questionnaire fixture requires E2E_QUESTIONNAIRE_FIXTURE=1")
|
|
}
|
|
databaseURL, _ := lookupEnv("DATABASE_URL")
|
|
if databaseURL == "" {
|
|
return errors.New("questionnaire fixture database is not configured")
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(parent, fixtureTimeout)
|
|
defer cancel()
|
|
pool, err := postgres.NewSizedPool(ctx, databaseURL, 4)
|
|
if err != nil {
|
|
return errors.New("questionnaire fixture could not open its database")
|
|
}
|
|
defer pool.Close()
|
|
if err := pool.Ping(ctx); err != nil {
|
|
return errors.New("questionnaire fixture database is unavailable")
|
|
}
|
|
if err := seedQuestionnaireBank(ctx, pool); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func seedQuestionnaireBank(ctx context.Context, pool *pgxpool.Pool) error {
|
|
const location = "questionnaire fixture"
|
|
occupied, err := backendQuestionnaireBankOccupied(ctx, pool)
|
|
if err != nil {
|
|
return errors.New(location + " could not inspect backend bank state")
|
|
}
|
|
if occupied {
|
|
return errors.New(location + " refuses existing backend openings or published families")
|
|
}
|
|
trainingOccupied, err := questionnaireTrainingBankOccupied(ctx, pool)
|
|
if err != nil {
|
|
return errors.New(location + " could not inspect training bank state")
|
|
}
|
|
if trainingOccupied {
|
|
return errors.New(location + " refuses an existing training binding or published families")
|
|
}
|
|
|
|
transactor := postgres.NewTransactor(pool)
|
|
currentPolicy, err := publishFixturePolicy(ctx, transactor)
|
|
if err != nil {
|
|
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
|
|
return errors.New(location + " requires a current product assessment policy")
|
|
}
|
|
return errors.New(location + " could not read the current product policy")
|
|
}
|
|
required, err := domain.RequiredPublishedAssessmentFamilies(currentPolicy.Policy())
|
|
if err != nil || required < 1 || required > maxFixtureFamilies {
|
|
return errors.New(location + " current policy has an unsupported family threshold")
|
|
}
|
|
bundle, err := reviewedQuestionnaireBundle(int(required))
|
|
if err != nil {
|
|
return errors.New(location + " reviewed family fixture is invalid")
|
|
}
|
|
|
|
bank := assessment.NewBank(transactor)
|
|
if _, err := bank.ImportBundle(ctx, bundle); err != nil {
|
|
return errors.New(location + " could not import reviewed families")
|
|
}
|
|
for _, family := range bundle.Families {
|
|
if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil {
|
|
return errors.New(location + " could not publish reviewed families")
|
|
}
|
|
}
|
|
metadata, err := questionnaireCatalogMetadata()
|
|
if err != nil {
|
|
return errors.New(location + " public catalog mapping is invalid")
|
|
}
|
|
if _, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{
|
|
Category: fixtureCategory, GradingPolicyID: currentPolicy.ID(), OpenedBy: fixtureOpener,
|
|
CatalogMetadata: &metadata,
|
|
}); err != nil {
|
|
return errors.New(location + " could not open the reviewed catalog mapping")
|
|
}
|
|
if err := seedQuestionnaireTrainingBank(ctx, pool, bank, currentPolicy); err != nil {
|
|
return errors.New(location + " could not seed the reviewed express training bank")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func questionnaireTrainingBankOccupied(ctx context.Context, pool *pgxpool.Pool) (bool, error) {
|
|
var occupied bool
|
|
err := pool.QueryRow(ctx, `
|
|
SELECT EXISTS (
|
|
SELECT 1 FROM assessment_training_bank_bindings WHERE category = $1
|
|
) OR EXISTS (
|
|
SELECT 1 FROM assessment_families
|
|
WHERE category = $1 AND family_key LIKE $2
|
|
)`, trainingCategory, trainingFamilyStem+"%").Scan(&occupied)
|
|
return occupied, err
|
|
}
|
|
|
|
func seedQuestionnaireTrainingBank(
|
|
ctx context.Context,
|
|
pool *pgxpool.Pool,
|
|
bank *assessment.Bank,
|
|
productPolicy domain.PolicyVersion,
|
|
) error {
|
|
trainingPolicy := productPolicy.Policy().Assessment.Training
|
|
if trainingPolicy == nil {
|
|
return errors.New("current product policy has no explicit training mode")
|
|
}
|
|
count := int(trainingPolicy.DemoExpressItemCount)
|
|
if count < 1 || count > maxFixtureFamilies {
|
|
return errors.New("training item count is outside the fixture limit")
|
|
}
|
|
bundle, err := reviewedTrainingBundle(count)
|
|
if err != nil {
|
|
return errors.New("reviewed training family fixture is invalid")
|
|
}
|
|
if _, err := bank.ImportBundle(ctx, bundle); err != nil {
|
|
return errors.New("could not import reviewed training families")
|
|
}
|
|
for _, family := range bundle.Families {
|
|
if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil {
|
|
return errors.New("could not publish reviewed training family")
|
|
}
|
|
}
|
|
return seedQuestionnaireTrainingBinding(ctx, pool, productPolicy.ID().UUID(), bundle.Category, count)
|
|
}
|
|
|
|
func reviewedTrainingBundle(count int) (assessment.Bundle, error) {
|
|
bundle, err := reviewedQuestionnaireBundle(count)
|
|
if err != nil {
|
|
return assessment.Bundle{}, err
|
|
}
|
|
bundle.Name = "e2e-express-training-bank"
|
|
bundle.Category = trainingCategory
|
|
for index := range bundle.Families {
|
|
bundle.Families[index].Key = fmt.Sprintf("%s%02d", trainingFamilyStem, index+1)
|
|
bundle.Families[index].Specialization = "rate-limiting"
|
|
}
|
|
if _, err := bundle.Drafts(); err != nil {
|
|
return assessment.Bundle{}, err
|
|
}
|
|
return bundle, nil
|
|
}
|
|
|
|
func seedQuestionnaireTrainingBinding(
|
|
ctx context.Context,
|
|
pool *pgxpool.Pool,
|
|
policyID uuid.UUID,
|
|
category string,
|
|
itemCount int,
|
|
) error {
|
|
type manifestEntry struct {
|
|
FamilyKey string `json:"family_key"`
|
|
Version int32 `json:"version"`
|
|
ContentSHA256 string `json:"content_sha256"`
|
|
}
|
|
type familyRecord struct {
|
|
ID uuid.UUID
|
|
Entry manifestEntry
|
|
Hash []byte
|
|
}
|
|
rows, err := pool.Query(ctx, `
|
|
SELECT id, family_key, version, content_sha256
|
|
FROM assessment_families
|
|
WHERE category=$1 AND lifecycle='published'
|
|
ORDER BY family_key, version`, category)
|
|
if err != nil {
|
|
return errors.New("could not read published training families")
|
|
}
|
|
var families []familyRecord
|
|
for rows.Next() {
|
|
var family familyRecord
|
|
if err := rows.Scan(&family.ID, &family.Entry.FamilyKey, &family.Entry.Version, &family.Hash); err != nil {
|
|
rows.Close()
|
|
return errors.New("could not read a published training family")
|
|
}
|
|
family.Entry.ContentSHA256 = hex.EncodeToString(family.Hash)
|
|
families = append(families, family)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
rows.Close()
|
|
return errors.New("could not finish reading training families")
|
|
}
|
|
rows.Close()
|
|
if len(families) != itemCount {
|
|
return errors.New("published training family count does not match policy")
|
|
}
|
|
entries := make([]manifestEntry, len(families))
|
|
canonical := []byte("lincodex.assessment.category-manifest.v1\x00")
|
|
for index, family := range families {
|
|
if len(family.Entry.FamilyKey) > 64 || family.Entry.Version < 1 || len(family.Hash) != sha256.Size {
|
|
return errors.New("training family manifest entry is outside the supported range")
|
|
}
|
|
entries[index] = family.Entry
|
|
key := []byte(family.Entry.FamilyKey)
|
|
canonical = binary.BigEndian.AppendUint32(canonical, uint32(len(key)))
|
|
canonical = append(canonical, key...)
|
|
canonical = binary.BigEndian.AppendUint32(canonical, uint32(family.Entry.Version))
|
|
canonical = append(canonical, family.Hash...)
|
|
}
|
|
manifest, err := json.Marshal(entries)
|
|
if err != nil {
|
|
return errors.New("could not encode training family manifest")
|
|
}
|
|
manifestHash := sha256.Sum256(canonical)
|
|
transaction, err := pool.Begin(ctx)
|
|
if err != nil {
|
|
return errors.New("could not begin training binding transaction")
|
|
}
|
|
defer transaction.Rollback(ctx)
|
|
bindingID := uuid.New()
|
|
if _, err := transaction.Exec(ctx, `
|
|
INSERT INTO assessment_training_bank_bindings (
|
|
id, category, product_policy_version_id, item_count, manifest_sha256, family_manifest, reviewed_by, created_at
|
|
) VALUES ($1,$2,$3,$4,$5,$6::jsonb,'operator:fixture-reviewer',clock_timestamp())`,
|
|
bindingID, category, policyID, itemCount, manifestHash[:], manifest); err != nil {
|
|
return errors.New("could not insert the training binding")
|
|
}
|
|
for index, family := range families {
|
|
if _, err := transaction.Exec(ctx, `
|
|
INSERT INTO assessment_training_bank_binding_families (
|
|
binding_id, ordinal, family_id, family_key, family_version, content_sha256
|
|
) VALUES ($1,$2,$3,$4,$5,$6)`,
|
|
bindingID, index+1, family.ID, family.Entry.FamilyKey, family.Entry.Version, family.Hash); err != nil {
|
|
return errors.New("could not add a training binding family")
|
|
}
|
|
}
|
|
if err := transaction.Commit(ctx); err != nil {
|
|
return errors.New("could not commit the training binding")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func questionnaireCatalogMetadata() (domain.AssessmentCategoryCatalogMetadata, error) {
|
|
return domain.NewAssessmentCategoryCatalogMetadata(
|
|
domain.SpecializationBackend,
|
|
domain.GradeJunior,
|
|
[]domain.TaskLanguageCode{domain.TaskLanguageGo, domain.TaskLanguagePython},
|
|
)
|
|
}
|
|
|
|
func backendQuestionnaireBankOccupied(ctx context.Context, pool *pgxpool.Pool) (bool, error) {
|
|
var occupied bool
|
|
err := pool.QueryRow(ctx, `
|
|
SELECT
|
|
EXISTS (SELECT 1 FROM assessment_category_openings WHERE category = $1)
|
|
OR EXISTS (
|
|
SELECT 1 FROM assessment_families
|
|
WHERE category = $1 AND lifecycle = 'published'
|
|
)
|
|
OR EXISTS (
|
|
SELECT 1 FROM assessment_families
|
|
WHERE category = $1 AND family_key LIKE $2
|
|
)`, string(fixtureCategory), fixtureFamilyStem+"%").Scan(&occupied)
|
|
return occupied, err
|
|
}
|
|
|
|
// The isolated browser fixture opts into the extended demo policy explicitly,
|
|
// including the manual-review band thresholds and the matching coefficients.
|
|
// Normal startup still seeds V1, and an operator's policy must never be
|
|
// replaced.
|
|
func publishFixturePolicy(ctx context.Context, transactor outbound.Transactor) (domain.PolicyVersion, error) {
|
|
initial, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
|
|
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo,
|
|
Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV1(),
|
|
})
|
|
if err != nil {
|
|
return domain.PolicyVersion{}, err
|
|
}
|
|
var version domain.PolicyVersion
|
|
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
current, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, databaseTime)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
latest, err := unit.Policies().GetLatest(ctx, domain.ProductPolicyKey)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if current.Kind() != domain.PolicyKindDemo || current.DocumentHash() != initial.DocumentHash() ||
|
|
current.Version() != 1 || current.ID() != latest.ID() {
|
|
return errors.New("questionnaire fixture refuses an operator-owned product policy")
|
|
}
|
|
version, err = policy.NewPublisher(unit.Policies(), func() time.Time { return databaseTime }).Publish(ctx, policy.PublishInput{
|
|
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo,
|
|
Author: domain.PolicyAuthor(fixtureAuthor), Policy: domain.DemoProductPolicyV4(),
|
|
})
|
|
return err
|
|
})
|
|
return version, err
|
|
}
|
|
|
|
func reviewedQuestionnaireBundle(count int) (assessment.Bundle, error) {
|
|
if count < 1 || count > maxFixtureFamilies {
|
|
return assessment.Bundle{}, errors.New("questionnaire fixture family count is outside the supported range")
|
|
}
|
|
bundle := assessment.Bundle{
|
|
Name: fixtureBundleName, Category: string(fixtureCategory), Author: fixtureAuthor,
|
|
Review: assessment.BundleReview{Status: string(domain.AssessmentReviewApproved), Reviewer: fixtureReviewer},
|
|
Families: make([]assessment.BundleFamily, 0, count),
|
|
}
|
|
requestsMinimum := int32(12)
|
|
for index := range count {
|
|
familyNumber := index + 1
|
|
family := assessment.BundleFamily{
|
|
Key: fmt.Sprintf("%s%03d", fixtureFamilyStem, familyNumber), Version: 1,
|
|
Specialization: "rate-limiting", Title: fmt.Sprintf("Sliding-window fixture case %03d", familyNumber),
|
|
SeedGenerator: domain.AssessmentSeedGenerator{
|
|
Algorithm: "rate_limit_window.v1",
|
|
Parameters: map[string]domain.AssessmentParameterRange{
|
|
"requests": {Min: requestsMinimum, Max: requestsMinimum + 8},
|
|
"window": {Min: 3, Max: 15},
|
|
"limit": {Min: 2, Max: 6},
|
|
"max_gap": {Min: 1, Max: 5},
|
|
},
|
|
StatementTemplate: "A gateway applies a sliding-window limiter. A request at second t is accepted only when fewer than {{.limit}} previously accepted requests arrived in (t - {{.window}}, t]. Rejected requests are not remembered. The gateway receives {{.requests}} requests at these non-decreasing arrival times: {{.timestamps}}. How many requests are rejected?",
|
|
},
|
|
AnswerKey: domain.AssessmentAnswerKey{
|
|
AnswerFormat: domain.AnswerFormatInteger,
|
|
ReferenceSolution: "Keep accepted arrival times in order. Before each request at t, remove accepted times at or before t - window. Accept and append t when fewer than limit times remain; otherwise count a rejection without appending it. Each request enters and leaves the queue at most once.",
|
|
},
|
|
Rubric: domain.AssessmentRubric{
|
|
Principle: "The answer is the exact number of rejected requests for the generated arrival sequence. The rubric has criteria but no points or pass mark.",
|
|
Criteria: []domain.AssessmentRubricCriterion{
|
|
{ID: "correct_answer", Description: "The submitted integer equals the generated reference answer."},
|
|
{ID: "window_boundary", Description: "A request exactly window seconds old is outside the half-open interval."},
|
|
{ID: "rejected_not_counted", Description: "Rejected requests do not occupy capacity in later windows."},
|
|
{ID: "queue_approach", Description: "The approach processes each arrival at most once when entering and once when leaving the queue."},
|
|
},
|
|
},
|
|
}
|
|
bundle.Families = append(bundle.Families, family)
|
|
requestsMinimum++
|
|
}
|
|
if _, err := bundle.Drafts(); err != nil {
|
|
return assessment.Bundle{}, err
|
|
}
|
|
return bundle, nil
|
|
}
|