feat(assessment): add immutable family versions and the demo bank loader
This commit is contained in:
1 parent
94488e2b57
commit
204c6bae62
28 files changed
+6269
-9
No files matched your search
@@ -0,0 +1,379 @@
|
||||
-- +goose Up
|
||||
-- Assessment bank: immutable versions of assessment task families and the
|
||||
-- openings that make a category available.
|
||||
--
|
||||
-- One row of assessment_families is one version of one family. Its content
|
||||
-- (key, rubric, seed generator, authorship, review) never changes: a change
|
||||
-- is a new row with the next version number. The only columns that move are
|
||||
-- lifecycle, published_at, published_by, retired_at, and retired_by, and only
|
||||
-- forward (draft -> published -> retired), which the guard trigger enforces.
|
||||
-- At most one version of a family is published at a time.
|
||||
--
|
||||
-- The tables hold task content and operator identities only, never personal
|
||||
-- data of candidates.
|
||||
CREATE TABLE assessment_families (
|
||||
-- UUIDv7 generated in Go.
|
||||
id uuid NOT NULL,
|
||||
-- Stable name of the family across versions.
|
||||
family_key text NOT NULL,
|
||||
-- Numbered from 1 within the family key.
|
||||
version integer NOT NULL,
|
||||
category text NOT NULL,
|
||||
-- Specialization or domain inside the category.
|
||||
specialization text NOT NULL,
|
||||
title text NOT NULL,
|
||||
-- Name of the bundle the version was imported from. Provenance only; it
|
||||
-- is not part of the content hash.
|
||||
bundle_name text NOT NULL,
|
||||
-- "ai:<name>" for a generated draft or "operator:<handle>" for a person.
|
||||
author text NOT NULL,
|
||||
-- The independent reviewer, "operator:<handle>"; NULL while the review
|
||||
-- is pending.
|
||||
reviewer text,
|
||||
review_status text NOT NULL,
|
||||
-- Seed generator: algorithm, parameter ranges, statement template.
|
||||
seed_generator jsonb NOT NULL,
|
||||
-- Answer key: answer format and the reference solution description.
|
||||
answer_key jsonb NOT NULL,
|
||||
-- Rubric: principle and criteria. It holds no points or thresholds;
|
||||
-- grading rules come from the versioned policy.
|
||||
rubric jsonb NOT NULL,
|
||||
-- SHA-256 of the canonical content, 32 raw bytes. The domain recomputes
|
||||
-- it when it reads a row, with the hash function that hash_scheme names.
|
||||
content_sha256 bytea NOT NULL,
|
||||
-- Version of the layout that content_sha256 hashes. A row keeps the
|
||||
-- scheme it was stored with, so a later scheme verifies new rows without
|
||||
-- invalidating old ones. Part of the immutable columns.
|
||||
hash_scheme smallint NOT NULL,
|
||||
lifecycle text NOT NULL,
|
||||
-- Time from the database clock, set by the stamp trigger.
|
||||
created_at timestamptz NOT NULL,
|
||||
published_at timestamptz,
|
||||
-- "operator:<handle>" that the caller declared when it published or
|
||||
-- retired the version; not an authenticated identity until operator
|
||||
-- accounts exist.
|
||||
published_by text,
|
||||
retired_at timestamptz,
|
||||
retired_by text,
|
||||
CONSTRAINT assessment_families_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT assessment_families_family_key_version_key UNIQUE (
|
||||
family_key, version
|
||||
),
|
||||
CONSTRAINT assessment_families_family_key_format CHECK (
|
||||
family_key ~ '^[a-z][a-z0-9-]{2,63}$'
|
||||
),
|
||||
CONSTRAINT assessment_families_version_positive CHECK (version > 0),
|
||||
CONSTRAINT assessment_families_category_format CHECK (
|
||||
category ~ '^[a-z][a-z0-9-]{1,47}$'
|
||||
),
|
||||
CONSTRAINT assessment_families_specialization_format CHECK (
|
||||
specialization ~ '^[a-z][a-z0-9-]{1,63}$'
|
||||
),
|
||||
CONSTRAINT assessment_families_title_format CHECK (
|
||||
char_length(title) BETWEEN 1 AND 200
|
||||
AND title !~ '^\s|\s$'
|
||||
AND title !~ '[[:cntrl:]]'
|
||||
-- Invisible format characters: zero-width, bidirectional marks and
|
||||
-- overrides, line and paragraph separators, word joiner and
|
||||
-- invisible operators, and the BOM.
|
||||
AND title !~ '[\u200B-\u200F\u202A-\u202E\u2028\u2029\u2060-\u2064\u2066-\u206F\uFEFF]'
|
||||
),
|
||||
CONSTRAINT assessment_families_bundle_name_format CHECK (
|
||||
bundle_name ~ '^[a-z][a-z0-9._-]{2,63}$'
|
||||
),
|
||||
CONSTRAINT assessment_families_author_format CHECK (
|
||||
char_length(author) <= 128
|
||||
AND author ~ '^(ai|operator):[a-z0-9][a-z0-9._-]*$'
|
||||
),
|
||||
CONSTRAINT assessment_families_reviewer_format CHECK (
|
||||
reviewer IS NULL OR (
|
||||
char_length(reviewer) <= 128
|
||||
AND reviewer ~ '^operator:[a-z0-9][a-z0-9._-]*$'
|
||||
)
|
||||
),
|
||||
CONSTRAINT assessment_families_review_status_known CHECK (
|
||||
review_status IN ('pending', 'approved', 'rejected')
|
||||
),
|
||||
-- A review is pending exactly while no reviewer is recorded.
|
||||
CONSTRAINT assessment_families_review_has_reviewer CHECK (
|
||||
(review_status = 'pending') = (reviewer IS NULL)
|
||||
),
|
||||
-- The review is independent: the reviewer is never the author.
|
||||
CONSTRAINT assessment_families_reviewer_independent CHECK (
|
||||
reviewer IS NULL OR reviewer <> author
|
||||
),
|
||||
CONSTRAINT assessment_families_documents_are_objects CHECK (
|
||||
jsonb_typeof(seed_generator) = 'object'
|
||||
AND jsonb_typeof(answer_key) = 'object'
|
||||
AND jsonb_typeof(rubric) = 'object'
|
||||
),
|
||||
CONSTRAINT assessment_families_content_sha256_size CHECK (
|
||||
octet_length(content_sha256) = 32
|
||||
),
|
||||
CONSTRAINT assessment_families_hash_scheme_known CHECK (
|
||||
hash_scheme IN (1)
|
||||
),
|
||||
CONSTRAINT assessment_families_lifecycle_known CHECK (
|
||||
lifecycle IN ('draft', 'published', 'retired')
|
||||
),
|
||||
CONSTRAINT assessment_families_lifecycle_stamps CHECK (
|
||||
(
|
||||
lifecycle = 'draft'
|
||||
AND published_at IS NULL AND published_by IS NULL
|
||||
AND retired_at IS NULL AND retired_by IS NULL
|
||||
) OR (
|
||||
lifecycle = 'published'
|
||||
AND published_at IS NOT NULL AND published_by IS NOT NULL
|
||||
AND retired_at IS NULL AND retired_by IS NULL
|
||||
) OR (
|
||||
lifecycle = 'retired'
|
||||
AND published_at IS NOT NULL AND published_by IS NOT NULL
|
||||
AND retired_at IS NOT NULL AND retired_by IS NOT NULL
|
||||
)
|
||||
),
|
||||
CONSTRAINT assessment_families_published_by_format CHECK (
|
||||
published_by IS NULL OR (
|
||||
char_length(published_by) <= 128
|
||||
AND published_by ~ '^operator:[a-z0-9][a-z0-9._-]*$'
|
||||
)
|
||||
),
|
||||
CONSTRAINT assessment_families_retired_by_format CHECK (
|
||||
retired_by IS NULL OR (
|
||||
char_length(retired_by) <= 128
|
||||
AND retired_by ~ '^operator:[a-z0-9][a-z0-9._-]*$'
|
||||
)
|
||||
),
|
||||
-- A family is published only with an approved review by a reviewer.
|
||||
CONSTRAINT assessment_families_published_requires_review CHECK (
|
||||
lifecycle = 'draft' OR (
|
||||
reviewer IS NOT NULL AND review_status = 'approved'
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
-- Coverage counts published families of a category.
|
||||
CREATE INDEX assessment_families_category_lifecycle_idx
|
||||
ON assessment_families (category, lifecycle);
|
||||
|
||||
-- At most one version of a family is published. Publishing a newer version
|
||||
-- retires the older one first, in the same transaction.
|
||||
CREATE UNIQUE INDEX assessment_families_one_published_key
|
||||
ON assessment_families (family_key) WHERE lifecycle = 'published';
|
||||
|
||||
-- Every new version starts as a draft. The database clock sets created_at and
|
||||
-- the lifecycle columns, whatever the caller sent.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_families_stamp_creation() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
NEW.created_at := clock_timestamp();
|
||||
NEW.lifecycle := 'draft';
|
||||
NEW.published_at := NULL;
|
||||
NEW.published_by := NULL;
|
||||
NEW.retired_at := NULL;
|
||||
NEW.retired_by := NULL;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_families_stamp_creation
|
||||
BEFORE INSERT ON assessment_families
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_families_stamp_creation();
|
||||
|
||||
-- Refuses every change except a forward lifecycle step. Any column other than
|
||||
-- the lifecycle columns that differs between OLD and NEW is an edit of a
|
||||
-- stored version. The caller names the operator of the step; the trigger sets
|
||||
-- the time and keeps the publisher through a retirement. The errors use
|
||||
-- SQLSTATE 23000 and the constraint names below, which the adapter maps to
|
||||
-- port sentinels without reading the message.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_families_guard_update() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF (to_jsonb(NEW) - 'lifecycle' - 'published_at' - 'published_by' - 'retired_at' - 'retired_by')
|
||||
IS DISTINCT FROM
|
||||
(to_jsonb(OLD) - 'lifecycle' - 'published_at' - 'published_by' - 'retired_at' - 'retired_by') THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'assessment_families_immutable',
|
||||
TABLE = 'assessment_families',
|
||||
MESSAGE = 'assessment family versions are immutable: import a new version instead';
|
||||
END IF;
|
||||
IF OLD.lifecycle = 'draft' AND NEW.lifecycle = 'published' THEN
|
||||
NEW.published_at := clock_timestamp();
|
||||
NEW.retired_at := NULL;
|
||||
NEW.retired_by := NULL;
|
||||
ELSIF OLD.lifecycle = 'published' AND NEW.lifecycle = 'retired' THEN
|
||||
NEW.published_at := OLD.published_at;
|
||||
NEW.published_by := OLD.published_by;
|
||||
NEW.retired_at := clock_timestamp();
|
||||
ELSE
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'assessment_families_lifecycle_transition',
|
||||
TABLE = 'assessment_families',
|
||||
MESSAGE = 'assessment family lifecycle moves only draft to published to retired';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_families_guard_update
|
||||
BEFORE UPDATE ON assessment_families
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_families_guard_update();
|
||||
|
||||
-- Refuses DELETE and TRUNCATE. Row triggers do not fire for TRUNCATE, so a
|
||||
-- statement trigger covers it.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_families_refuse_removal() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'assessment_families_immutable',
|
||||
TABLE = 'assessment_families',
|
||||
MESSAGE = 'assessment family versions are immutable: import a new version instead';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_families_refuse_delete
|
||||
BEFORE DELETE ON assessment_families
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_families_refuse_removal();
|
||||
|
||||
CREATE TRIGGER assessment_families_refuse_truncate
|
||||
BEFORE TRUNCATE ON assessment_families
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION assessment_families_refuse_removal();
|
||||
|
||||
-- A category opening makes a category available. It records the versioned
|
||||
-- policy the opening was made under, by reference, and the coverage the
|
||||
-- database counted at that moment. An opening is never edited; the newest
|
||||
-- opening of a category is the current one.
|
||||
CREATE TABLE assessment_category_openings (
|
||||
-- UUIDv7 generated in Go.
|
||||
id uuid NOT NULL,
|
||||
category text NOT NULL,
|
||||
-- The agreed basic grading policy: a policy_versions.id. Product
|
||||
-- thresholds are read from this version; the bank stores no thresholds
|
||||
-- of its own. The insert trigger checks that the version exists instead
|
||||
-- of a FOREIGN KEY, because PostgreSQL refuses TRUNCATE of a referenced
|
||||
-- table before the policy_versions trigger can refuse it with its own
|
||||
-- error. Versions are never deleted, so the check cannot go stale.
|
||||
policy_version_id uuid NOT NULL,
|
||||
-- "operator:<handle>" of the person who agreed to open the category.
|
||||
opened_by text NOT NULL,
|
||||
-- Distinct published families the policy requires: the insert trigger
|
||||
-- derives it from the referenced policy document, so a value from the
|
||||
-- caller is ignored.
|
||||
required_families integer NOT NULL,
|
||||
-- Distinct published families counted by the insert trigger.
|
||||
published_families integer NOT NULL,
|
||||
-- Time from the database clock, set by the stamp trigger.
|
||||
opened_at timestamptz NOT NULL,
|
||||
CONSTRAINT assessment_category_openings_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT assessment_category_openings_category_format CHECK (
|
||||
category ~ '^[a-z][a-z0-9-]{1,47}$'
|
||||
),
|
||||
CONSTRAINT assessment_category_openings_opened_by_format CHECK (
|
||||
char_length(opened_by) <= 128
|
||||
AND opened_by ~ '^operator:[a-z0-9][a-z0-9._-]*$'
|
||||
),
|
||||
CONSTRAINT assessment_category_openings_required_positive CHECK (
|
||||
required_families > 0
|
||||
),
|
||||
CONSTRAINT assessment_category_openings_coverage CHECK (
|
||||
published_families >= required_families
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX assessment_category_openings_category_idx
|
||||
ON assessment_category_openings (category, opened_at DESC, id DESC);
|
||||
|
||||
-- Checks the policy reference, derives the required coverage from the stored
|
||||
-- policy document, counts the published families of the category, and stamps
|
||||
-- the opening time. The coverage CHECK then refuses an opening whose category
|
||||
-- has fewer published families than the policy requires. The requirement is
|
||||
-- assessment.stop_rule.max_scored_items + assessment.stop_rule.seed_items, the
|
||||
-- two paths that domain.RequiredPublishedAssessmentFamilies reads. A missing
|
||||
-- policy version raises SQLSTATE 23503 under the constraint name that a
|
||||
-- foreign key would have had; a document without the two values is refused
|
||||
-- as well. The caller serializes openings, publications, and retirements of
|
||||
-- a category with an advisory lock, so the count cannot miss a concurrent
|
||||
-- retirement.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_category_openings_stamp() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
maximum_text text;
|
||||
seed_text text;
|
||||
BEGIN
|
||||
SELECT
|
||||
policy.document #>> '{assessment,stop_rule,max_scored_items}',
|
||||
policy.document #>> '{assessment,stop_rule,seed_items}'
|
||||
INTO maximum_text, seed_text
|
||||
FROM policy_versions AS policy
|
||||
WHERE policy.id = NEW.policy_version_id;
|
||||
IF NOT FOUND THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'foreign_key_violation',
|
||||
CONSTRAINT = 'assessment_category_openings_policy_version_id_fkey',
|
||||
TABLE = 'assessment_category_openings',
|
||||
MESSAGE = 'assessment category opening references an unknown policy version';
|
||||
END IF;
|
||||
-- The text is checked before the cast, so a malformed document of a row
|
||||
-- written around the application raises the refusal below and not a cast
|
||||
-- error (22P02 or 22003).
|
||||
IF maximum_text IS NULL OR seed_text IS NULL
|
||||
OR maximum_text !~ '^[0-9]{1,4}$' OR seed_text !~ '^[0-9]{1,4}$' THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'check_violation',
|
||||
CONSTRAINT = 'assessment_category_openings_policy_thresholds',
|
||||
TABLE = 'assessment_category_openings',
|
||||
MESSAGE = 'the referenced policy version has no scored item bounds';
|
||||
END IF;
|
||||
NEW.required_families := maximum_text::integer + seed_text::integer;
|
||||
NEW.opened_at := clock_timestamp();
|
||||
SELECT count(DISTINCT family.family_key)::integer
|
||||
INTO NEW.published_families
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = NEW.category AND family.lifecycle = 'published';
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_category_openings_stamp
|
||||
BEFORE INSERT ON assessment_category_openings
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_category_openings_stamp();
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_category_openings_refuse_change() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'assessment_category_openings_immutable',
|
||||
TABLE = 'assessment_category_openings',
|
||||
MESSAGE = 'assessment category openings are immutable';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_category_openings_refuse_update_delete
|
||||
BEFORE UPDATE OR DELETE ON assessment_category_openings
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_category_openings_refuse_change();
|
||||
|
||||
CREATE TRIGGER assessment_category_openings_refuse_truncate
|
||||
BEFORE TRUNCATE ON assessment_category_openings
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION assessment_category_openings_refuse_change();
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE assessment_category_openings;
|
||||
DROP FUNCTION assessment_category_openings_refuse_change();
|
||||
DROP FUNCTION assessment_category_openings_stamp();
|
||||
DROP TABLE assessment_families;
|
||||
DROP FUNCTION assessment_families_refuse_removal();
|
||||
DROP FUNCTION assessment_families_guard_update();
|
||||
DROP FUNCTION assessment_families_stamp_creation();
|
||||
@@ -0,0 +1,340 @@
|
||||
-- Stores a new family version as a draft and returns the stored row with the
|
||||
-- creation time set by the stamp trigger. A taken ID or (family_key, version)
|
||||
-- returns no row instead of an error, so a conflict does not abort the
|
||||
-- surrounding transaction.
|
||||
-- name: InsertAssessmentFamily :one
|
||||
INSERT INTO assessment_families (
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(family_key),
|
||||
sqlc.arg(version),
|
||||
sqlc.arg(category),
|
||||
sqlc.arg(specialization),
|
||||
sqlc.arg(title),
|
||||
sqlc.arg(bundle_name),
|
||||
sqlc.arg(author),
|
||||
sqlc.narg(reviewer),
|
||||
sqlc.arg(review_status),
|
||||
sqlc.arg(seed_generator),
|
||||
sqlc.arg(answer_key),
|
||||
sqlc.arg(rubric),
|
||||
sqlc.arg(content_sha256),
|
||||
sqlc.arg(hash_scheme),
|
||||
'draft'
|
||||
)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by;
|
||||
|
||||
-- name: GetAssessmentFamilyByID :one
|
||||
SELECT
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by
|
||||
FROM assessment_families
|
||||
WHERE id = sqlc.arg(id);
|
||||
|
||||
-- name: GetAssessmentFamilyVersion :one
|
||||
SELECT
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by
|
||||
FROM assessment_families
|
||||
WHERE
|
||||
family_key = sqlc.arg(family_key)
|
||||
AND version = sqlc.arg(version);
|
||||
|
||||
-- name: GetLatestAssessmentFamily :one
|
||||
SELECT
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by
|
||||
FROM assessment_families
|
||||
WHERE family_key = sqlc.arg(family_key)
|
||||
ORDER BY version DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- One page of the versions of a category in key and version order, after the
|
||||
-- given position; an empty key and version 0 start at the beginning. The
|
||||
-- (family_key, version) unique index serves the scan.
|
||||
-- name: ListAssessmentFamiliesByCategory :many
|
||||
SELECT
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by
|
||||
FROM assessment_families
|
||||
WHERE
|
||||
category = sqlc.arg(category)
|
||||
AND (family_key, version) > (sqlc.arg(after_key)::text, sqlc.arg(after_version)::integer)
|
||||
ORDER BY family_key ASC, version ASC
|
||||
LIMIT sqlc.arg(page_size);
|
||||
|
||||
-- The published version of a family, if any. The partial unique index
|
||||
-- assessment_families_one_published_key allows at most one.
|
||||
-- name: GetPublishedAssessmentFamily :one
|
||||
SELECT
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by
|
||||
FROM assessment_families
|
||||
WHERE
|
||||
family_key = sqlc.arg(family_key)
|
||||
AND lifecycle = 'published';
|
||||
|
||||
-- Serializes the operations that change which versions of a category are
|
||||
-- published or open the category, until the transaction ends. The key is
|
||||
-- namespaced, so it cannot collide with another use of advisory locks.
|
||||
-- name: LockAssessmentCategory :exec
|
||||
SELECT pg_advisory_xact_lock(
|
||||
hashtextextended('lincodex.assessment.category:' || sqlc.arg(category)::text, 0)
|
||||
);
|
||||
|
||||
-- Counts the families of a category that have at least one published
|
||||
-- version, however many versions each has.
|
||||
-- name: CountPublishedAssessmentFamilies :one
|
||||
SELECT count(DISTINCT family_key)::integer AS published
|
||||
FROM assessment_families
|
||||
WHERE
|
||||
category = sqlc.arg(category)
|
||||
AND lifecycle = 'published';
|
||||
|
||||
-- Moves a draft to published by the named operator and returns the row with
|
||||
-- the publication time set by the guard trigger. No row means the version
|
||||
-- was not a draft any more.
|
||||
-- name: PublishAssessmentFamily :one
|
||||
UPDATE assessment_families
|
||||
SET
|
||||
lifecycle = 'published',
|
||||
published_by = sqlc.arg(actor)
|
||||
WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND lifecycle = 'draft'
|
||||
RETURNING
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by;
|
||||
|
||||
-- name: RetireAssessmentFamily :one
|
||||
UPDATE assessment_families
|
||||
SET
|
||||
lifecycle = 'retired',
|
||||
retired_by = sqlc.arg(actor)
|
||||
WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND lifecycle = 'published'
|
||||
RETURNING
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by;
|
||||
|
||||
-- Stores an opening. The insert trigger derives required_families from the
|
||||
-- policy document and counts the published families, and the coverage CHECK
|
||||
-- refuses the row when they are fewer; both numbers from the caller are
|
||||
-- replaced by the trigger's.
|
||||
-- name: InsertAssessmentCategoryOpening :one
|
||||
INSERT INTO assessment_category_openings (
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
opened_by,
|
||||
required_families,
|
||||
published_families,
|
||||
opened_at
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(category),
|
||||
sqlc.arg(policy_version_id),
|
||||
sqlc.arg(opened_by),
|
||||
0,
|
||||
0,
|
||||
clock_timestamp()
|
||||
)
|
||||
RETURNING
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
opened_by,
|
||||
required_families,
|
||||
published_families,
|
||||
opened_at;
|
||||
|
||||
-- name: GetCurrentAssessmentCategoryOpening :one
|
||||
SELECT
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
opened_by,
|
||||
required_families,
|
||||
published_families,
|
||||
opened_at
|
||||
FROM assessment_category_openings
|
||||
WHERE category = sqlc.arg(category)
|
||||
ORDER BY opened_at DESC, id DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- The database clock, which stamps the effective time of a policy version, so
|
||||
-- "the version in force now" is judged against the same clock.
|
||||
-- name: GetDatabaseTime :one
|
||||
SELECT clock_timestamp()::timestamptz AS now;
|
||||
@@ -0,0 +1,659 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
postgresadapter "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 (
|
||||
assessmentTestTimeout = 3 * time.Minute
|
||||
// demoBundleFile is the AI draft that the loader task ships. It has no
|
||||
// human review, so nothing in it may become published.
|
||||
demoBundleFile = "../testdata/assessment/backend_demo_bundle.json"
|
||||
// assessmentCategory is the category of the demo bundle.
|
||||
assessmentCategory = domain.AssessmentCategory("backend")
|
||||
// Fixture identities of reviewed test bundles. They stand for people in
|
||||
// tests only and are not content of the demo bank.
|
||||
fixtureAuthor = "operator:fixture-author"
|
||||
fixtureReviewer = "operator:fixture-reviewer"
|
||||
fixtureOpener = domain.AssessmentOperator("operator:fixture-opener")
|
||||
fixturePublisher = domain.AssessmentOperator("operator:fixture-publisher")
|
||||
|
||||
assessmentIntegritySQLState = "23000"
|
||||
assessmentCheckSQLState = "23514"
|
||||
)
|
||||
|
||||
type assessmentFixture struct {
|
||||
ctx context.Context
|
||||
pool *pgxpool.Pool
|
||||
store *postgresadapter.AssessmentBankStore
|
||||
transactor *postgresadapter.Transactor
|
||||
bank *assessment.Bank
|
||||
publisher *policy.Publisher
|
||||
demoBundle assessment.Bundle
|
||||
}
|
||||
|
||||
func TestAssessmentBank(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), assessmentTestTimeout)
|
||||
defer cancel()
|
||||
newFixture := func(t *testing.T) assessmentFixture {
|
||||
t.Helper()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
pool := newPoolFor(ctx, t, databaseURL)
|
||||
return assessmentFixture{
|
||||
ctx: ctx,
|
||||
pool: pool,
|
||||
store: postgresadapter.NewAssessmentBankStore(pool),
|
||||
transactor: postgresadapter.NewTransactor(pool),
|
||||
bank: assessment.NewBank(postgresadapter.NewTransactor(pool)),
|
||||
publisher: policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now),
|
||||
demoBundle: loadDemoBundleFile(t),
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("two versions of a family are stored and the first keeps its original key", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
first := fixture.singleFamilyBundle("backend-demo-v1", 1, "")
|
||||
originalKey := first.Families[0].AnswerKey
|
||||
if _, err := fixture.bank.ImportBundle(ctx, first); err != nil {
|
||||
t.Fatalf("ImportBundle(version 1) error = %v", err)
|
||||
}
|
||||
second := fixture.singleFamilyBundle("backend-demo-v2", 2, "A different reference approach for version two.")
|
||||
result, err := fixture.bank.ImportBundle(ctx, second)
|
||||
if err != nil || len(result.Created) != 1 {
|
||||
t.Fatalf("ImportBundle(version 2) = %+v, %v, want one created version", result, err)
|
||||
}
|
||||
|
||||
key := domain.AssessmentFamilyKey(first.Families[0].Key)
|
||||
stored, err := fixture.store.AssessmentBank().GetFamilyVersion(ctx, key, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("GetFamilyVersion(1) error = %v", err)
|
||||
}
|
||||
if stored.AnswerKey() != originalKey {
|
||||
t.Fatalf("version 1 key = %+v, want the original %+v", stored.AnswerKey(), originalKey)
|
||||
}
|
||||
latest, err := fixture.store.AssessmentBank().GetLatestFamily(ctx, key)
|
||||
if err != nil || latest.Version() != 2 || latest.AnswerKey() == originalKey {
|
||||
t.Fatalf("GetLatestFamily() = version %d, %v, want version 2 with a different key", latest.Version(), err)
|
||||
}
|
||||
if stored.Lifecycle() != domain.AssessmentLifecycleDraft || stored.ReviewStatus() != domain.AssessmentReviewPending || stored.Reviewer() != "" {
|
||||
t.Fatalf("imported demo version = %s/%s/%q, want draft, pending, no reviewer", stored.Lifecycle(), stored.ReviewStatus(), stored.Reviewer())
|
||||
}
|
||||
|
||||
// Importing the same bundle again changes nothing; the same version
|
||||
// with other content, and a gap in the numbering, are refused.
|
||||
again, err := fixture.bank.ImportBundle(ctx, first)
|
||||
if err != nil || len(again.Created) != 0 || len(again.Unchanged) != 1 {
|
||||
t.Fatalf("ImportBundle(repeat) = %+v, %v, want one unchanged version", again, err)
|
||||
}
|
||||
changed := fixture.singleFamilyBundle("backend-demo-v1", 1, "Rewritten reference approach.")
|
||||
fixture.assertRefusal(t, "ImportBundle(changed version 1)", domain.RefusalVersionConflict, importError(fixture, changed))
|
||||
fixture.assertRefusal(t, "ImportBundle(version 4)", domain.RefusalVersionGap, importError(fixture, fixture.singleFamilyBundle("backend-demo-v4", 4, "Skipped.")))
|
||||
fixture.assertFamilyCount(t, 2)
|
||||
})
|
||||
|
||||
t.Run("the database refuses to edit or remove a stored version", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
if _, err := fixture.bank.ImportBundle(ctx, fixture.demoBundle); err != nil {
|
||||
t.Fatalf("ImportBundle(demo) error = %v", err)
|
||||
}
|
||||
for name, statement := range map[string]string{
|
||||
"edit the key": `UPDATE assessment_families SET answer_key = '{"answer_format":"integer","reference_solution":"edited"}'`,
|
||||
"edit the review": `UPDATE assessment_families SET reviewer = 'operator:someone', review_status = 'approved'`,
|
||||
"edit the version": `UPDATE assessment_families SET version = version + 10`,
|
||||
"edit the hash scheme": `UPDATE assessment_families SET hash_scheme = 2`,
|
||||
"delete": `DELETE FROM assessment_families`,
|
||||
"truncate": `TRUNCATE assessment_families`,
|
||||
} {
|
||||
_, err := fixture.pool.Exec(ctx, statement)
|
||||
assertPgError(t, name, err, assessmentIntegritySQLState, "assessment_families_immutable")
|
||||
}
|
||||
// Publishing a version without an approved review is refused by the
|
||||
// table itself, not only by the domain.
|
||||
_, err := fixture.pool.Exec(ctx, `UPDATE assessment_families SET lifecycle = 'published', published_by = 'operator:raw-sql'`)
|
||||
assertPgError(t, "publish without review", err, assessmentCheckSQLState, "assessment_families_published_requires_review")
|
||||
// The lifecycle never moves backward or skips a step.
|
||||
_, err = fixture.pool.Exec(ctx, `UPDATE assessment_families SET lifecycle = 'retired'`)
|
||||
assertPgError(t, "retire a draft", err, assessmentIntegritySQLState, "assessment_families_lifecycle_transition")
|
||||
// A new row cannot start published, whatever the caller sends.
|
||||
fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE lifecycle <> 'draft'`, 0)
|
||||
// The reviewer cannot be the author.
|
||||
_, err = fixture.pool.Exec(ctx, `
|
||||
INSERT INTO assessment_families (id, family_key, version, category, specialization, title, bundle_name, author, reviewer, review_status,
|
||||
seed_generator, answer_key, rubric, content_sha256, hash_scheme, lifecycle)
|
||||
SELECT gen_random_uuid(), 'self-reviewed-family', 1, category, specialization, title, bundle_name, 'operator:same-person', 'operator:same-person', 'approved',
|
||||
seed_generator, answer_key, rubric, content_sha256, hash_scheme, 'draft'
|
||||
FROM assessment_families LIMIT 1`)
|
||||
assertPgError(t, "reviewer is the author", err, assessmentCheckSQLState, "assessment_families_reviewer_independent")
|
||||
fixture.assertFamilyCount(t, len(fixture.demoBundle.Families))
|
||||
})
|
||||
|
||||
t.Run("the same seed gives the same variant and a different seed keeps the rubric principle", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
if _, err := fixture.bank.ImportBundle(ctx, fixture.demoBundle); err != nil {
|
||||
t.Fatalf("ImportBundle(demo) error = %v", err)
|
||||
}
|
||||
for _, family := range fixture.demoBundle.Families {
|
||||
key := domain.AssessmentFamilyKey(family.Key)
|
||||
first, err := fixture.bank.GenerateVariant(ctx, key, 1, 42)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateVariant(%s, seed 42) error = %v", key, err)
|
||||
}
|
||||
second, err := fixture.bank.GenerateVariant(ctx, key, 1, 42)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateVariant(%s, seed 42) again error = %v", key, err)
|
||||
}
|
||||
if first.Statement != second.Statement || first.ReferenceAnswer != second.ReferenceAnswer {
|
||||
t.Fatalf("%s: variants of seed 42 differ", key)
|
||||
}
|
||||
other := fixture.firstDifferentVariant(t, key, first)
|
||||
if other.Rubric.Principle != first.Rubric.Principle || !slices.Equal(other.Rubric.Criteria, first.Rubric.Criteria) {
|
||||
t.Fatalf("%s: the rubric changed with the seed", key)
|
||||
}
|
||||
if other.Rubric.Principle != family.Rubric.Principle {
|
||||
t.Fatalf("%s: the variant rubric principle differs from the stored family rubric", key)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a family without a reviewer cannot be published and the category stays closed", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
if _, err := fixture.bank.ImportBundle(ctx, fixture.demoBundle); err != nil {
|
||||
t.Fatalf("ImportBundle(demo) error = %v", err)
|
||||
}
|
||||
for _, family := range fixture.demoBundle.Families {
|
||||
_, err := fixture.bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), 1, fixturePublisher)
|
||||
fixture.assertRefusal(t, "PublishFamily("+family.Key+")", domain.RefusalReviewerMissing, err)
|
||||
}
|
||||
fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE lifecycle = 'published'`, 0)
|
||||
|
||||
policyVersion := fixture.publishGradingPolicy(t)
|
||||
_, err := fixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{
|
||||
Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener,
|
||||
})
|
||||
fixture.assertRefusal(t, "OpenCategory(no published families)", domain.RefusalCoverageInsufficient, err)
|
||||
if _, err := fixture.bank.CategoryAvailability(ctx, assessmentCategory); !errors.Is(err, outbound.ErrAssessmentCategoryNotOpen) {
|
||||
t.Fatalf("CategoryAvailability() error = %v, want ErrAssessmentCategoryNotOpen", err)
|
||||
}
|
||||
fixture.assertCount(t, `SELECT count(*) FROM assessment_category_openings`, 0)
|
||||
})
|
||||
|
||||
t.Run("a category opens only under a referenced stored grading policy", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
_, err := fixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{Category: assessmentCategory, OpenedBy: fixtureOpener})
|
||||
fixture.assertRefusal(t, "OpenCategory(no policy reference)", domain.RefusalGradingPolicyMissing, err)
|
||||
|
||||
unknown, err := domain.NewPolicyVersionID()
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionID() error = %v", err)
|
||||
}
|
||||
_, err = fixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{Category: assessmentCategory, GradingPolicyID: unknown, OpenedBy: fixtureOpener})
|
||||
fixture.assertRefusal(t, "OpenCategory(unknown policy)", domain.RefusalGradingPolicyMissing, err)
|
||||
fixture.assertCount(t, `SELECT count(*) FROM assessment_category_openings`, 0)
|
||||
})
|
||||
|
||||
t.Run("a reviewed bundle opens the category once coverage reaches the policy requirement", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
policyVersion := fixture.publishGradingPolicy(t)
|
||||
requiredFamilies, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy())
|
||||
if err != nil {
|
||||
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
|
||||
}
|
||||
required := int(requiredFamilies)
|
||||
bundle := fixture.reviewedBundle(required)
|
||||
if _, err := fixture.bank.ImportBundle(ctx, bundle); err != nil {
|
||||
t.Fatalf("ImportBundle(reviewed) error = %v", err)
|
||||
}
|
||||
input := assessment.OpenCategoryInput{Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener}
|
||||
|
||||
for index, family := range bundle.Families {
|
||||
published, err := fixture.bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), 1, fixturePublisher)
|
||||
if err != nil {
|
||||
t.Fatalf("PublishFamily(%s) error = %v", family.Key, err)
|
||||
}
|
||||
if _, ok := published.PublishedAt(); !ok || published.Lifecycle() != domain.AssessmentLifecyclePublished {
|
||||
t.Fatalf("PublishFamily(%s) = %s without a publication time", family.Key, published.Lifecycle())
|
||||
}
|
||||
if index < required-1 {
|
||||
_, err := fixture.bank.OpenCategory(ctx, input)
|
||||
fixture.assertRefusal(t, fmt.Sprintf("OpenCategory(%d of %d published)", index+1, required), domain.RefusalCoverageInsufficient, err)
|
||||
}
|
||||
}
|
||||
opening, err := fixture.bank.OpenCategory(ctx, input)
|
||||
if err != nil {
|
||||
t.Fatalf("OpenCategory(enough coverage) error = %v", err)
|
||||
}
|
||||
if int(opening.RequiredFamilies) != required || int(opening.PublishedFamilies) != required || opening.PolicyVersionID != policyVersion.ID() {
|
||||
t.Fatalf("opening = %+v, want %d required and published families under policy %s", opening, required, policyVersion.ID())
|
||||
}
|
||||
current, err := fixture.bank.CategoryAvailability(ctx, assessmentCategory)
|
||||
if err != nil || current.ID != opening.ID {
|
||||
t.Fatalf("CategoryAvailability() = %+v, %v, want the new opening", current, err)
|
||||
}
|
||||
// The database derived the requirement from the policy document; it
|
||||
// must equal the number that the domain computes from the same paths.
|
||||
fixture.assertCount(t, `SELECT required_families FROM assessment_category_openings`, required)
|
||||
published, err := fixture.store.AssessmentBank().GetPublishedFamily(ctx, domain.AssessmentFamilyKey(bundle.Families[1].Key))
|
||||
if err != nil || published.PublishedBy() != fixturePublisher {
|
||||
t.Fatalf("GetPublishedFamily() = %v, %v, want a version published by %s", published.PublishedBy(), err, fixturePublisher)
|
||||
}
|
||||
// A new policy version takes force: the opening was made under the
|
||||
// old one, so the category needs a new opening.
|
||||
fixture.publishGradingPolicy(t)
|
||||
_, err = fixture.bank.CategoryAvailability(ctx, assessmentCategory)
|
||||
fixture.assertRefusal(t, "CategoryAvailability(policy superseded)", domain.RefusalGradingPolicyNotCurrent, err)
|
||||
_, err = fixture.pool.Exec(ctx, `UPDATE assessment_category_openings SET opened_by = 'operator:other'`)
|
||||
assertPgError(t, "edit an opening", err, assessmentIntegritySQLState, "assessment_category_openings_immutable")
|
||||
|
||||
// A second publication of a published version, and the retirement of
|
||||
// a draft, are refused with a reason.
|
||||
_, err = fixture.bank.PublishFamily(ctx, domain.AssessmentFamilyKey(bundle.Families[0].Key), 1, fixturePublisher)
|
||||
fixture.assertRefusal(t, "PublishFamily(published)", domain.RefusalNotDraft, err)
|
||||
retired, err := fixture.bank.RetireFamily(ctx, domain.AssessmentFamilyKey(bundle.Families[0].Key), 1, fixturePublisher)
|
||||
if err != nil || retired.Lifecycle() != domain.AssessmentLifecycleRetired || retired.RetiredBy() != fixturePublisher {
|
||||
t.Fatalf("RetireFamily() = %v, %v, want retired by %s", retired.Lifecycle(), err, fixturePublisher)
|
||||
}
|
||||
// Availability is live: with one published family fewer than the
|
||||
// opening required, the category is refused with the reason.
|
||||
_, err = fixture.bank.CategoryAvailability(ctx, assessmentCategory)
|
||||
fixture.assertRefusal(t, "CategoryAvailability(after a retirement below the requirement)", domain.RefusalCoverageInsufficient, err)
|
||||
_, err = fixture.bank.RetireFamily(ctx, domain.AssessmentFamilyKey(bundle.Families[0].Key), 1, fixturePublisher)
|
||||
fixture.assertRefusal(t, "RetireFamily(retired)", domain.RefusalNotPublished, err)
|
||||
_, err = fixture.pool.Exec(ctx, `UPDATE assessment_families SET lifecycle = 'published' WHERE lifecycle = 'retired'`)
|
||||
assertPgError(t, "publish a retired version", err, assessmentIntegritySQLState, "assessment_families_lifecycle_transition")
|
||||
})
|
||||
|
||||
t.Run("publishing a version retires the older published one and refuses an older one", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
versions := fixture.reviewedVersionsBundle(1, 3)
|
||||
key := domain.AssessmentFamilyKey(versions[0].Families[0].Key)
|
||||
if _, err := fixture.bank.ImportBundle(ctx, versions[0]); err != nil {
|
||||
t.Fatalf("ImportBundle(version 1) error = %v", err)
|
||||
}
|
||||
if _, err := fixture.bank.ActiveFamily(ctx, key); !errors.Is(err, outbound.ErrAssessmentFamilyNotFound) {
|
||||
t.Fatalf("ActiveFamily(nothing published) error = %v, want ErrAssessmentFamilyNotFound", err)
|
||||
}
|
||||
if _, err := fixture.bank.PublishFamily(ctx, key, 1, fixturePublisher); err != nil {
|
||||
t.Fatalf("PublishFamily(1) error = %v", err)
|
||||
}
|
||||
for _, version := range versions[1:] {
|
||||
if _, err := fixture.bank.ImportBundle(ctx, version); err != nil {
|
||||
t.Fatalf("ImportBundle(%s) error = %v", version.Name, err)
|
||||
}
|
||||
}
|
||||
other := domain.AssessmentOperator("operator:second-publisher")
|
||||
if _, err := fixture.bank.PublishFamily(ctx, key, 3, other); err != nil {
|
||||
t.Fatalf("PublishFamily(3) error = %v", err)
|
||||
}
|
||||
first, err := fixture.store.AssessmentBank().GetFamilyVersion(ctx, key, 1)
|
||||
if err != nil || first.Lifecycle() != domain.AssessmentLifecycleRetired || first.RetiredBy() != other || first.PublishedBy() != fixturePublisher {
|
||||
t.Fatalf("version 1 = %s published by %q retired by %q, %v, want retired by %s and published by %s",
|
||||
first.Lifecycle(), first.PublishedBy(), first.RetiredBy(), err, other, fixturePublisher)
|
||||
}
|
||||
active, err := fixture.bank.ActiveFamily(ctx, key)
|
||||
if err != nil || active.Version() != 3 {
|
||||
t.Fatalf("ActiveFamily() = version %d, %v, want version 3", active.Version(), err)
|
||||
}
|
||||
_, err = fixture.bank.PublishFamily(ctx, key, 2, fixturePublisher)
|
||||
fixture.assertRefusal(t, "PublishFamily(older than the published version)", domain.RefusalNewerVersionPublished, err)
|
||||
_, err = fixture.bank.PublishFamily(ctx, key, 1, fixturePublisher)
|
||||
fixture.assertRefusal(t, "PublishFamily(retired version)", domain.RefusalNotDraft, err)
|
||||
fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE lifecycle = 'published'`, 1)
|
||||
|
||||
// The table allows one published version per family, whoever writes.
|
||||
_, err = fixture.pool.Exec(ctx, `UPDATE assessment_families SET lifecycle = 'published', published_by = 'operator:raw-sql' WHERE family_key = $1 AND version = 2`, string(key))
|
||||
assertPgError(t, "second published version", err, "23505", "assessment_families_one_published_key")
|
||||
// The recorded operators change only with their step.
|
||||
_, err = fixture.pool.Exec(ctx, `UPDATE assessment_families SET published_by = 'operator:raw-sql' WHERE lifecycle = 'published'`)
|
||||
assertPgError(t, "rewrite the publisher", err, assessmentIntegritySQLState, "assessment_families_lifecycle_transition")
|
||||
// An approved pending draft is a new version, never an edit: the
|
||||
// demo drafts stay pending drafts.
|
||||
fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE review_status = 'pending' AND lifecycle <> 'draft'`, 0)
|
||||
})
|
||||
|
||||
t.Run("an older approved draft is not published after a newer version exists", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
versions := fixture.reviewedVersionsBundle(1, 2)
|
||||
for _, version := range versions {
|
||||
if _, err := fixture.bank.ImportBundle(ctx, version); err != nil {
|
||||
t.Fatalf("ImportBundle(%s) error = %v", version.Name, err)
|
||||
}
|
||||
}
|
||||
key := domain.AssessmentFamilyKey(versions[0].Families[0].Key)
|
||||
if _, err := fixture.bank.PublishFamily(ctx, key, 2, fixturePublisher); err != nil {
|
||||
t.Fatalf("PublishFamily(2) error = %v", err)
|
||||
}
|
||||
_, err := fixture.bank.PublishFamily(ctx, key, 1, fixturePublisher)
|
||||
fixture.assertRefusal(t, "PublishFamily(1 while 2 is published)", domain.RefusalNewerVersionPublished, err)
|
||||
if _, err := fixture.bank.RetireFamily(ctx, key, 2, fixturePublisher); err != nil {
|
||||
t.Fatalf("RetireFamily(2) error = %v", err)
|
||||
}
|
||||
_, err = fixture.bank.PublishFamily(ctx, key, 1, fixturePublisher)
|
||||
fixture.assertRefusal(t, "PublishFamily(1 while 2 is retired)", domain.RefusalNewerVersionPublished, err)
|
||||
fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE lifecycle = 'published'`, 0)
|
||||
})
|
||||
|
||||
t.Run("opening, publishing, and retiring of one category run one after another", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
policyVersion := fixture.publishGradingPolicy(t)
|
||||
required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy())
|
||||
if err != nil {
|
||||
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
|
||||
}
|
||||
bundle := fixture.reviewedBundle(int(required))
|
||||
if _, err := fixture.bank.ImportBundle(ctx, bundle); err != nil {
|
||||
t.Fatalf("ImportBundle() error = %v", err)
|
||||
}
|
||||
for _, family := range bundle.Families {
|
||||
if _, err := fixture.bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), 1, fixturePublisher); err != nil {
|
||||
t.Fatalf("PublishFamily(%s) error = %v", family.Key, err)
|
||||
}
|
||||
}
|
||||
// A transaction that holds the category lock, as a publication does
|
||||
// until it commits, makes an opening wait instead of counting.
|
||||
held, release, done := make(chan struct{}), make(chan struct{}), make(chan error, 1)
|
||||
go func() {
|
||||
done <- fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := unit.AssessmentBank().LockCategory(ctx, assessmentCategory); err != nil {
|
||||
return err
|
||||
}
|
||||
close(held)
|
||||
<-release
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
<-held
|
||||
waiting, cancelWait := context.WithTimeout(ctx, 500*time.Millisecond)
|
||||
defer cancelWait()
|
||||
_, err = fixture.bank.OpenCategory(waiting, assessment.OpenCategoryInput{Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener})
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("OpenCategory(while another transaction holds the category lock) error = %v, want a wait that ends with the deadline", err)
|
||||
}
|
||||
close(release)
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("lock holder error = %v", err)
|
||||
}
|
||||
if _, err := fixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener}); err != nil {
|
||||
t.Fatalf("OpenCategory(after the lock is released) error = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a category opens only under the policy version in force", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
superseded := fixture.publishGradingPolicy(t)
|
||||
current := fixture.publishGradingPolicy(t)
|
||||
_, err := fixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{Category: assessmentCategory, GradingPolicyID: superseded.ID(), OpenedBy: fixtureOpener})
|
||||
fixture.assertRefusal(t, "OpenCategory(superseded policy)", domain.RefusalGradingPolicyNotCurrent, err)
|
||||
// The policy in force passes that check and then fails on coverage.
|
||||
_, err = fixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{Category: assessmentCategory, GradingPolicyID: current.ID(), OpenedBy: fixtureOpener})
|
||||
fixture.assertRefusal(t, "OpenCategory(policy in force, no coverage)", domain.RefusalCoverageInsufficient, err)
|
||||
})
|
||||
|
||||
t.Run("the database derives the required coverage and refuses invisible characters", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
policyVersion := fixture.publishGradingPolicy(t)
|
||||
bundle := fixture.reviewedBundle(3)
|
||||
if _, err := fixture.bank.ImportBundle(ctx, bundle); err != nil {
|
||||
t.Fatalf("ImportBundle() error = %v", err)
|
||||
}
|
||||
for _, family := range bundle.Families {
|
||||
if _, err := fixture.bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), 1, fixturePublisher); err != nil {
|
||||
t.Fatalf("PublishFamily(%s) error = %v", family.Key, err)
|
||||
}
|
||||
}
|
||||
// Three published families, and a caller that claims that one is
|
||||
// enough: the trigger replaces the claim with the policy's number.
|
||||
_, err := fixture.pool.Exec(ctx, `
|
||||
INSERT INTO assessment_category_openings (id, category, policy_version_id, opened_by, required_families, published_families, opened_at)
|
||||
VALUES (gen_random_uuid(), 'backend', $1, 'operator:fixture-opener', 1, 3, now())`, policyVersion.ID().UUID())
|
||||
assertPgError(t, "opening with a claimed requirement", err, assessmentCheckSQLState, "assessment_category_openings_coverage")
|
||||
|
||||
_, err = fixture.pool.Exec(ctx, `
|
||||
INSERT INTO assessment_families (id, family_key, version, category, specialization, title, bundle_name, author, review_status,
|
||||
seed_generator, answer_key, rubric, content_sha256, hash_scheme, lifecycle)
|
||||
SELECT gen_random_uuid(), 'bidi-title-family', 1, category, specialization, E'Cache \u202Etest', bundle_name, author, 'pending',
|
||||
seed_generator, answer_key, rubric, content_sha256, hash_scheme, 'draft'
|
||||
FROM assessment_families LIMIT 1`)
|
||||
assertPgError(t, "title with a bidi override", err, assessmentCheckSQLState, "assessment_families_title_format")
|
||||
})
|
||||
|
||||
t.Run("a policy document with malformed scored item bounds is refused with the thresholds refusal", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
for index, document := range []string{
|
||||
`{}`,
|
||||
`{"assessment":{"stop_rule":{"max_scored_items":"many","seed_items":1}}}`,
|
||||
`{"assessment":{"stop_rule":{"max_scored_items":99999999999,"seed_items":1}}}`,
|
||||
`{"assessment":{"stop_rule":{"max_scored_items":2.5,"seed_items":1}}}`,
|
||||
`{"assessment":{"stop_rule":{"max_scored_items":-3,"seed_items":1}}}`,
|
||||
`{"assessment":{"stop_rule":{"max_scored_items":10}}}`,
|
||||
} {
|
||||
// The document is written around the domain, which would never
|
||||
// store it; the policy table only checks that it is an object.
|
||||
var policyID string
|
||||
err := fixture.pool.QueryRow(ctx, `
|
||||
INSERT INTO policy_versions (id, policy_key, version, kind, effective_at, author, document, document_sha256)
|
||||
VALUES (gen_random_uuid(), 'product', $1, 'demo', NULL, 'operator:raw-sql', $2::jsonb, decode(repeat('00', 32), 'hex'))
|
||||
RETURNING id::text`, index+1, document).Scan(&policyID)
|
||||
if err != nil {
|
||||
t.Fatalf("insert raw policy version %d: %v", index+1, err)
|
||||
}
|
||||
_, err = fixture.pool.Exec(ctx, `
|
||||
INSERT INTO assessment_category_openings (id, category, policy_version_id, opened_by, required_families, published_families, opened_at)
|
||||
VALUES (gen_random_uuid(), 'backend', $1::uuid, 'operator:fixture-opener', 1, 1, now())`, policyID)
|
||||
assertPgError(t, "opening under document "+document, err, assessmentCheckSQLState, "assessment_category_openings_policy_thresholds")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a stored hash scheme must be a known one", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
if _, err := fixture.bank.ImportBundle(ctx, fixture.demoBundle); err != nil {
|
||||
t.Fatalf("ImportBundle(demo) error = %v", err)
|
||||
}
|
||||
fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE hash_scheme = 1`, len(fixture.demoBundle.Families))
|
||||
_, err := fixture.pool.Exec(ctx, `
|
||||
INSERT INTO assessment_families (id, family_key, version, category, specialization, title, bundle_name, author, review_status,
|
||||
seed_generator, answer_key, rubric, content_sha256, hash_scheme, lifecycle)
|
||||
SELECT gen_random_uuid(), 'other-scheme-family', 1, category, specialization, title, bundle_name, author, 'pending',
|
||||
seed_generator, answer_key, rubric, content_sha256, 7, 'draft'
|
||||
FROM assessment_families LIMIT 1`)
|
||||
assertPgError(t, "unknown hash scheme", err, assessmentCheckSQLState, "assessment_families_hash_scheme_known")
|
||||
})
|
||||
|
||||
t.Run("families are listed in pages after a cursor", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
bundle := fixture.reviewedBundle(5)
|
||||
if _, err := fixture.bank.ImportBundle(ctx, bundle); err != nil {
|
||||
t.Fatalf("ImportBundle() error = %v", err)
|
||||
}
|
||||
var seen []string
|
||||
var cursor outbound.AssessmentFamilyCursor
|
||||
for range 10 {
|
||||
page, err := fixture.store.AssessmentBank().ListFamilies(ctx, assessmentCategory, cursor, 2)
|
||||
if err != nil {
|
||||
t.Fatalf("ListFamilies() error = %v", err)
|
||||
}
|
||||
if len(page) == 0 {
|
||||
break
|
||||
}
|
||||
if len(page) > 2 {
|
||||
t.Fatalf("ListFamilies(limit 2) returned %d rows", len(page))
|
||||
}
|
||||
for _, family := range page {
|
||||
seen = append(seen, string(family.Key()))
|
||||
}
|
||||
last := page[len(page)-1]
|
||||
cursor = outbound.AssessmentFamilyCursor{Key: last.Key(), Version: last.Version()}
|
||||
}
|
||||
if len(seen) != 5 || !slices.IsSorted(seen) {
|
||||
t.Fatalf("pages returned %v, want the five keys once and in order", seen)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the database refuses an opening below the required coverage", func(t *testing.T) {
|
||||
fixture := newFixture(t)
|
||||
policyVersion := fixture.publishGradingPolicy(t)
|
||||
// Written around the usecase: the opening trigger counts the
|
||||
// published families itself and the coverage CHECK refuses the row.
|
||||
_, err := fixture.pool.Exec(ctx, `
|
||||
INSERT INTO assessment_category_openings (id, category, policy_version_id, opened_by, required_families, published_families, opened_at)
|
||||
VALUES (gen_random_uuid(), 'backend', $1, 'operator:fixture-opener', 1, 999, now())`, policyVersion.ID().UUID())
|
||||
assertPgError(t, "opening without published families", err, assessmentCheckSQLState, "assessment_category_openings_coverage")
|
||||
_, err = fixture.pool.Exec(ctx, `
|
||||
INSERT INTO assessment_category_openings (id, category, policy_version_id, opened_by, required_families, published_families, opened_at)
|
||||
VALUES (gen_random_uuid(), 'backend', gen_random_uuid(), 'operator:fixture-opener', 1, 1, now())`)
|
||||
assertPgError(t, "opening under an unknown policy version", err, "23503", "assessment_category_openings_policy_version_id_fkey")
|
||||
})
|
||||
}
|
||||
|
||||
func importError(fixture assessmentFixture, bundle assessment.Bundle) error {
|
||||
_, err := fixture.bank.ImportBundle(fixture.ctx, bundle)
|
||||
return err
|
||||
}
|
||||
|
||||
func loadDemoBundleFile(t *testing.T) assessment.Bundle {
|
||||
t.Helper()
|
||||
file, err := os.Open(filepath.FromSlash(demoBundleFile))
|
||||
if err != nil {
|
||||
t.Fatalf("open demo bundle: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
bundle, err := assessment.ParseBundle(file)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseBundle(demo) error = %v", err)
|
||||
}
|
||||
return bundle
|
||||
}
|
||||
|
||||
// singleFamilyBundle takes the first family of the demo bundle as the given
|
||||
// version. A non-empty solution replaces the reference solution, which makes
|
||||
// the version's key differ from version 1.
|
||||
func (fixture assessmentFixture) singleFamilyBundle(name string, version int32, solution string) assessment.Bundle {
|
||||
bundle := fixture.demoBundle
|
||||
bundle.Name = name
|
||||
family := bundle.Families[0]
|
||||
family.Version = version
|
||||
if solution != "" {
|
||||
family.AnswerKey.ReferenceSolution = solution
|
||||
}
|
||||
bundle.Families = []assessment.BundleFamily{family}
|
||||
return bundle
|
||||
}
|
||||
|
||||
// reviewedBundle builds a bundle of count families that carries an approved
|
||||
// review by a person who is not the author. It is a test fixture for the
|
||||
// loader rules and not content of the demo bank: it reuses the generator
|
||||
// definitions of the demo families under other keys.
|
||||
func (fixture assessmentFixture) reviewedBundle(count int) assessment.Bundle {
|
||||
bundle := fixture.demoBundle
|
||||
bundle.Name = "fixture-reviewed-bundle"
|
||||
bundle.Author = fixtureAuthor
|
||||
bundle.Review = assessment.BundleReview{Status: string(domain.AssessmentReviewApproved), Reviewer: fixtureReviewer}
|
||||
bundle.Families = make([]assessment.BundleFamily, 0, count)
|
||||
for index := range count {
|
||||
family := fixture.demoBundle.Families[index%len(fixture.demoBundle.Families)]
|
||||
family.Key = fmt.Sprintf("fixture-family-%02d", index+1)
|
||||
bundle.Families = append(bundle.Families, family)
|
||||
}
|
||||
return bundle
|
||||
}
|
||||
|
||||
// reviewedVersionsBundle returns one bundle per version from first to last,
|
||||
// each holding the first demo family as that version with an approved review
|
||||
// by a person who is not the author. Later versions change the reference
|
||||
// solution, so their keys differ.
|
||||
func (fixture assessmentFixture) reviewedVersionsBundle(first, last int32) []assessment.Bundle {
|
||||
var bundles []assessment.Bundle
|
||||
for version := first; version <= last; version++ {
|
||||
bundle := fixture.singleFamilyBundle(fmt.Sprintf("fixture-version-%d", version), version, "")
|
||||
bundle.Families = []assessment.BundleFamily{bundle.Families[0]}
|
||||
bundle.Families[0].AnswerKey.ReferenceSolution = fmt.Sprintf("Reference approach of version %d.", version)
|
||||
bundle.Author = fixtureAuthor
|
||||
bundle.Review = assessment.BundleReview{Status: string(domain.AssessmentReviewApproved), Reviewer: fixtureReviewer}
|
||||
bundles = append(bundles, bundle)
|
||||
}
|
||||
return bundles
|
||||
}
|
||||
|
||||
// publishGradingPolicy stores a test policy as the grading policy that
|
||||
// categories open under.
|
||||
func (fixture assessmentFixture) publishGradingPolicy(t *testing.T) domain.PolicyVersion {
|
||||
t.Helper()
|
||||
version, err := fixture.publisher.Publish(fixture.ctx, policy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: integrationPolicy(11),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Publish(grading policy) error = %v", err)
|
||||
}
|
||||
return version
|
||||
}
|
||||
|
||||
// firstDifferentVariant generates variants of other seeds until the
|
||||
// statement differs from the given variant.
|
||||
func (fixture assessmentFixture) firstDifferentVariant(t *testing.T, key domain.AssessmentFamilyKey, variant domain.AssessmentVariant) domain.AssessmentVariant {
|
||||
t.Helper()
|
||||
for seed := variant.Seed + 1; seed < variant.Seed+50; seed++ {
|
||||
other, err := fixture.bank.GenerateVariant(fixture.ctx, key, variant.FamilyVersion, seed)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateVariant(%s, seed %d) error = %v", key, seed, err)
|
||||
}
|
||||
if other.Statement != variant.Statement {
|
||||
return other
|
||||
}
|
||||
}
|
||||
t.Fatalf("no seed near %d changed the statement of %s", variant.Seed, key)
|
||||
return domain.AssessmentVariant{}
|
||||
}
|
||||
|
||||
func (fixture assessmentFixture) assertRefusal(t *testing.T, operation string, want domain.AssessmentRefusalReason, err error) {
|
||||
t.Helper()
|
||||
var refusal *domain.AssessmentRefusalError
|
||||
if !errors.Is(err, domain.ErrAssessmentRefused) || !errors.As(err, &refusal) || refusal.Reason != want {
|
||||
t.Fatalf("%s error = %v, want a refusal with reason %s", operation, err, want)
|
||||
}
|
||||
if refusal.Detail == "" {
|
||||
t.Fatalf("%s refusal has no detail", operation)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture assessmentFixture) assertFamilyCount(t *testing.T, want int) {
|
||||
t.Helper()
|
||||
fixture.assertCount(t, `SELECT count(*) FROM assessment_families`, want)
|
||||
}
|
||||
|
||||
func (fixture assessmentFixture) assertCount(t *testing.T, query string, want int) {
|
||||
t.Helper()
|
||||
var got int
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, query).Scan(&got); err != nil {
|
||||
t.Fatalf("count rows with %q: %v", query, err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("%q = %d, want %d", query, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func assertPgError(t *testing.T, operation string, err error, sqlState, constraint string) {
|
||||
t.Helper()
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) || pgError.Code != sqlState || pgError.ConstraintName != constraint {
|
||||
t.Fatalf("%s error = %v, want SQLSTATE %s on %s", operation, err, sqlState, constraint)
|
||||
}
|
||||
}
|
||||
@@ -36,11 +36,14 @@ const (
|
||||
// organizationMigrationVersion creates organizationTableNames and
|
||||
// organizationFunctionNames.
|
||||
organizationMigrationVersion = 10
|
||||
// assessmentBankMigrationVersion creates assessmentBankTableNames and
|
||||
// assessmentBankFunctionNames.
|
||||
assessmentBankMigrationVersion = 11
|
||||
)
|
||||
|
||||
var (
|
||||
// Tables created by 00001, 00002, 00003, 00005, 00006, 00007, 00008, and
|
||||
// 00010.
|
||||
// 00010, and 00011.
|
||||
outboxTables = []string{"outbox_events"}
|
||||
identityTableNames = []string{"users", "email_tokens", "sessions"}
|
||||
policyTableNames = []string{"policy_versions"}
|
||||
@@ -50,10 +53,16 @@ var (
|
||||
scheduledJobTableNames = []string{"scheduled_jobs"}
|
||||
// organizationTableNames lists the tables of migration 00010.
|
||||
organizationTableNames = []string{"organizations", "organization_representatives", "memberships"}
|
||||
// Trigger functions created by 00003, 00006, and 00010.
|
||||
policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"}
|
||||
deliveryFunctionNames = []string{"deliveries_refuse_content_change()", "delivery_attempts_refuse_update()"}
|
||||
organizationFunctionNames = []string{"organizations_require_owner()"}
|
||||
// assessmentBankTableNames lists the tables of migration 00011.
|
||||
assessmentBankTableNames = []string{"assessment_families", "assessment_category_openings"}
|
||||
// Trigger functions created by 00003, 00006, 00010, and 00011.
|
||||
policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"}
|
||||
deliveryFunctionNames = []string{"deliveries_refuse_content_change()", "delivery_attempts_refuse_update()"}
|
||||
organizationFunctionNames = []string{"organizations_require_owner()"}
|
||||
assessmentBankFunctionNames = []string{
|
||||
"assessment_families_stamp_creation()", "assessment_families_guard_update()", "assessment_families_refuse_removal()",
|
||||
"assessment_category_openings_stamp()", "assessment_category_openings_refuse_change()",
|
||||
}
|
||||
)
|
||||
|
||||
func TestPostgresMigrations(t *testing.T) {
|
||||
@@ -89,9 +98,11 @@ func TestPostgresMigrations(t *testing.T) {
|
||||
assertTablesExist(ctx, t, pool, true, scheduledJobTableNames...)
|
||||
assertTablesExist(ctx, t, pool, true, organizationTableNames...)
|
||||
assertFunctionsExist(ctx, t, pool, true, organizationFunctionNames...)
|
||||
assertTablesExist(ctx, t, pool, true, assessmentBankTableNames...)
|
||||
assertFunctionsExist(ctx, t, pool, true, assessmentBankFunctionNames...)
|
||||
|
||||
identityRolledBack, policyRolledBack, consumerRolledBack, deliveryRolledBack, mailQuotaRolledBack := false, false, false, false, false
|
||||
scheduledJobRolledBack, organizationRolledBack := false, false
|
||||
scheduledJobRolledBack, organizationRolledBack, assessmentBankRolledBack := false, false, false
|
||||
for rolledBack := 0; ; rolledBack++ {
|
||||
result, err := migrator.DownOne(ctx)
|
||||
if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) {
|
||||
@@ -103,6 +114,14 @@ func TestPostgresMigrations(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err)
|
||||
}
|
||||
if result.Version == assessmentBankMigrationVersion {
|
||||
// The bank migration removes its tables and functions and
|
||||
// leaves the policy table its openings referenced.
|
||||
assertTablesExist(ctx, t, pool, false, assessmentBankTableNames...)
|
||||
assertFunctionsExist(ctx, t, pool, false, assessmentBankFunctionNames...)
|
||||
assertTablesExist(ctx, t, pool, true, policyTableNames...)
|
||||
assessmentBankRolledBack = true
|
||||
}
|
||||
if result.Version == organizationMigrationVersion {
|
||||
// The organization migration removes its tables and its
|
||||
// function and leaves the identity tables they reference.
|
||||
@@ -155,10 +174,10 @@ func TestPostgresMigrations(t *testing.T) {
|
||||
}
|
||||
}
|
||||
if !identityRolledBack || !policyRolledBack || !consumerRolledBack || !deliveryRolledBack || !mailQuotaRolledBack ||
|
||||
!scheduledJobRolledBack || !organizationRolledBack {
|
||||
t.Fatalf("migrations %d, %d, %d, %d, %d, %d, and %d were not all rolled back",
|
||||
!scheduledJobRolledBack || !organizationRolledBack || !assessmentBankRolledBack {
|
||||
t.Fatalf("migrations %d, %d, %d, %d, %d, %d, %d, and %d were not all rolled back",
|
||||
identityMigrationVersion, policyMigrationVersion, consumerMigrationVersion, deliveryMigrationVersion, mailQuotaMigrationVersion,
|
||||
scheduledJobMigrationVersion, organizationMigrationVersion)
|
||||
scheduledJobMigrationVersion, organizationMigrationVersion, assessmentBankMigrationVersion)
|
||||
}
|
||||
assertTablesExist(ctx, t, pool, false, outboxTables...)
|
||||
assertTablesExist(ctx, t, pool, false, identityTableNames...)
|
||||
@@ -201,6 +220,8 @@ func TestPostgresMigrations(t *testing.T) {
|
||||
assertTablesExist(ctx, t, pool, true, deliveryTableNames...)
|
||||
assertTablesExist(ctx, t, pool, true, organizationTableNames...)
|
||||
assertFunctionsExist(ctx, t, pool, true, organizationFunctionNames...)
|
||||
assertTablesExist(ctx, t, pool, true, assessmentBankTableNames...)
|
||||
assertFunctionsExist(ctx, t, pool, true, assessmentBankFunctionNames...)
|
||||
assertAllApplied(ctx, t, migrator, total)
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// assessmentConstraintErrors maps the bank constraints and triggers whose
|
||||
// refusal is a caller-visible outcome to port sentinels by SQLSTATE and
|
||||
// constraint name, never by text. Duplicate versions are no errors: the
|
||||
// insert uses ON CONFLICT DO NOTHING.
|
||||
var assessmentConstraintErrors = map[constraintViolation]error{
|
||||
{integrityConstraintViolationCode, "assessment_families_immutable"}: outbound.ErrAssessmentFamilyImmutable,
|
||||
{integrityConstraintViolationCode, "assessment_families_lifecycle_transition"}: outbound.ErrAssessmentFamilyLifecycle,
|
||||
// A second published version of one family: another publication won.
|
||||
{uniqueViolationCode, "assessment_families_one_published_key"}: outbound.ErrAssessmentFamilyLifecycle,
|
||||
{integrityConstraintViolationCode, "assessment_category_openings_immutable"}: outbound.ErrAssessmentFamilyImmutable,
|
||||
{checkViolationCode, "assessment_families_published_requires_review"}: outbound.ErrAssessmentFamilyNotPublishable,
|
||||
{checkViolationCode, "assessment_category_openings_coverage"}: outbound.ErrAssessmentCoverageInsufficient,
|
||||
{checkViolationCode, "assessment_category_openings_policy_thresholds"}: outbound.ErrAssessmentGradingPolicyNotFound,
|
||||
{foreignKeyViolationCode, "assessment_category_openings_policy_version_id_fkey"}: outbound.ErrAssessmentGradingPolicyNotFound,
|
||||
}
|
||||
|
||||
// mapAssessmentError turns a known bank constraint or trigger error into its
|
||||
// port sentinel and keeps the constraint name. Any other PostgreSQL error is
|
||||
// replaced by its SQLSTATE and constraint name, so task content and operator
|
||||
// identities never reach error text. Deadlocks and serialization failures
|
||||
// also match ErrTransactionConflict. A connection error loses the pgx prefix
|
||||
// that names the database user and database.
|
||||
func mapAssessmentError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) {
|
||||
return sanitizeConnectError(err)
|
||||
}
|
||||
if sentinel, ok := assessmentConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok {
|
||||
return fmt.Errorf("postgres.mapAssessmentError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
|
||||
}
|
||||
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
|
||||
}
|
||||
|
||||
// AssessmentBankStore provides the assessment bank outside a transaction.
|
||||
// Every call runs as its own statement on a pool connection. Called with a
|
||||
// context that belongs to a Transactor callback, it fails with
|
||||
// outbound.ErrNestedTransaction; use UnitOfWork.AssessmentBank there.
|
||||
type AssessmentBankStore struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func NewAssessmentBankStore(pool *pgxpool.Pool) *AssessmentBankStore {
|
||||
return &AssessmentBankStore{queries: sqlc.New(standaloneDB{pool: pool})}
|
||||
}
|
||||
|
||||
func (store *AssessmentBankStore) AssessmentBank() outbound.AssessmentBankRepository {
|
||||
return assessmentBankRepository{queries: store.queries, transactional: false}
|
||||
}
|
||||
|
||||
var _ outbound.AssessmentBankRepositories = (*AssessmentBankStore)(nil)
|
||||
var _ outbound.AssessmentBankRepositories = (*UnitOfWork)(nil)
|
||||
|
||||
func (unit *UnitOfWork) AssessmentBank() outbound.AssessmentBankRepository {
|
||||
return assessmentBankRepository{queries: unit.queries, transactional: true}
|
||||
}
|
||||
|
||||
type assessmentBankRepository struct {
|
||||
queries *sqlc.Queries
|
||||
// transactional is true for the repository of a UnitOfWork, the only one
|
||||
// where a transaction-scoped advisory lock lasts.
|
||||
transactional bool
|
||||
}
|
||||
|
||||
var _ outbound.AssessmentBankRepository = assessmentBankRepository{}
|
||||
|
||||
func (repository assessmentBankRepository) CreateFamily(ctx context.Context, draft domain.AssessmentFamilyDraft) (domain.AssessmentFamily, error) {
|
||||
const location = "assessmentBankRepository.CreateFamily"
|
||||
if draft.IsZero() {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("%s - draft was not built by domain.NewAssessmentFamilyDraft: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
generator, err := draft.SeedGeneratorJSON()
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("%s - encode seed generator: %w", location, err)
|
||||
}
|
||||
answerKey, err := draft.AnswerKeyJSON()
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("%s - encode answer key: %w", location, err)
|
||||
}
|
||||
rubric, err := draft.RubricJSON()
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("%s - encode rubric: %w", location, err)
|
||||
}
|
||||
core, hash := draft.Core(), draft.ContentHash()
|
||||
reviewer := pgtype.Text{}
|
||||
if core.Reviewer != "" {
|
||||
reviewer = pgtype.Text{String: string(core.Reviewer), Valid: true}
|
||||
}
|
||||
row, err := repository.queries.InsertAssessmentFamily(ctx, sqlc.InsertAssessmentFamilyParams{
|
||||
ID: pgUUID(draft.ID().UUID()),
|
||||
FamilyKey: string(core.Key),
|
||||
Version: core.Version,
|
||||
Category: string(core.Category),
|
||||
Specialization: string(core.Specialization),
|
||||
Title: core.Title,
|
||||
BundleName: string(core.BundleName),
|
||||
Author: string(core.Author),
|
||||
Reviewer: reviewer,
|
||||
ReviewStatus: string(core.ReviewStatus),
|
||||
SeedGenerator: generator,
|
||||
AnswerKey: answerKey,
|
||||
Rubric: rubric,
|
||||
ContentSha256: hash[:],
|
||||
HashScheme: draft.HashScheme(),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("%s - insert %s version %d: %w", location, core.Key, core.Version, outbound.ErrAssessmentFamilyConflict)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("%s - insert family: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
return assessmentFamilyFromRow(row)
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) GetFamilyVersion(ctx context.Context, key domain.AssessmentFamilyKey, version int32) (domain.AssessmentFamily, error) {
|
||||
row, err := repository.queries.GetAssessmentFamilyVersion(ctx, sqlc.GetAssessmentFamilyVersionParams{FamilyKey: string(key), Version: version})
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("assessmentBankRepository.GetFamilyVersion - select family: %w", mapAssessmentNoRows(err))
|
||||
}
|
||||
return assessmentFamilyFromRow(row)
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) GetLatestFamily(ctx context.Context, key domain.AssessmentFamilyKey) (domain.AssessmentFamily, error) {
|
||||
row, err := repository.queries.GetLatestAssessmentFamily(ctx, string(key))
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("assessmentBankRepository.GetLatestFamily - select family: %w", mapAssessmentNoRows(err))
|
||||
}
|
||||
return assessmentFamilyFromRow(row)
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) ListFamilies(
|
||||
ctx context.Context,
|
||||
category domain.AssessmentCategory,
|
||||
after outbound.AssessmentFamilyCursor,
|
||||
limit int32,
|
||||
) ([]domain.AssessmentFamily, error) {
|
||||
if limit < 1 || limit > outbound.MaxAssessmentFamilyPageSize {
|
||||
return nil, fmt.Errorf("assessmentBankRepository.ListFamilies - limit must be between 1 and %d: %w", outbound.MaxAssessmentFamilyPageSize, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
rows, err := repository.queries.ListAssessmentFamiliesByCategory(ctx, sqlc.ListAssessmentFamiliesByCategoryParams{
|
||||
Category: string(category), AfterKey: string(after.Key), AfterVersion: after.Version, PageSize: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("assessmentBankRepository.ListFamilies - select families: %w", mapAssessmentError(err))
|
||||
}
|
||||
families := make([]domain.AssessmentFamily, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
family, err := assessmentFamilyFromRow(row)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
families = append(families, family)
|
||||
}
|
||||
return families, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) GetPublishedFamily(ctx context.Context, key domain.AssessmentFamilyKey) (domain.AssessmentFamily, error) {
|
||||
row, err := repository.queries.GetPublishedAssessmentFamily(ctx, string(key))
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("assessmentBankRepository.GetPublishedFamily - select family: %w", mapAssessmentNoRows(err))
|
||||
}
|
||||
return assessmentFamilyFromRow(row)
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) LockCategory(ctx context.Context, category domain.AssessmentCategory) error {
|
||||
if !repository.transactional {
|
||||
return fmt.Errorf("assessmentBankRepository.LockCategory - lock %s: %w", category, outbound.ErrAssessmentLockOutsideTransaction)
|
||||
}
|
||||
if err := repository.queries.LockAssessmentCategory(ctx, string(category)); err != nil {
|
||||
return fmt.Errorf("assessmentBankRepository.LockCategory - take advisory lock: %w", mapAssessmentError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) CountPublishedFamilies(ctx context.Context, category domain.AssessmentCategory) (int32, error) {
|
||||
count, err := repository.queries.CountPublishedAssessmentFamilies(ctx, string(category))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("assessmentBankRepository.CountPublishedFamilies - count families: %w", mapAssessmentError(err))
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) MarkPublished(ctx context.Context, id domain.AssessmentFamilyID, by domain.AssessmentOperator) (domain.AssessmentFamily, error) {
|
||||
row, err := repository.queries.PublishAssessmentFamily(ctx, sqlc.PublishAssessmentFamilyParams{ID: pgUUID(id.UUID()), Actor: pgText(string(by))})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("assessmentBankRepository.MarkPublished - publish %s: %w", id, outbound.ErrAssessmentFamilyLifecycle)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("assessmentBankRepository.MarkPublished - update family: %w", mapAssessmentError(err))
|
||||
}
|
||||
return assessmentFamilyFromRow(row)
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) MarkRetired(ctx context.Context, id domain.AssessmentFamilyID, by domain.AssessmentOperator) (domain.AssessmentFamily, error) {
|
||||
row, err := repository.queries.RetireAssessmentFamily(ctx, sqlc.RetireAssessmentFamilyParams{ID: pgUUID(id.UUID()), Actor: pgText(string(by))})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("assessmentBankRepository.MarkRetired - retire %s: %w", id, outbound.ErrAssessmentFamilyLifecycle)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("assessmentBankRepository.MarkRetired - update family: %w", mapAssessmentError(err))
|
||||
}
|
||||
return assessmentFamilyFromRow(row)
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) CreateCategoryOpening(ctx context.Context, draft domain.AssessmentCategoryOpeningDraft) (domain.AssessmentCategoryOpening, error) {
|
||||
if draft.IsZero() {
|
||||
return domain.AssessmentCategoryOpening{}, fmt.Errorf("assessmentBankRepository.CreateCategoryOpening - draft was not built by domain.NewAssessmentCategoryOpeningDraft: %w", domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
row, err := repository.queries.InsertAssessmentCategoryOpening(ctx, sqlc.InsertAssessmentCategoryOpeningParams{
|
||||
ID: pgUUID(draft.ID()),
|
||||
Category: string(draft.Category()),
|
||||
PolicyVersionID: pgUUID(draft.PolicyVersionID().UUID()),
|
||||
OpenedBy: string(draft.OpenedBy()),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryOpening{}, fmt.Errorf("assessmentBankRepository.CreateCategoryOpening - insert opening: %w", mapAssessmentError(err))
|
||||
}
|
||||
return assessmentOpeningFromRow(row), nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) DatabaseTime(ctx context.Context) (time.Time, error) {
|
||||
now, err := repository.queries.GetDatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return time.Time{}, fmt.Errorf("assessmentBankRepository.DatabaseTime - select clock: %w", mapAssessmentError(err))
|
||||
}
|
||||
return now.Time, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) GetCurrentCategoryOpening(ctx context.Context, category domain.AssessmentCategory) (domain.AssessmentCategoryOpening, error) {
|
||||
row, err := repository.queries.GetCurrentAssessmentCategoryOpening(ctx, string(category))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AssessmentCategoryOpening{}, fmt.Errorf("assessmentBankRepository.GetCurrentCategoryOpening - select opening: %w", outbound.ErrAssessmentCategoryNotOpen)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryOpening{}, fmt.Errorf("assessmentBankRepository.GetCurrentCategoryOpening - select opening: %w", mapAssessmentError(err))
|
||||
}
|
||||
return assessmentOpeningFromRow(row), nil
|
||||
}
|
||||
|
||||
func pgText(value string) pgtype.Text {
|
||||
return pgtype.Text{String: value, Valid: true}
|
||||
}
|
||||
|
||||
func mapAssessmentNoRows(err error) error {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return outbound.ErrAssessmentFamilyNotFound
|
||||
}
|
||||
return mapAssessmentError(err)
|
||||
}
|
||||
|
||||
func assessmentFamilyFromRow(row sqlc.AssessmentFamily) (domain.AssessmentFamily, error) {
|
||||
family, err := domain.RestoreAssessmentFamily(domain.StoredAssessmentFamily{
|
||||
ID: domain.AssessmentFamilyID(row.ID.Bytes),
|
||||
FamilyKey: row.FamilyKey,
|
||||
Version: row.Version,
|
||||
Category: row.Category,
|
||||
Specialization: row.Specialization,
|
||||
Title: row.Title,
|
||||
BundleName: row.BundleName,
|
||||
Author: row.Author,
|
||||
Reviewer: row.Reviewer.String,
|
||||
ReviewStatus: row.ReviewStatus,
|
||||
SeedGenerator: row.SeedGenerator,
|
||||
AnswerKey: row.AnswerKey,
|
||||
Rubric: row.Rubric,
|
||||
ContentHash: row.ContentSha256,
|
||||
HashScheme: row.HashScheme,
|
||||
Lifecycle: row.Lifecycle,
|
||||
CreatedAt: row.CreatedAt.Time,
|
||||
PublishedAt: row.PublishedAt.Time,
|
||||
PublishedBy: row.PublishedBy.String,
|
||||
RetiredAt: row.RetiredAt.Time,
|
||||
RetiredBy: row.RetiredBy.String,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("postgres.assessmentFamilyFromRow - restore family: %w", err)
|
||||
}
|
||||
return family, nil
|
||||
}
|
||||
|
||||
func assessmentOpeningFromRow(row sqlc.AssessmentCategoryOpening) domain.AssessmentCategoryOpening {
|
||||
return domain.AssessmentCategoryOpening{
|
||||
ID: row.ID.Bytes,
|
||||
Category: domain.AssessmentCategory(row.Category),
|
||||
PolicyVersionID: domain.PolicyVersionID(row.PolicyVersionID.Bytes),
|
||||
OpenedBy: domain.AssessmentOperator(row.OpenedBy),
|
||||
RequiredFamilies: row.RequiredFamilies,
|
||||
PublishedFamilies: row.PublishedFamilies,
|
||||
OpenedAt: row.OpenedAt.Time,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestMapAssessmentErrorRecognizesBankConstraints(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
code string
|
||||
constraint string
|
||||
want error
|
||||
}{
|
||||
{code: integrityConstraintViolationCode, constraint: "assessment_families_immutable", want: outbound.ErrAssessmentFamilyImmutable},
|
||||
{code: integrityConstraintViolationCode, constraint: "assessment_families_lifecycle_transition", want: outbound.ErrAssessmentFamilyLifecycle},
|
||||
{code: integrityConstraintViolationCode, constraint: "assessment_category_openings_immutable", want: outbound.ErrAssessmentFamilyImmutable},
|
||||
{code: uniqueViolationCode, constraint: "assessment_families_one_published_key", want: outbound.ErrAssessmentFamilyLifecycle},
|
||||
{code: checkViolationCode, constraint: "assessment_category_openings_policy_thresholds", want: outbound.ErrAssessmentGradingPolicyNotFound},
|
||||
{code: checkViolationCode, constraint: "assessment_families_published_requires_review", want: outbound.ErrAssessmentFamilyNotPublishable},
|
||||
{code: checkViolationCode, constraint: "assessment_category_openings_coverage", want: outbound.ErrAssessmentCoverageInsufficient},
|
||||
{code: foreignKeyViolationCode, constraint: "assessment_category_openings_policy_version_id_fkey", want: outbound.ErrAssessmentGradingPolicyNotFound},
|
||||
} {
|
||||
err := mapAssessmentError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: "Failing row contains (secret task content)."})
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("mapAssessmentError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want)
|
||||
}
|
||||
if strings.Contains(err.Error(), "secret task content") {
|
||||
t.Fatalf("mapAssessmentError(%s) = %v, want no row values", test.constraint, err)
|
||||
}
|
||||
}
|
||||
other := mapAssessmentError(&pgconn.PgError{Code: checkViolationCode, ConstraintName: "assessment_families_title_format", Detail: "Failing row contains (secret task content)."})
|
||||
if strings.Contains(other.Error(), "secret task content") {
|
||||
t.Fatalf("mapAssessmentError(other) = %v, want only SQLSTATE and constraint", other)
|
||||
}
|
||||
if err := mapAssessmentError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(err, outbound.ErrTransactionConflict) {
|
||||
t.Fatalf("mapAssessmentError(deadlock) = %v, want ErrTransactionConflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockCategoryWorksOnlyInsideATransaction(t *testing.T) {
|
||||
// A repository without queries proves that no statement runs.
|
||||
standalone := assessmentBankRepository{transactional: false}
|
||||
if err := standalone.LockCategory(t.Context(), "backend"); !errors.Is(err, outbound.ErrAssessmentLockOutsideTransaction) {
|
||||
t.Fatalf("LockCategory(standalone) error = %v, want ErrAssessmentLockOutsideTransaction", err)
|
||||
}
|
||||
if store := NewAssessmentBankStore(nil).AssessmentBank(); !errors.Is(store.LockCategory(t.Context(), "backend"), outbound.ErrAssessmentLockOutsideTransaction) {
|
||||
t.Fatal("the standalone store must refuse LockCategory")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentBankRejectsUnbuiltDraftsBeforeQuerying(t *testing.T) {
|
||||
// A repository without queries proves that no statement runs.
|
||||
repository := assessmentBankRepository{}
|
||||
if _, err := repository.CreateFamily(t.Context(), domain.AssessmentFamilyDraft{}); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("CreateFamily(zero draft) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
for _, limit := range []int32{0, -1, outbound.MaxAssessmentFamilyPageSize + 1} {
|
||||
if _, err := repository.ListFamilies(t.Context(), "backend", outbound.AssessmentFamilyCursor{}, limit); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("ListFamilies(limit %d) error = %v, want ErrInvalidAssessmentFamily", limit, err)
|
||||
}
|
||||
}
|
||||
if _, err := repository.CreateCategoryOpening(t.Context(), domain.AssessmentCategoryOpeningDraft{}); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("CreateCategoryOpening(zero draft) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,733 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: assessment_bank.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const countPublishedAssessmentFamilies = `-- name: CountPublishedAssessmentFamilies :one
|
||||
SELECT count(DISTINCT family_key)::integer AS published
|
||||
FROM assessment_families
|
||||
WHERE
|
||||
category = $1
|
||||
AND lifecycle = 'published'
|
||||
`
|
||||
|
||||
// Counts the families of a category that have at least one published
|
||||
// version, however many versions each has.
|
||||
func (q *Queries) CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error) {
|
||||
row := q.db.QueryRow(ctx, countPublishedAssessmentFamilies, category)
|
||||
var published int32
|
||||
err := row.Scan(&published)
|
||||
return published, err
|
||||
}
|
||||
|
||||
const getAssessmentFamilyByID = `-- name: GetAssessmentFamilyByID :one
|
||||
SELECT
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by
|
||||
FROM assessment_families
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error) {
|
||||
row := q.db.QueryRow(ctx, getAssessmentFamilyByID, id)
|
||||
var i AssessmentFamily
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.FamilyKey,
|
||||
&i.Version,
|
||||
&i.Category,
|
||||
&i.Specialization,
|
||||
&i.Title,
|
||||
&i.BundleName,
|
||||
&i.Author,
|
||||
&i.Reviewer,
|
||||
&i.ReviewStatus,
|
||||
&i.SeedGenerator,
|
||||
&i.AnswerKey,
|
||||
&i.Rubric,
|
||||
&i.ContentSha256,
|
||||
&i.HashScheme,
|
||||
&i.Lifecycle,
|
||||
&i.CreatedAt,
|
||||
&i.PublishedAt,
|
||||
&i.PublishedBy,
|
||||
&i.RetiredAt,
|
||||
&i.RetiredBy,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getAssessmentFamilyVersion = `-- name: GetAssessmentFamilyVersion :one
|
||||
SELECT
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by
|
||||
FROM assessment_families
|
||||
WHERE
|
||||
family_key = $1
|
||||
AND version = $2
|
||||
`
|
||||
|
||||
type GetAssessmentFamilyVersionParams struct {
|
||||
FamilyKey string
|
||||
Version int32
|
||||
}
|
||||
|
||||
func (q *Queries) GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error) {
|
||||
row := q.db.QueryRow(ctx, getAssessmentFamilyVersion, arg.FamilyKey, arg.Version)
|
||||
var i AssessmentFamily
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.FamilyKey,
|
||||
&i.Version,
|
||||
&i.Category,
|
||||
&i.Specialization,
|
||||
&i.Title,
|
||||
&i.BundleName,
|
||||
&i.Author,
|
||||
&i.Reviewer,
|
||||
&i.ReviewStatus,
|
||||
&i.SeedGenerator,
|
||||
&i.AnswerKey,
|
||||
&i.Rubric,
|
||||
&i.ContentSha256,
|
||||
&i.HashScheme,
|
||||
&i.Lifecycle,
|
||||
&i.CreatedAt,
|
||||
&i.PublishedAt,
|
||||
&i.PublishedBy,
|
||||
&i.RetiredAt,
|
||||
&i.RetiredBy,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getCurrentAssessmentCategoryOpening = `-- name: GetCurrentAssessmentCategoryOpening :one
|
||||
SELECT
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
opened_by,
|
||||
required_families,
|
||||
published_families,
|
||||
opened_at
|
||||
FROM assessment_category_openings
|
||||
WHERE category = $1
|
||||
ORDER BY opened_at DESC, id DESC
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
func (q *Queries) GetCurrentAssessmentCategoryOpening(ctx context.Context, category string) (AssessmentCategoryOpening, error) {
|
||||
row := q.db.QueryRow(ctx, getCurrentAssessmentCategoryOpening, category)
|
||||
var i AssessmentCategoryOpening
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Category,
|
||||
&i.PolicyVersionID,
|
||||
&i.OpenedBy,
|
||||
&i.RequiredFamilies,
|
||||
&i.PublishedFamilies,
|
||||
&i.OpenedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getDatabaseTime = `-- name: GetDatabaseTime :one
|
||||
SELECT clock_timestamp()::timestamptz AS now
|
||||
`
|
||||
|
||||
// The database clock, which stamps the effective time of a policy version, so
|
||||
// "the version in force now" is judged against the same clock.
|
||||
func (q *Queries) GetDatabaseTime(ctx context.Context) (pgtype.Timestamptz, error) {
|
||||
row := q.db.QueryRow(ctx, getDatabaseTime)
|
||||
var now pgtype.Timestamptz
|
||||
err := row.Scan(&now)
|
||||
return now, err
|
||||
}
|
||||
|
||||
const getLatestAssessmentFamily = `-- name: GetLatestAssessmentFamily :one
|
||||
SELECT
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by
|
||||
FROM assessment_families
|
||||
WHERE family_key = $1
|
||||
ORDER BY version DESC
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
func (q *Queries) GetLatestAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error) {
|
||||
row := q.db.QueryRow(ctx, getLatestAssessmentFamily, familyKey)
|
||||
var i AssessmentFamily
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.FamilyKey,
|
||||
&i.Version,
|
||||
&i.Category,
|
||||
&i.Specialization,
|
||||
&i.Title,
|
||||
&i.BundleName,
|
||||
&i.Author,
|
||||
&i.Reviewer,
|
||||
&i.ReviewStatus,
|
||||
&i.SeedGenerator,
|
||||
&i.AnswerKey,
|
||||
&i.Rubric,
|
||||
&i.ContentSha256,
|
||||
&i.HashScheme,
|
||||
&i.Lifecycle,
|
||||
&i.CreatedAt,
|
||||
&i.PublishedAt,
|
||||
&i.PublishedBy,
|
||||
&i.RetiredAt,
|
||||
&i.RetiredBy,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getPublishedAssessmentFamily = `-- name: GetPublishedAssessmentFamily :one
|
||||
SELECT
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by
|
||||
FROM assessment_families
|
||||
WHERE
|
||||
family_key = $1
|
||||
AND lifecycle = 'published'
|
||||
`
|
||||
|
||||
// The published version of a family, if any. The partial unique index
|
||||
// assessment_families_one_published_key allows at most one.
|
||||
func (q *Queries) GetPublishedAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error) {
|
||||
row := q.db.QueryRow(ctx, getPublishedAssessmentFamily, familyKey)
|
||||
var i AssessmentFamily
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.FamilyKey,
|
||||
&i.Version,
|
||||
&i.Category,
|
||||
&i.Specialization,
|
||||
&i.Title,
|
||||
&i.BundleName,
|
||||
&i.Author,
|
||||
&i.Reviewer,
|
||||
&i.ReviewStatus,
|
||||
&i.SeedGenerator,
|
||||
&i.AnswerKey,
|
||||
&i.Rubric,
|
||||
&i.ContentSha256,
|
||||
&i.HashScheme,
|
||||
&i.Lifecycle,
|
||||
&i.CreatedAt,
|
||||
&i.PublishedAt,
|
||||
&i.PublishedBy,
|
||||
&i.RetiredAt,
|
||||
&i.RetiredBy,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertAssessmentCategoryOpening = `-- name: InsertAssessmentCategoryOpening :one
|
||||
INSERT INTO assessment_category_openings (
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
opened_by,
|
||||
required_families,
|
||||
published_families,
|
||||
opened_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
0,
|
||||
0,
|
||||
clock_timestamp()
|
||||
)
|
||||
RETURNING
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
opened_by,
|
||||
required_families,
|
||||
published_families,
|
||||
opened_at
|
||||
`
|
||||
|
||||
type InsertAssessmentCategoryOpeningParams struct {
|
||||
ID pgtype.UUID
|
||||
Category string
|
||||
PolicyVersionID pgtype.UUID
|
||||
OpenedBy string
|
||||
}
|
||||
|
||||
// Stores an opening. The insert trigger derives required_families from the
|
||||
// policy document and counts the published families, and the coverage CHECK
|
||||
// refuses the row when they are fewer; both numbers from the caller are
|
||||
// replaced by the trigger's.
|
||||
func (q *Queries) InsertAssessmentCategoryOpening(ctx context.Context, arg InsertAssessmentCategoryOpeningParams) (AssessmentCategoryOpening, error) {
|
||||
row := q.db.QueryRow(ctx, insertAssessmentCategoryOpening,
|
||||
arg.ID,
|
||||
arg.Category,
|
||||
arg.PolicyVersionID,
|
||||
arg.OpenedBy,
|
||||
)
|
||||
var i AssessmentCategoryOpening
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Category,
|
||||
&i.PolicyVersionID,
|
||||
&i.OpenedBy,
|
||||
&i.RequiredFamilies,
|
||||
&i.PublishedFamilies,
|
||||
&i.OpenedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertAssessmentFamily = `-- name: InsertAssessmentFamily :one
|
||||
INSERT INTO assessment_families (
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8,
|
||||
$9,
|
||||
$10,
|
||||
$11,
|
||||
$12,
|
||||
$13,
|
||||
$14,
|
||||
$15,
|
||||
'draft'
|
||||
)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by
|
||||
`
|
||||
|
||||
type InsertAssessmentFamilyParams struct {
|
||||
ID pgtype.UUID
|
||||
FamilyKey string
|
||||
Version int32
|
||||
Category string
|
||||
Specialization string
|
||||
Title string
|
||||
BundleName string
|
||||
Author string
|
||||
Reviewer pgtype.Text
|
||||
ReviewStatus string
|
||||
SeedGenerator []byte
|
||||
AnswerKey []byte
|
||||
Rubric []byte
|
||||
ContentSha256 []byte
|
||||
HashScheme int16
|
||||
}
|
||||
|
||||
// Stores a new family version as a draft and returns the stored row with the
|
||||
// creation time set by the stamp trigger. A taken ID or (family_key, version)
|
||||
// returns no row instead of an error, so a conflict does not abort the
|
||||
// surrounding transaction.
|
||||
func (q *Queries) InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error) {
|
||||
row := q.db.QueryRow(ctx, insertAssessmentFamily,
|
||||
arg.ID,
|
||||
arg.FamilyKey,
|
||||
arg.Version,
|
||||
arg.Category,
|
||||
arg.Specialization,
|
||||
arg.Title,
|
||||
arg.BundleName,
|
||||
arg.Author,
|
||||
arg.Reviewer,
|
||||
arg.ReviewStatus,
|
||||
arg.SeedGenerator,
|
||||
arg.AnswerKey,
|
||||
arg.Rubric,
|
||||
arg.ContentSha256,
|
||||
arg.HashScheme,
|
||||
)
|
||||
var i AssessmentFamily
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.FamilyKey,
|
||||
&i.Version,
|
||||
&i.Category,
|
||||
&i.Specialization,
|
||||
&i.Title,
|
||||
&i.BundleName,
|
||||
&i.Author,
|
||||
&i.Reviewer,
|
||||
&i.ReviewStatus,
|
||||
&i.SeedGenerator,
|
||||
&i.AnswerKey,
|
||||
&i.Rubric,
|
||||
&i.ContentSha256,
|
||||
&i.HashScheme,
|
||||
&i.Lifecycle,
|
||||
&i.CreatedAt,
|
||||
&i.PublishedAt,
|
||||
&i.PublishedBy,
|
||||
&i.RetiredAt,
|
||||
&i.RetiredBy,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listAssessmentFamiliesByCategory = `-- name: ListAssessmentFamiliesByCategory :many
|
||||
SELECT
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by
|
||||
FROM assessment_families
|
||||
WHERE
|
||||
category = $1
|
||||
AND (family_key, version) > ($2::text, $3::integer)
|
||||
ORDER BY family_key ASC, version ASC
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type ListAssessmentFamiliesByCategoryParams struct {
|
||||
Category string
|
||||
AfterKey string
|
||||
AfterVersion int32
|
||||
PageSize int32
|
||||
}
|
||||
|
||||
// One page of the versions of a category in key and version order, after the
|
||||
// given position; an empty key and version 0 start at the beginning. The
|
||||
// (family_key, version) unique index serves the scan.
|
||||
func (q *Queries) ListAssessmentFamiliesByCategory(ctx context.Context, arg ListAssessmentFamiliesByCategoryParams) ([]AssessmentFamily, error) {
|
||||
rows, err := q.db.Query(ctx, listAssessmentFamiliesByCategory,
|
||||
arg.Category,
|
||||
arg.AfterKey,
|
||||
arg.AfterVersion,
|
||||
arg.PageSize,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AssessmentFamily
|
||||
for rows.Next() {
|
||||
var i AssessmentFamily
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.FamilyKey,
|
||||
&i.Version,
|
||||
&i.Category,
|
||||
&i.Specialization,
|
||||
&i.Title,
|
||||
&i.BundleName,
|
||||
&i.Author,
|
||||
&i.Reviewer,
|
||||
&i.ReviewStatus,
|
||||
&i.SeedGenerator,
|
||||
&i.AnswerKey,
|
||||
&i.Rubric,
|
||||
&i.ContentSha256,
|
||||
&i.HashScheme,
|
||||
&i.Lifecycle,
|
||||
&i.CreatedAt,
|
||||
&i.PublishedAt,
|
||||
&i.PublishedBy,
|
||||
&i.RetiredAt,
|
||||
&i.RetiredBy,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockAssessmentCategory = `-- name: LockAssessmentCategory :exec
|
||||
SELECT pg_advisory_xact_lock(
|
||||
hashtextextended('lincodex.assessment.category:' || $1::text, 0)
|
||||
)
|
||||
`
|
||||
|
||||
// Serializes the operations that change which versions of a category are
|
||||
// published or open the category, until the transaction ends. The key is
|
||||
// namespaced, so it cannot collide with another use of advisory locks.
|
||||
func (q *Queries) LockAssessmentCategory(ctx context.Context, category string) error {
|
||||
_, err := q.db.Exec(ctx, lockAssessmentCategory, category)
|
||||
return err
|
||||
}
|
||||
|
||||
const publishAssessmentFamily = `-- name: PublishAssessmentFamily :one
|
||||
UPDATE assessment_families
|
||||
SET
|
||||
lifecycle = 'published',
|
||||
published_by = $1
|
||||
WHERE
|
||||
id = $2
|
||||
AND lifecycle = 'draft'
|
||||
RETURNING
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by
|
||||
`
|
||||
|
||||
type PublishAssessmentFamilyParams struct {
|
||||
Actor pgtype.Text
|
||||
ID pgtype.UUID
|
||||
}
|
||||
|
||||
// Moves a draft to published by the named operator and returns the row with
|
||||
// the publication time set by the guard trigger. No row means the version
|
||||
// was not a draft any more.
|
||||
func (q *Queries) PublishAssessmentFamily(ctx context.Context, arg PublishAssessmentFamilyParams) (AssessmentFamily, error) {
|
||||
row := q.db.QueryRow(ctx, publishAssessmentFamily, arg.Actor, arg.ID)
|
||||
var i AssessmentFamily
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.FamilyKey,
|
||||
&i.Version,
|
||||
&i.Category,
|
||||
&i.Specialization,
|
||||
&i.Title,
|
||||
&i.BundleName,
|
||||
&i.Author,
|
||||
&i.Reviewer,
|
||||
&i.ReviewStatus,
|
||||
&i.SeedGenerator,
|
||||
&i.AnswerKey,
|
||||
&i.Rubric,
|
||||
&i.ContentSha256,
|
||||
&i.HashScheme,
|
||||
&i.Lifecycle,
|
||||
&i.CreatedAt,
|
||||
&i.PublishedAt,
|
||||
&i.PublishedBy,
|
||||
&i.RetiredAt,
|
||||
&i.RetiredBy,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const retireAssessmentFamily = `-- name: RetireAssessmentFamily :one
|
||||
UPDATE assessment_families
|
||||
SET
|
||||
lifecycle = 'retired',
|
||||
retired_by = $1
|
||||
WHERE
|
||||
id = $2
|
||||
AND lifecycle = 'published'
|
||||
RETURNING
|
||||
id,
|
||||
family_key,
|
||||
version,
|
||||
category,
|
||||
specialization,
|
||||
title,
|
||||
bundle_name,
|
||||
author,
|
||||
reviewer,
|
||||
review_status,
|
||||
seed_generator,
|
||||
answer_key,
|
||||
rubric,
|
||||
content_sha256,
|
||||
hash_scheme,
|
||||
lifecycle,
|
||||
created_at,
|
||||
published_at,
|
||||
published_by,
|
||||
retired_at,
|
||||
retired_by
|
||||
`
|
||||
|
||||
type RetireAssessmentFamilyParams struct {
|
||||
Actor pgtype.Text
|
||||
ID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) RetireAssessmentFamily(ctx context.Context, arg RetireAssessmentFamilyParams) (AssessmentFamily, error) {
|
||||
row := q.db.QueryRow(ctx, retireAssessmentFamily, arg.Actor, arg.ID)
|
||||
var i AssessmentFamily
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.FamilyKey,
|
||||
&i.Version,
|
||||
&i.Category,
|
||||
&i.Specialization,
|
||||
&i.Title,
|
||||
&i.BundleName,
|
||||
&i.Author,
|
||||
&i.Reviewer,
|
||||
&i.ReviewStatus,
|
||||
&i.SeedGenerator,
|
||||
&i.AnswerKey,
|
||||
&i.Rubric,
|
||||
&i.ContentSha256,
|
||||
&i.HashScheme,
|
||||
&i.Lifecycle,
|
||||
&i.CreatedAt,
|
||||
&i.PublishedAt,
|
||||
&i.PublishedBy,
|
||||
&i.RetiredAt,
|
||||
&i.RetiredBy,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -8,6 +8,40 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type AssessmentCategoryOpening struct {
|
||||
ID pgtype.UUID
|
||||
Category string
|
||||
PolicyVersionID pgtype.UUID
|
||||
OpenedBy string
|
||||
RequiredFamilies int32
|
||||
PublishedFamilies int32
|
||||
OpenedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentFamily struct {
|
||||
ID pgtype.UUID
|
||||
FamilyKey string
|
||||
Version int32
|
||||
Category string
|
||||
Specialization string
|
||||
Title string
|
||||
BundleName string
|
||||
Author string
|
||||
Reviewer pgtype.Text
|
||||
ReviewStatus string
|
||||
SeedGenerator []byte
|
||||
AnswerKey []byte
|
||||
Rubric []byte
|
||||
ContentSha256 []byte
|
||||
HashScheme int16
|
||||
Lifecycle string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
PublishedAt pgtype.Timestamptz
|
||||
PublishedBy pgtype.Text
|
||||
RetiredAt pgtype.Timestamptz
|
||||
RetiredBy pgtype.Text
|
||||
}
|
||||
|
||||
type ConsentRecord struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
|
||||
@@ -48,6 +48,9 @@ type Querier interface {
|
||||
// returned registration version in the same transaction, rolled back when it
|
||||
// matches no row.
|
||||
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error)
|
||||
// Counts the families of a category that have at least one published
|
||||
// version, however many versions each has.
|
||||
CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error)
|
||||
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
|
||||
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
|
||||
// Deletes one batch of accounts that stayed unverified since before cutoff,
|
||||
@@ -91,13 +94,19 @@ type Querier interface {
|
||||
// provider's idempotency window reuses it instead of counting again.
|
||||
FindOpenMailQuotaReservation(ctx context.Context, arg FindOpenMailQuotaReservationParams) (FindOpenMailQuotaReservationRow, error)
|
||||
GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error)
|
||||
GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error)
|
||||
GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error)
|
||||
GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error)
|
||||
GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error)
|
||||
GetCurrentAssessmentCategoryOpening(ctx context.Context, category string) (AssessmentCategoryOpening, error)
|
||||
// The newest unrevoked record of a purpose other than C4.
|
||||
GetCurrentConsentRecord(ctx context.Context, arg GetCurrentConsentRecordParams) (GetCurrentConsentRecordRow, error)
|
||||
// The text of a purpose that applies at a time: the latest publication not
|
||||
// after it.
|
||||
GetCurrentConsentText(ctx context.Context, arg GetCurrentConsentTextParams) (ConsentText, error)
|
||||
// The database clock, which stamps the effective time of a policy version, so
|
||||
// "the version in force now" is judged against the same clock.
|
||||
GetDatabaseTime(ctx context.Context) (pgtype.Timestamptz, error)
|
||||
GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error)
|
||||
// Aggregates the deliveries by kind and status for the metrics, at most once
|
||||
// per metrics interval. It reads only kind, status, and next_attempt_at,
|
||||
@@ -112,6 +121,7 @@ type Querier interface {
|
||||
GetEffectivePolicyVersion(ctx context.Context, arg GetEffectivePolicyVersionParams) (PolicyVersion, error)
|
||||
// Explains why ConsumeEmailToken matched no row.
|
||||
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
|
||||
GetLatestAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error)
|
||||
// Reads the status of the newest delivery of a kind addressed to an account,
|
||||
// for the account's own view of its mail. It selects no address and no
|
||||
// content. The recipient index narrows the scan to the account's rows.
|
||||
@@ -133,6 +143,9 @@ type Querier interface {
|
||||
// clock that set occurred_at.
|
||||
GetOutboxBacklog(ctx context.Context) (GetOutboxBacklogRow, error)
|
||||
GetPolicyVersionByID(ctx context.Context, id pgtype.UUID) (PolicyVersion, error)
|
||||
// The published version of a family, if any. The partial unique index
|
||||
// assessment_families_one_published_key allows at most one.
|
||||
GetPublishedAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error)
|
||||
// Reads the backlog for metrics without locking: jobs that a worker may
|
||||
// claim at now, how long the earliest of them has waited, and the dead
|
||||
// jobs. The
|
||||
@@ -146,6 +159,16 @@ type Querier interface {
|
||||
GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error)
|
||||
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
|
||||
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
|
||||
// Stores an opening. The insert trigger derives required_families from the
|
||||
// policy document and counts the published families, and the coverage CHECK
|
||||
// refuses the row when they are fewer; both numbers from the caller are
|
||||
// replaced by the trigger's.
|
||||
InsertAssessmentCategoryOpening(ctx context.Context, arg InsertAssessmentCategoryOpeningParams) (AssessmentCategoryOpening, error)
|
||||
// Stores a new family version as a draft and returns the stored row with the
|
||||
// creation time set by the stamp trigger. A taken ID or (family_key, version)
|
||||
// returns no row instead of an error, so a conflict does not abort the
|
||||
// surrounding transaction.
|
||||
InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error)
|
||||
// Records a grant of C1, C2, C3, or C5. An unrevoked record of the same
|
||||
// subject, purpose, and text version already exists when no row returns;
|
||||
// the insert then changes nothing and does not abort the transaction.
|
||||
@@ -204,6 +227,10 @@ type Querier interface {
|
||||
InsertSession(ctx context.Context, arg InsertSessionParams) error
|
||||
InsertUser(ctx context.Context, arg InsertUserParams) error
|
||||
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
|
||||
// One page of the versions of a category in key and version order, after the
|
||||
// given position; an empty key and version 0 start at the beginning. The
|
||||
// (family_key, version) unique index serves the scan.
|
||||
ListAssessmentFamiliesByCategory(ctx context.Context, arg ListAssessmentFamiliesByCategoryParams) ([]AssessmentFamily, error)
|
||||
// One page of the subject's ledger, newest grant first, optionally limited
|
||||
// to one state. Every record query is scoped by the subject, so a caller
|
||||
// never reads or revokes another subject's consent. The state is computed,
|
||||
@@ -222,6 +249,10 @@ type Querier interface {
|
||||
// Lists the other accounts of a provider that have usage in a month, so
|
||||
// startup can warn about a renamed EMAIL_ACCOUNT.
|
||||
ListOtherMailQuotaAccounts(ctx context.Context, arg ListOtherMailQuotaAccountsParams) ([]string, error)
|
||||
// Serializes the operations that change which versions of a category are
|
||||
// published or open the category, until the transaction ends. The key is
|
||||
// namespaced, so it cannot collide with another use of advisory locks.
|
||||
LockAssessmentCategory(ctx context.Context, category string) error
|
||||
// Locks a claimed job for its handler transaction and checks that the lease
|
||||
// still belongs to this attempt. It returns no row when the job was
|
||||
// canceled, or reclaimed after the lease expired. While the lock is held,
|
||||
@@ -264,6 +295,10 @@ type Querier interface {
|
||||
// Reports whether a family has any version without reading a document, so a
|
||||
// caller that only needs presence never depends on decoding.
|
||||
PolicyVersionExists(ctx context.Context, policyKey string) (bool, error)
|
||||
// Moves a draft to published by the named operator and returns the row with
|
||||
// the publication time set by the guard trigger. No row means the version
|
||||
// was not a draft any more.
|
||||
PublishAssessmentFamily(ctx context.Context, arg PublishAssessmentFamilyParams) (AssessmentFamily, error)
|
||||
// Advances a delivery past one attempt and appends the attempt in one
|
||||
// statement, so both happen or neither does, inside or outside a
|
||||
// transaction. The update applies only while the stored version still
|
||||
@@ -288,6 +323,7 @@ type Querier interface {
|
||||
// the job did not cause the failure. The same guard as the completion
|
||||
// applies, one (id, attempt) pair per job. It returns the IDs it released.
|
||||
ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error)
|
||||
RetireAssessmentFamily(ctx context.Context, arg RetireAssessmentFamilyParams) (AssessmentFamily, error)
|
||||
// Revokes every unrevoked record of a purpose other than C4, superseded ones
|
||||
// included, and returns them. A revocation time before the grant time, from
|
||||
// clock skew between instances, is stamped at the grant time instead.
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Registered seed algorithms. Each one draws an input from the seed and
|
||||
// computes the reference answer with its solver. The names carry a version;
|
||||
// see assessmentAlgorithm.
|
||||
var assessmentAlgorithms = map[string]assessmentAlgorithm{
|
||||
"rate_limit_window.v1": {
|
||||
answerFormat: AnswerFormatInteger,
|
||||
parameters: []assessmentParameterSpec{
|
||||
{name: "requests", lowest: 1, highest: 500},
|
||||
{name: "window", lowest: 1, highest: 1000},
|
||||
{name: "limit", lowest: 1, highest: 100},
|
||||
{name: "max_gap", lowest: 0, highest: 100},
|
||||
},
|
||||
dataNames: []string{"timestamps"},
|
||||
requiredNames: []string{"timestamps", "window", "limit"},
|
||||
generate: generateRateLimitWindow,
|
||||
},
|
||||
"dedup_window.v1": {
|
||||
answerFormat: AnswerFormatInteger,
|
||||
parameters: []assessmentParameterSpec{
|
||||
{name: "events", lowest: 1, highest: 500},
|
||||
{name: "keys", lowest: 1, highest: 26},
|
||||
{name: "ttl", lowest: 1, highest: 1000},
|
||||
{name: "max_gap", lowest: 0, highest: 100},
|
||||
},
|
||||
dataNames: []string{"stream"},
|
||||
requiredNames: []string{"stream", "ttl"},
|
||||
generate: generateDedupWindow,
|
||||
},
|
||||
"lru_hits.v1": {
|
||||
answerFormat: AnswerFormatInteger,
|
||||
parameters: []assessmentParameterSpec{
|
||||
{name: "accesses", lowest: 1, highest: 500},
|
||||
{name: "keys", lowest: 1, highest: 100},
|
||||
{name: "capacity", lowest: 1, highest: 50},
|
||||
},
|
||||
dataNames: []string{"sequence"},
|
||||
requiredNames: []string{"sequence", "capacity"},
|
||||
generate: generateLRUHits,
|
||||
},
|
||||
"dependency_order.v1": {
|
||||
answerFormat: AnswerFormatIntegerSequence,
|
||||
parameters: []assessmentParameterSpec{
|
||||
{name: "tasks", lowest: 2, highest: 20},
|
||||
{name: "links", lowest: 0, highest: 60},
|
||||
},
|
||||
dataNames: []string{"dependencies"},
|
||||
requiredNames: []string{"dependencies", "tasks"},
|
||||
generate: generateDependencyOrder,
|
||||
},
|
||||
}
|
||||
|
||||
// keyLetters names the keys of the duplicate-window stream; the algorithm
|
||||
// allows at most this many keys.
|
||||
const keyLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
|
||||
// ascendingTimes returns count non-decreasing times. The first is a draw from
|
||||
// 0 to maxGap and every next one adds another such draw to its predecessor.
|
||||
func ascendingTimes(random *seededRandom, count, maxGap int32) []int {
|
||||
times := make([]int, count)
|
||||
current := 0
|
||||
for index := range times {
|
||||
current += int(random.between(0, maxGap))
|
||||
times[index] = current
|
||||
}
|
||||
return times
|
||||
}
|
||||
|
||||
// joinInts writes values as decimal numbers separated by single spaces.
|
||||
func joinInts(values []int) string {
|
||||
parts := make([]string, len(values))
|
||||
for index, value := range values {
|
||||
parts[index] = strconv.Itoa(value)
|
||||
}
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
// Data names: timestamps.
|
||||
func generateRateLimitWindow(random *seededRandom, parameters map[string]int32) (map[string]string, string) {
|
||||
times := ascendingTimes(random, parameters["requests"], parameters["max_gap"])
|
||||
rejected := rateLimitRejected(times, int(parameters["window"]), int(parameters["limit"]))
|
||||
return map[string]string{"timestamps": joinInts(times)}, strconv.Itoa(rejected)
|
||||
}
|
||||
|
||||
// rateLimitRejected counts requests that a sliding-window limiter rejects. A
|
||||
// request at time t is accepted when fewer than limit accepted requests lie
|
||||
// in the half-open interval (t-window, t]; rejected requests are not
|
||||
// remembered. Times are non-decreasing.
|
||||
func rateLimitRejected(times []int, window, limit int) int {
|
||||
accepted := make([]int, 0, len(times))
|
||||
oldest, rejected := 0, 0
|
||||
for _, moment := range times {
|
||||
for oldest < len(accepted) && accepted[oldest] <= moment-window {
|
||||
oldest++
|
||||
}
|
||||
if len(accepted)-oldest < limit {
|
||||
accepted = append(accepted, moment)
|
||||
} else {
|
||||
rejected++
|
||||
}
|
||||
}
|
||||
return rejected
|
||||
}
|
||||
|
||||
// Data names: stream.
|
||||
func generateDedupWindow(random *seededRandom, parameters map[string]int32) (map[string]string, string) {
|
||||
times := ascendingTimes(random, parameters["events"], parameters["max_gap"])
|
||||
keys := make([]int, len(times))
|
||||
events := make([]string, len(times))
|
||||
for index, moment := range times {
|
||||
keys[index] = random.below(int(parameters["keys"]))
|
||||
events[index] = keyLetters[keys[index]:keys[index]+1] + "@" + strconv.Itoa(moment)
|
||||
}
|
||||
processed := dedupProcessed(keys, times, int(parameters["ttl"]))
|
||||
return map[string]string{"stream": strings.Join(events, " ")}, strconv.Itoa(processed)
|
||||
}
|
||||
|
||||
// dedupProcessed counts events that an idempotent consumer processes. An
|
||||
// event is dropped as a duplicate when its key was processed less than ttl
|
||||
// time units earlier; a dropped event does not extend that period. Times are
|
||||
// non-decreasing.
|
||||
func dedupProcessed(keys, times []int, ttl int) int {
|
||||
lastProcessed := make(map[int]int, len(keys))
|
||||
processed := 0
|
||||
for index, key := range keys {
|
||||
last, seen := lastProcessed[key]
|
||||
if seen && times[index]-last < ttl {
|
||||
continue
|
||||
}
|
||||
lastProcessed[key] = times[index]
|
||||
processed++
|
||||
}
|
||||
return processed
|
||||
}
|
||||
|
||||
// Data names: sequence.
|
||||
func generateLRUHits(random *seededRandom, parameters map[string]int32) (map[string]string, string) {
|
||||
accesses := make([]int, parameters["accesses"])
|
||||
for index := range accesses {
|
||||
accesses[index] = 1 + random.below(int(parameters["keys"]))
|
||||
}
|
||||
hits := lruHits(accesses, int(parameters["capacity"]))
|
||||
return map[string]string{"sequence": joinInts(accesses)}, strconv.Itoa(hits)
|
||||
}
|
||||
|
||||
// lruHits counts the accesses that find their key in a least-recently-used
|
||||
// cache of the given capacity. A hit and a miss both make the key the most
|
||||
// recently used one; a miss on a full cache evicts the least recently used
|
||||
// key first.
|
||||
func lruHits(accesses []int, capacity int) int {
|
||||
// recent holds the cached keys from least to most recently used.
|
||||
recent := make([]int, 0, capacity)
|
||||
hits := 0
|
||||
for _, key := range accesses {
|
||||
position := -1
|
||||
for index, cached := range recent {
|
||||
if cached == key {
|
||||
position = index
|
||||
break
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case position >= 0:
|
||||
hits++
|
||||
recent = append(recent[:position], recent[position+1:]...)
|
||||
case len(recent) == capacity:
|
||||
recent = recent[1:]
|
||||
}
|
||||
recent = append(recent, key)
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
// Data names: dependencies.
|
||||
func generateDependencyOrder(random *seededRandom, parameters map[string]int32) (map[string]string, string) {
|
||||
tasks := int(parameters["tasks"])
|
||||
// A hidden shuffle fixes a valid order; links only point forward in it,
|
||||
// so the graph never has a cycle.
|
||||
hidden := make([]int, tasks)
|
||||
for index := range hidden {
|
||||
hidden[index] = index + 1
|
||||
}
|
||||
for index := tasks - 1; index > 0; index-- {
|
||||
swap := random.below(index + 1)
|
||||
hidden[index], hidden[swap] = hidden[swap], hidden[index]
|
||||
}
|
||||
seen := make(map[[2]int]bool)
|
||||
var links [][2]int
|
||||
var described []string
|
||||
for range parameters["links"] {
|
||||
first, second := random.below(tasks), random.below(tasks)
|
||||
if first == second {
|
||||
continue
|
||||
}
|
||||
if first > second {
|
||||
first, second = second, first
|
||||
}
|
||||
link := [2]int{hidden[first], hidden[second]}
|
||||
if seen[link] {
|
||||
continue
|
||||
}
|
||||
seen[link] = true
|
||||
links = append(links, link)
|
||||
described = append(described, strconv.Itoa(link[0])+"->"+strconv.Itoa(link[1]))
|
||||
}
|
||||
dependencies := "none"
|
||||
if len(described) > 0 {
|
||||
dependencies = strings.Join(described, " ")
|
||||
}
|
||||
return map[string]string{"dependencies": dependencies}, joinInts(smallestDependencyOrder(tasks, links))
|
||||
}
|
||||
|
||||
// smallestDependencyOrder returns the lexicographically smallest order of
|
||||
// tasks 1..tasks in which every link {before, after} has before first. The
|
||||
// links must not contain a cycle.
|
||||
func smallestDependencyOrder(tasks int, links [][2]int) []int {
|
||||
pending := make([]int, tasks+1)
|
||||
for _, link := range links {
|
||||
pending[link[1]]++
|
||||
}
|
||||
done := make([]bool, tasks+1)
|
||||
order := make([]int, 0, tasks)
|
||||
for len(order) < tasks {
|
||||
next := 0
|
||||
for task := 1; task <= tasks; task++ {
|
||||
if !done[task] && pending[task] == 0 {
|
||||
next = task
|
||||
break
|
||||
}
|
||||
}
|
||||
done[next] = true
|
||||
order = append(order, next)
|
||||
for _, link := range links {
|
||||
if link[0] == next {
|
||||
pending[link[1]]--
|
||||
}
|
||||
}
|
||||
}
|
||||
return order
|
||||
}
|
||||
@@ -0,0 +1,847 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
maxAssessmentTitleLength = 200
|
||||
maxAssessmentIdentityLength = 128
|
||||
maxAssessmentTextLength = 4000
|
||||
maxAssessmentRubricCriteria = 20
|
||||
maxAssessmentCriterionIDSize = 64
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidAssessmentFamily reports a family version, bundle value, or
|
||||
// opening that is missing, malformed, or inconsistent.
|
||||
ErrInvalidAssessmentFamily = errors.New("invalid assessment family")
|
||||
|
||||
// ErrAssessmentFamilyIntegrity reports a stored family whose canonical
|
||||
// content no longer matches the stored SHA-256. The row was changed
|
||||
// outside the application.
|
||||
ErrAssessmentFamilyIntegrity = errors.New("assessment family does not match its hash")
|
||||
|
||||
// ErrAssessmentRefused reports an operation that the bank rules refuse:
|
||||
// publishing a family or opening a category. errors.As with
|
||||
// *AssessmentRefusalError yields the machine-readable reason.
|
||||
ErrAssessmentRefused = errors.New("assessment bank operation refused")
|
||||
|
||||
assessmentCategoryPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{1,47}$`)
|
||||
assessmentFamilyKeyPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{2,63}$`)
|
||||
assessmentSpecializationPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{1,63}$`)
|
||||
assessmentBundleNamePattern = regexp.MustCompile(`^[a-z][a-z0-9._-]{2,63}$`)
|
||||
assessmentAuthorPattern = regexp.MustCompile(`^(ai|operator):[a-z0-9][a-z0-9._-]*$`)
|
||||
assessmentOperatorPattern = regexp.MustCompile(`^operator:[a-z0-9][a-z0-9._-]*$`)
|
||||
assessmentCriterionIDPattern = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
|
||||
)
|
||||
|
||||
// AssessmentRefusalReason names why the bank refused an operation.
|
||||
type AssessmentRefusalReason string
|
||||
|
||||
const (
|
||||
// RefusalReviewerMissing: the family has no reviewer.
|
||||
RefusalReviewerMissing AssessmentRefusalReason = "reviewer_missing"
|
||||
// RefusalReviewNotApproved: the review of the family is not approved.
|
||||
RefusalReviewNotApproved AssessmentRefusalReason = "review_not_approved"
|
||||
// RefusalNotDraft: the family is not a draft any more.
|
||||
RefusalNotDraft AssessmentRefusalReason = "not_draft"
|
||||
// RefusalNotPublished: the family is not published.
|
||||
RefusalNotPublished AssessmentRefusalReason = "not_published"
|
||||
// RefusalCoverageInsufficient: the category has fewer published families
|
||||
// than the grading policy requires.
|
||||
RefusalCoverageInsufficient AssessmentRefusalReason = "coverage_insufficient"
|
||||
// RefusalGradingPolicyMissing: no versioned grading policy was
|
||||
// referenced, or the reference does not resolve to a stored version.
|
||||
RefusalGradingPolicyMissing AssessmentRefusalReason = "grading_policy_missing"
|
||||
// RefusalVersionConflict: a version with the same number but different
|
||||
// content is already stored.
|
||||
RefusalVersionConflict AssessmentRefusalReason = "version_conflict"
|
||||
// RefusalVersionGap: the version is not the next one of its family.
|
||||
RefusalVersionGap AssessmentRefusalReason = "version_gap"
|
||||
// RefusalCategoryChanged: a new version moves the family to another
|
||||
// category.
|
||||
RefusalCategoryChanged AssessmentRefusalReason = "category_changed"
|
||||
// RefusalNewerVersionPublished: a newer version of the family is already
|
||||
// published, so an older one cannot be published.
|
||||
RefusalNewerVersionPublished AssessmentRefusalReason = "newer_version_published"
|
||||
// RefusalGradingPolicyNotCurrent: the referenced grading policy version
|
||||
// is stored but is not the version in force.
|
||||
RefusalGradingPolicyNotCurrent AssessmentRefusalReason = "grading_policy_not_current"
|
||||
)
|
||||
|
||||
// AssessmentRefusalError is the error of a refused operation. It carries the
|
||||
// reason for callers and a detail for operators. The detail never quotes
|
||||
// task content.
|
||||
type AssessmentRefusalError struct {
|
||||
Reason AssessmentRefusalReason
|
||||
Detail string
|
||||
}
|
||||
|
||||
func (refusal *AssessmentRefusalError) Error() string {
|
||||
return fmt.Sprintf("assessment bank refused: %s: %s", refusal.Reason, refusal.Detail)
|
||||
}
|
||||
|
||||
func (refusal *AssessmentRefusalError) Unwrap() error { return ErrAssessmentRefused }
|
||||
|
||||
// NewAssessmentRefusalError builds the error of a refused operation.
|
||||
func NewAssessmentRefusal(reason AssessmentRefusalReason, detail string) *AssessmentRefusalError {
|
||||
return &AssessmentRefusalError{Reason: reason, Detail: detail}
|
||||
}
|
||||
|
||||
func invalidAssessmentFamily(location, reason string) error {
|
||||
return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidAssessmentFamily)
|
||||
}
|
||||
|
||||
// AssessmentFamilyID identifies one stored version of a family.
|
||||
type AssessmentFamilyID uuid.UUID
|
||||
|
||||
// NewAssessmentFamilyID returns a time-ordered UUIDv7.
|
||||
func NewAssessmentFamilyID() (AssessmentFamilyID, error) {
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return AssessmentFamilyID{}, fmt.Errorf("domain.NewAssessmentFamilyID - generate ID: %w", err)
|
||||
}
|
||||
return AssessmentFamilyID(id), nil
|
||||
}
|
||||
|
||||
func (id AssessmentFamilyID) UUID() uuid.UUID { return uuid.UUID(id) }
|
||||
|
||||
func (id AssessmentFamilyID) String() string { return uuid.UUID(id).String() }
|
||||
|
||||
func (id AssessmentFamilyID) IsZero() bool { return uuid.UUID(id) == uuid.Nil }
|
||||
|
||||
// AssessmentCategory is a category of the bank, for example "backend". A
|
||||
// category is available to candidates only after an opening.
|
||||
type AssessmentCategory string
|
||||
|
||||
func ParseAssessmentCategory(value string) (AssessmentCategory, error) {
|
||||
if !assessmentCategoryPattern.MatchString(value) {
|
||||
return "", invalidAssessmentFamily("domain.ParseAssessmentCategory", "category must be 2 to 48 lowercase letters, digits, or '-', starting with a letter")
|
||||
}
|
||||
return AssessmentCategory(value), nil
|
||||
}
|
||||
|
||||
// AssessmentFamilyKey is the stable name of a family across its versions.
|
||||
type AssessmentFamilyKey string
|
||||
|
||||
func ParseAssessmentFamilyKey(value string) (AssessmentFamilyKey, error) {
|
||||
if !assessmentFamilyKeyPattern.MatchString(value) {
|
||||
return "", invalidAssessmentFamily("domain.ParseAssessmentFamilyKey", "family key must be 3 to 64 lowercase letters, digits, or '-', starting with a letter")
|
||||
}
|
||||
return AssessmentFamilyKey(value), nil
|
||||
}
|
||||
|
||||
// AssessmentSpecialization is the specialization or domain of a family
|
||||
// inside its category.
|
||||
type AssessmentSpecialization string
|
||||
|
||||
func ParseAssessmentSpecialization(value string) (AssessmentSpecialization, error) {
|
||||
if !assessmentSpecializationPattern.MatchString(value) {
|
||||
return "", invalidAssessmentFamily("domain.ParseAssessmentSpecialization", "specialization must be 2 to 64 lowercase letters, digits, or '-', starting with a letter")
|
||||
}
|
||||
return AssessmentSpecialization(value), nil
|
||||
}
|
||||
|
||||
// AssessmentBundleName names the bundle a version was imported from.
|
||||
type AssessmentBundleName string
|
||||
|
||||
func ParseAssessmentBundleName(value string) (AssessmentBundleName, error) {
|
||||
if !assessmentBundleNamePattern.MatchString(value) {
|
||||
return "", invalidAssessmentFamily("domain.ParseAssessmentBundleName", "bundle name must be 3 to 64 lowercase letters, digits, '.', '_', or '-', starting with a letter")
|
||||
}
|
||||
return AssessmentBundleName(value), nil
|
||||
}
|
||||
|
||||
// AssessmentAuthor identifies who wrote a family: "ai:<name>" for a
|
||||
// generated draft or "operator:<handle>" for a person. Never contact data.
|
||||
type AssessmentAuthor string
|
||||
|
||||
func ParseAssessmentAuthor(value string) (AssessmentAuthor, error) {
|
||||
if len(value) > maxAssessmentIdentityLength || !assessmentAuthorPattern.MatchString(value) {
|
||||
return "", invalidAssessmentFamily("domain.ParseAssessmentAuthor", "author must be ai:<name> or operator:<handle> of at most 128 bytes in lowercase letters, digits, '.', '_', or '-'")
|
||||
}
|
||||
return AssessmentAuthor(value), nil
|
||||
}
|
||||
|
||||
// AssessmentOperator identifies a person who reviews a family or opens a
|
||||
// category: "operator:<handle>". An AI draft cannot review itself or open a
|
||||
// category, so no "ai:" identity parses here.
|
||||
type AssessmentOperator string
|
||||
|
||||
func ParseAssessmentOperator(value string) (AssessmentOperator, error) {
|
||||
if len(value) > maxAssessmentIdentityLength || !assessmentOperatorPattern.MatchString(value) {
|
||||
return "", invalidAssessmentFamily("domain.ParseAssessmentOperator", "operator must be operator:<handle> of at most 128 bytes in lowercase letters, digits, '.', '_', or '-'")
|
||||
}
|
||||
return AssessmentOperator(value), nil
|
||||
}
|
||||
|
||||
// AssessmentReviewStatus is the state of the independent review of one
|
||||
// family version.
|
||||
type AssessmentReviewStatus string
|
||||
|
||||
const (
|
||||
// AssessmentReviewPending means no reviewer has judged the version yet.
|
||||
AssessmentReviewPending AssessmentReviewStatus = "pending"
|
||||
// AssessmentReviewApproved means an independent reviewer approved it.
|
||||
AssessmentReviewApproved AssessmentReviewStatus = "approved"
|
||||
// AssessmentReviewRejected means the reviewer did not approve it.
|
||||
AssessmentReviewRejected AssessmentReviewStatus = "rejected"
|
||||
)
|
||||
|
||||
func ParseAssessmentReviewStatus(value string) (AssessmentReviewStatus, error) {
|
||||
status := AssessmentReviewStatus(value)
|
||||
switch status {
|
||||
case AssessmentReviewPending, AssessmentReviewApproved, AssessmentReviewRejected:
|
||||
return status, nil
|
||||
default:
|
||||
return "", invalidAssessmentFamily("domain.ParseAssessmentReviewStatus", "review status must be pending, approved, or rejected")
|
||||
}
|
||||
}
|
||||
|
||||
// AssessmentLifecycle is the publication state of a family version.
|
||||
type AssessmentLifecycle string
|
||||
|
||||
const (
|
||||
// AssessmentLifecycleDraft is an imported version that candidates never
|
||||
// see.
|
||||
AssessmentLifecycleDraft AssessmentLifecycle = "draft"
|
||||
// AssessmentLifecyclePublished is a reviewed version that counts for
|
||||
// coverage.
|
||||
AssessmentLifecyclePublished AssessmentLifecycle = "published"
|
||||
// AssessmentLifecycleRetired is a version withdrawn from the bank.
|
||||
AssessmentLifecycleRetired AssessmentLifecycle = "retired"
|
||||
)
|
||||
|
||||
func ParseAssessmentLifecycle(value string) (AssessmentLifecycle, error) {
|
||||
lifecycle := AssessmentLifecycle(value)
|
||||
switch lifecycle {
|
||||
case AssessmentLifecycleDraft, AssessmentLifecyclePublished, AssessmentLifecycleRetired:
|
||||
return lifecycle, nil
|
||||
default:
|
||||
return "", invalidAssessmentFamily("domain.ParseAssessmentLifecycle", "lifecycle must be draft, published, or retired")
|
||||
}
|
||||
}
|
||||
|
||||
// AssessmentAnswerKey is the reference answer description of a family. The
|
||||
// reference answer of a variant itself comes from the family's algorithm.
|
||||
type AssessmentAnswerKey struct {
|
||||
// AnswerFormat is the format of the reference answer: "integer" or
|
||||
// "integer_sequence". It must match the algorithm of the generator.
|
||||
AnswerFormat string `json:"answer_format"`
|
||||
// ReferenceSolution describes the reference approach in prose.
|
||||
ReferenceSolution string `json:"reference_solution"`
|
||||
}
|
||||
|
||||
// AssessmentRubricCriterion is one thing a reviewer or grader looks for.
|
||||
// A criterion has no points: how criteria become a grade is a matter of the
|
||||
// versioned grading policy, not of the family.
|
||||
type AssessmentRubricCriterion struct {
|
||||
ID string `json:"id"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// AssessmentRubric is the rubric of a family. Its principle does not depend
|
||||
// on the seed of a variant.
|
||||
type AssessmentRubric struct {
|
||||
Principle string `json:"principle"`
|
||||
Criteria []AssessmentRubricCriterion `json:"criteria"`
|
||||
}
|
||||
|
||||
func (rubric AssessmentRubric) clone() AssessmentRubric {
|
||||
copied := rubric
|
||||
copied.Criteria = append([]AssessmentRubricCriterion(nil), rubric.Criteria...)
|
||||
return copied
|
||||
}
|
||||
|
||||
func (rubric AssessmentRubric) validate(location string) error {
|
||||
if err := checkAssessmentText(location, "rubric principle", rubric.Principle); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rubric.Criteria) == 0 || len(rubric.Criteria) > maxAssessmentRubricCriteria {
|
||||
return invalidAssessmentFamily(location, fmt.Sprintf("rubric must have 1 to %d criteria", maxAssessmentRubricCriteria))
|
||||
}
|
||||
seen := make(map[string]bool, len(rubric.Criteria))
|
||||
for _, criterion := range rubric.Criteria {
|
||||
if len(criterion.ID) > maxAssessmentCriterionIDSize || !assessmentCriterionIDPattern.MatchString(criterion.ID) {
|
||||
return invalidAssessmentFamily(location, "rubric criterion ID must be lowercase letters, digits, or '_', starting with a letter")
|
||||
}
|
||||
if seen[criterion.ID] {
|
||||
return invalidAssessmentFamily(location, "rubric criterion IDs must be unique")
|
||||
}
|
||||
seen[criterion.ID] = true
|
||||
if err := checkAssessmentText(location, "rubric criterion description", criterion.Description); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (key AssessmentAnswerKey) validate(location string, algorithm assessmentAlgorithm) error {
|
||||
if key.AnswerFormat != algorithm.answerFormat {
|
||||
return invalidAssessmentFamily(location, "answer format does not match the answer format of the generator algorithm")
|
||||
}
|
||||
return checkAssessmentText(location, "reference solution", key.ReferenceSolution)
|
||||
}
|
||||
|
||||
// checkAssessmentText accepts non-empty text without surrounding blanks, and
|
||||
// without control characters other than line breaks and without Unicode
|
||||
// format characters (category Cf) and line and paragraph separators (Zl, Zp).
|
||||
func checkAssessmentText(location, field, value string) error {
|
||||
trimmed := strings.TrimSpace(value)
|
||||
if trimmed == "" || trimmed != value || len(value) > maxAssessmentTextLength {
|
||||
return invalidAssessmentFamily(location, fmt.Sprintf("%s must be 1 to %d bytes without surrounding blanks", field, maxAssessmentTextLength))
|
||||
}
|
||||
for _, character := range value {
|
||||
if unicode.IsControl(character) && character != '\n' {
|
||||
return invalidAssessmentFamily(location, field+" must not contain control characters")
|
||||
}
|
||||
// Format characters, such as the bidirectional overrides, change how
|
||||
// text is displayed without being visible, and the line and
|
||||
// paragraph separators U+2028 and U+2029 break lines in ways that
|
||||
// plain text does not expect.
|
||||
if unicode.In(character, unicode.Cf, unicode.Zl, unicode.Zp) {
|
||||
return invalidAssessmentFamily(location, field+" must not contain invisible format characters or line and paragraph separators")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AssessmentFamilyCore holds the immutable content of one family version as
|
||||
// the importer supplies it.
|
||||
type AssessmentFamilyCore struct {
|
||||
Key AssessmentFamilyKey
|
||||
Version int32
|
||||
Category AssessmentCategory
|
||||
Specialization AssessmentSpecialization
|
||||
Title string
|
||||
BundleName AssessmentBundleName
|
||||
Author AssessmentAuthor
|
||||
// Reviewer is empty while the review is pending.
|
||||
Reviewer AssessmentOperator
|
||||
ReviewStatus AssessmentReviewStatus
|
||||
Generator AssessmentSeedGenerator
|
||||
AnswerKey AssessmentAnswerKey
|
||||
Rubric AssessmentRubric
|
||||
}
|
||||
|
||||
// NewAssessmentFamilyDraftInput is the input of NewAssessmentFamilyDraft.
|
||||
type NewAssessmentFamilyDraftInput = AssessmentFamilyCore
|
||||
|
||||
func (core AssessmentFamilyCore) clone() AssessmentFamilyCore {
|
||||
copied := core
|
||||
copied.Generator = core.Generator.clone()
|
||||
copied.Rubric = core.Rubric.clone()
|
||||
return copied
|
||||
}
|
||||
|
||||
// validate checks every field and the rules between them. probe asks the
|
||||
// generator to render probe variants, which an importer does and a read of a
|
||||
// stored row does not. The review rules
|
||||
// mirror the CHECK constraints of assessment_families: a review is pending
|
||||
// exactly while no reviewer is recorded, and the reviewer is never the
|
||||
// author.
|
||||
func (core AssessmentFamilyCore) validate(location string, probe bool) error {
|
||||
if _, err := ParseAssessmentFamilyKey(string(core.Key)); err != nil {
|
||||
return fmt.Errorf("%s - validate key: %w", location, err)
|
||||
}
|
||||
if core.Version <= 0 {
|
||||
return invalidAssessmentFamily(location, "version must be positive")
|
||||
}
|
||||
if _, err := ParseAssessmentCategory(string(core.Category)); err != nil {
|
||||
return fmt.Errorf("%s - validate category: %w", location, err)
|
||||
}
|
||||
if _, err := ParseAssessmentSpecialization(string(core.Specialization)); err != nil {
|
||||
return fmt.Errorf("%s - validate specialization: %w", location, err)
|
||||
}
|
||||
if _, err := ParseAssessmentBundleName(string(core.BundleName)); err != nil {
|
||||
return fmt.Errorf("%s - validate bundle name: %w", location, err)
|
||||
}
|
||||
if _, err := ParseAssessmentAuthor(string(core.Author)); err != nil {
|
||||
return fmt.Errorf("%s - validate author: %w", location, err)
|
||||
}
|
||||
if len(core.Title) > maxAssessmentTitleLength || strings.Contains(core.Title, "\n") ||
|
||||
checkAssessmentText(location, "title", core.Title) != nil {
|
||||
return invalidAssessmentFamily(location, "title must be one line of 1 to 200 bytes without surrounding blanks")
|
||||
}
|
||||
if err := core.validateReview(location); err != nil {
|
||||
return err
|
||||
}
|
||||
algorithm, err := core.Generator.validate(location, probe)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := core.AnswerKey.validate(location, algorithm); err != nil {
|
||||
return err
|
||||
}
|
||||
return core.Rubric.validate(location)
|
||||
}
|
||||
|
||||
func (core AssessmentFamilyCore) validateReview(location string) error {
|
||||
if _, err := ParseAssessmentReviewStatus(string(core.ReviewStatus)); err != nil {
|
||||
return fmt.Errorf("%s - validate review status: %w", location, err)
|
||||
}
|
||||
if core.ReviewStatus == AssessmentReviewPending {
|
||||
if core.Reviewer != "" {
|
||||
return invalidAssessmentFamily(location, "a pending review has no reviewer")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if _, err := ParseAssessmentOperator(string(core.Reviewer)); err != nil {
|
||||
return fmt.Errorf("%s - validate reviewer: %w", location, err)
|
||||
}
|
||||
if string(core.Reviewer) == string(core.Author) {
|
||||
return invalidAssessmentFamily(location, "the reviewer must not be the author")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// currentAssessmentHashScheme is the scheme that new versions are stored
|
||||
// with. A stored row keeps its own scheme in the hash_scheme column, and
|
||||
// RestoreAssessmentFamily verifies it with that scheme's function, so a later
|
||||
// scheme verifies new rows without invalidating the old ones. A change of the
|
||||
// canonical layout, of a field, or of the encoding adds a scheme here and to
|
||||
// the assessment_families_hash_scheme_known CHECK; it never edits the
|
||||
// function of an existing scheme.
|
||||
const currentAssessmentHashScheme int16 = 1
|
||||
|
||||
// assessmentHashSchemes maps a scheme number to its hash function. It is a
|
||||
// variable only so that a test can register a scheme.
|
||||
var assessmentHashSchemes = map[int16]func(AssessmentFamilyCore) (AssessmentContentHash, error){
|
||||
1: contentHashV1,
|
||||
}
|
||||
|
||||
// assessmentCanonicalContentV1 is the form that scheme 1 hashes. The bundle
|
||||
// name, the ID, and the lifecycle are not part of it: they are provenance and
|
||||
// state, not content.
|
||||
type assessmentCanonicalContentV1 struct {
|
||||
Key AssessmentFamilyKey `json:"family_key"`
|
||||
Version int32 `json:"version"`
|
||||
Category AssessmentCategory `json:"category"`
|
||||
Specialization AssessmentSpecialization `json:"specialization"`
|
||||
Title string `json:"title"`
|
||||
Author AssessmentAuthor `json:"author"`
|
||||
Reviewer AssessmentOperator `json:"reviewer,omitempty"`
|
||||
ReviewStatus AssessmentReviewStatus `json:"review_status"`
|
||||
Generator AssessmentSeedGenerator `json:"seed_generator"`
|
||||
AnswerKey AssessmentAnswerKey `json:"answer_key"`
|
||||
Rubric AssessmentRubric `json:"rubric"`
|
||||
}
|
||||
|
||||
// AssessmentContentHash is the SHA-256 of the canonical content.
|
||||
type AssessmentContentHash [sha256.Size]byte
|
||||
|
||||
// contentHash hashes the content with the named scheme, or returns
|
||||
// ErrInvalidAssessmentFamily for a scheme that this code does not know.
|
||||
func (core AssessmentFamilyCore) contentHash(scheme int16) (AssessmentContentHash, error) {
|
||||
hashContent, ok := assessmentHashSchemes[scheme]
|
||||
if !ok {
|
||||
return AssessmentContentHash{}, invalidAssessmentFamily("AssessmentFamilyCore.contentHash", "hash scheme is unknown")
|
||||
}
|
||||
return hashContent(core)
|
||||
}
|
||||
|
||||
func contentHashV1(core AssessmentFamilyCore) (AssessmentContentHash, error) {
|
||||
encoded, err := json.Marshal(assessmentCanonicalContentV1{
|
||||
Key: core.Key, Version: core.Version, Category: core.Category, Specialization: core.Specialization,
|
||||
Title: core.Title, Author: core.Author, Reviewer: core.Reviewer, ReviewStatus: core.ReviewStatus,
|
||||
Generator: core.Generator, AnswerKey: core.AnswerKey, Rubric: core.Rubric,
|
||||
})
|
||||
if err != nil {
|
||||
return AssessmentContentHash{}, fmt.Errorf("domain.contentHashV1 - encode canonical content: %w", err)
|
||||
}
|
||||
return sha256.Sum256(encoded), nil
|
||||
}
|
||||
|
||||
// AssessmentFamilyDraft is a version that is not stored yet. It has an ID, a
|
||||
// validated content, and its hash, but no creation time: the database sets
|
||||
// that. Every stored version starts as a draft, whatever its review says.
|
||||
type AssessmentFamilyDraft struct {
|
||||
id AssessmentFamilyID
|
||||
core AssessmentFamilyCore
|
||||
hash AssessmentContentHash
|
||||
scheme int16
|
||||
}
|
||||
|
||||
// NewAssessmentFamilyDraft validates the content, hashes it, and assigns a
|
||||
// UUIDv7. The family can be generated for review before it is published.
|
||||
func NewAssessmentFamilyDraft(input NewAssessmentFamilyDraftInput) (AssessmentFamilyDraft, error) {
|
||||
const location = "domain.NewAssessmentFamilyDraft"
|
||||
core := input.clone()
|
||||
if err := core.validate(location, true); err != nil {
|
||||
return AssessmentFamilyDraft{}, err
|
||||
}
|
||||
hash, err := core.contentHash(currentAssessmentHashScheme)
|
||||
if err != nil {
|
||||
return AssessmentFamilyDraft{}, err
|
||||
}
|
||||
id, err := NewAssessmentFamilyID()
|
||||
if err != nil {
|
||||
return AssessmentFamilyDraft{}, fmt.Errorf("%s - assign ID: %w", location, err)
|
||||
}
|
||||
return AssessmentFamilyDraft{id: id, core: core, hash: hash, scheme: currentAssessmentHashScheme}, nil
|
||||
}
|
||||
|
||||
func (draft AssessmentFamilyDraft) ID() AssessmentFamilyID { return draft.id }
|
||||
|
||||
// Core returns a copy of the content.
|
||||
func (draft AssessmentFamilyDraft) Core() AssessmentFamilyCore { return draft.core.clone() }
|
||||
|
||||
func (draft AssessmentFamilyDraft) ContentHash() AssessmentContentHash { return draft.hash }
|
||||
|
||||
// HashScheme is the scheme of ContentHash, stored beside it.
|
||||
func (draft AssessmentFamilyDraft) HashScheme() int16 { return draft.scheme }
|
||||
|
||||
// IsZero reports a draft not built by NewAssessmentFamilyDraft.
|
||||
func (draft AssessmentFamilyDraft) IsZero() bool { return draft.id.IsZero() }
|
||||
|
||||
// SeedGeneratorJSON returns the canonical document stored in the
|
||||
// seed_generator column.
|
||||
func (draft AssessmentFamilyDraft) SeedGeneratorJSON() ([]byte, error) {
|
||||
return marshalAssessmentDocument("AssessmentFamilyDraft.SeedGeneratorJSON", draft.core.Generator)
|
||||
}
|
||||
|
||||
// AnswerKeyJSON returns the canonical document stored in the answer_key
|
||||
// column.
|
||||
func (draft AssessmentFamilyDraft) AnswerKeyJSON() ([]byte, error) {
|
||||
return marshalAssessmentDocument("AssessmentFamilyDraft.AnswerKeyJSON", draft.core.AnswerKey)
|
||||
}
|
||||
|
||||
// RubricJSON returns the canonical document stored in the rubric column.
|
||||
func (draft AssessmentFamilyDraft) RubricJSON() ([]byte, error) {
|
||||
return marshalAssessmentDocument("AssessmentFamilyDraft.RubricJSON", draft.core.Rubric)
|
||||
}
|
||||
|
||||
func marshalAssessmentDocument(location string, value any) ([]byte, error) {
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - encode document: %w", location, err)
|
||||
}
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
// StoredAssessmentFamily is an assessment_families row as storage reads it.
|
||||
// Reviewer, PublishedBy, and RetiredBy are empty for a NULL column, and a
|
||||
// zero PublishedAt or RetiredAt means NULL.
|
||||
type StoredAssessmentFamily struct {
|
||||
ID AssessmentFamilyID
|
||||
FamilyKey string
|
||||
Version int32
|
||||
Category string
|
||||
Specialization string
|
||||
Title string
|
||||
BundleName string
|
||||
Author string
|
||||
Reviewer string
|
||||
ReviewStatus string
|
||||
SeedGenerator []byte
|
||||
AnswerKey []byte
|
||||
Rubric []byte
|
||||
ContentHash []byte
|
||||
HashScheme int16
|
||||
Lifecycle string
|
||||
CreatedAt time.Time
|
||||
PublishedAt time.Time
|
||||
PublishedBy string
|
||||
RetiredAt time.Time
|
||||
RetiredBy string
|
||||
}
|
||||
|
||||
// AssessmentFamily is one stored, immutable version of a family. Only
|
||||
// RestoreAssessmentFamily builds it; accessors return copies.
|
||||
type AssessmentFamily struct {
|
||||
id AssessmentFamilyID
|
||||
core AssessmentFamilyCore
|
||||
hash AssessmentContentHash
|
||||
scheme int16
|
||||
lifecycle AssessmentLifecycle
|
||||
createdAt time.Time
|
||||
publishedAt time.Time
|
||||
publishedBy AssessmentOperator
|
||||
retiredAt time.Time
|
||||
retiredBy AssessmentOperator
|
||||
}
|
||||
|
||||
// RestoreAssessmentFamily rebuilds a stored version. It decodes every
|
||||
// document strictly, validates the content like NewAssessmentFamilyDraft,
|
||||
// and requires the SHA-256 of the canonical content, built with the scheme
|
||||
// that the row names, to equal the stored hash; otherwise it returns
|
||||
// ErrAssessmentFamilyIntegrity, and an unknown scheme returns
|
||||
// ErrInvalidAssessmentFamily. jsonb normalizes
|
||||
// stored text, so the hash is never compared with stored bytes directly.
|
||||
func RestoreAssessmentFamily(stored StoredAssessmentFamily) (AssessmentFamily, error) {
|
||||
const location = "domain.RestoreAssessmentFamily"
|
||||
if stored.ID.IsZero() {
|
||||
return AssessmentFamily{}, invalidAssessmentFamily(location, "ID must not be nil")
|
||||
}
|
||||
lifecycle, err := ParseAssessmentLifecycle(stored.Lifecycle)
|
||||
if err != nil {
|
||||
return AssessmentFamily{}, fmt.Errorf("%s - parse lifecycle: %w", location, err)
|
||||
}
|
||||
if stored.CreatedAt.IsZero() {
|
||||
return AssessmentFamily{}, invalidAssessmentFamily(location, "creation time must be set")
|
||||
}
|
||||
core := AssessmentFamilyCore{
|
||||
Key: AssessmentFamilyKey(stored.FamilyKey),
|
||||
Version: stored.Version,
|
||||
Category: AssessmentCategory(stored.Category),
|
||||
Specialization: AssessmentSpecialization(stored.Specialization),
|
||||
Title: stored.Title,
|
||||
BundleName: AssessmentBundleName(stored.BundleName),
|
||||
Author: AssessmentAuthor(stored.Author),
|
||||
Reviewer: AssessmentOperator(stored.Reviewer),
|
||||
ReviewStatus: AssessmentReviewStatus(stored.ReviewStatus),
|
||||
}
|
||||
if err := decodeAssessmentDocument(stored.SeedGenerator, &core.Generator); err != nil {
|
||||
return AssessmentFamily{}, fmt.Errorf("%s - decode seed generator: %w", location, err)
|
||||
}
|
||||
if err := decodeAssessmentDocument(stored.AnswerKey, &core.AnswerKey); err != nil {
|
||||
return AssessmentFamily{}, fmt.Errorf("%s - decode answer key: %w", location, err)
|
||||
}
|
||||
if err := decodeAssessmentDocument(stored.Rubric, &core.Rubric); err != nil {
|
||||
return AssessmentFamily{}, fmt.Errorf("%s - decode rubric: %w", location, err)
|
||||
}
|
||||
if err := core.validate(location, false); err != nil {
|
||||
return AssessmentFamily{}, err
|
||||
}
|
||||
hash, err := core.contentHash(stored.HashScheme)
|
||||
if err != nil {
|
||||
return AssessmentFamily{}, fmt.Errorf("%s - hash content: %w", location, err)
|
||||
}
|
||||
if len(stored.ContentHash) != len(hash) || subtle.ConstantTimeCompare(stored.ContentHash, hash[:]) != 1 {
|
||||
return AssessmentFamily{}, fmt.Errorf("%s - verify content hash: %w", location, ErrAssessmentFamilyIntegrity)
|
||||
}
|
||||
if err := checkLifecycleStamps(location, lifecycle, core, stored); err != nil {
|
||||
return AssessmentFamily{}, err
|
||||
}
|
||||
for _, actor := range []string{stored.PublishedBy, stored.RetiredBy} {
|
||||
if actor == "" {
|
||||
continue
|
||||
}
|
||||
if _, err := ParseAssessmentOperator(actor); err != nil {
|
||||
return AssessmentFamily{}, fmt.Errorf("%s - parse publishing operator: %w", location, err)
|
||||
}
|
||||
}
|
||||
return AssessmentFamily{
|
||||
id: stored.ID,
|
||||
core: core,
|
||||
hash: hash,
|
||||
scheme: stored.HashScheme,
|
||||
lifecycle: lifecycle,
|
||||
createdAt: stored.CreatedAt,
|
||||
publishedAt: stored.PublishedAt,
|
||||
publishedBy: AssessmentOperator(stored.PublishedBy),
|
||||
retiredAt: stored.RetiredAt,
|
||||
retiredBy: AssessmentOperator(stored.RetiredBy),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func checkLifecycleStamps(location string, lifecycle AssessmentLifecycle, core AssessmentFamilyCore, stored StoredAssessmentFamily) error {
|
||||
published, retired := !stored.PublishedAt.IsZero(), !stored.RetiredAt.IsZero()
|
||||
if published != (stored.PublishedBy != "") || retired != (stored.RetiredBy != "") {
|
||||
return invalidAssessmentFamily(location, "a publication or retirement time comes with the operator who made it, and only with it")
|
||||
}
|
||||
switch {
|
||||
case lifecycle == AssessmentLifecycleDraft && (published || retired):
|
||||
return invalidAssessmentFamily(location, "a draft has no publication or retirement time")
|
||||
case lifecycle == AssessmentLifecyclePublished && (!published || retired):
|
||||
return invalidAssessmentFamily(location, "a published version has a publication time and no retirement time")
|
||||
case lifecycle == AssessmentLifecycleRetired && (!published || !retired):
|
||||
return invalidAssessmentFamily(location, "a retired version has publication and retirement times")
|
||||
case lifecycle != AssessmentLifecycleDraft && core.ReviewStatus != AssessmentReviewApproved:
|
||||
return invalidAssessmentFamily(location, "a published or retired version needs an approved review")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeAssessmentDocument decodes one JSON document strictly: an unknown
|
||||
// field or trailing data is an error, so a document of a different layout
|
||||
// never decodes into a partly empty value.
|
||||
func decodeAssessmentDocument(document []byte, target any) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(document))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrInvalidAssessmentFamily, err)
|
||||
}
|
||||
if decoder.More() {
|
||||
return fmt.Errorf("%w: trailing data after the document", ErrInvalidAssessmentFamily)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (family AssessmentFamily) ID() AssessmentFamilyID { return family.id }
|
||||
|
||||
// Core returns a copy of the content.
|
||||
func (family AssessmentFamily) Core() AssessmentFamilyCore { return family.core.clone() }
|
||||
|
||||
func (family AssessmentFamily) Key() AssessmentFamilyKey { return family.core.Key }
|
||||
|
||||
func (family AssessmentFamily) Version() int32 { return family.core.Version }
|
||||
|
||||
func (family AssessmentFamily) Category() AssessmentCategory { return family.core.Category }
|
||||
|
||||
func (family AssessmentFamily) Author() AssessmentAuthor { return family.core.Author }
|
||||
|
||||
// Reviewer is empty while the review is pending.
|
||||
func (family AssessmentFamily) Reviewer() AssessmentOperator { return family.core.Reviewer }
|
||||
|
||||
func (family AssessmentFamily) ReviewStatus() AssessmentReviewStatus { return family.core.ReviewStatus }
|
||||
|
||||
func (family AssessmentFamily) AnswerKey() AssessmentAnswerKey { return family.core.AnswerKey }
|
||||
|
||||
// Rubric returns a copy of the rubric.
|
||||
func (family AssessmentFamily) Rubric() AssessmentRubric { return family.core.Rubric.clone() }
|
||||
|
||||
func (family AssessmentFamily) ContentHash() AssessmentContentHash { return family.hash }
|
||||
|
||||
// HashScheme is the scheme that ContentHash was verified with.
|
||||
func (family AssessmentFamily) HashScheme() int16 { return family.scheme }
|
||||
|
||||
func (family AssessmentFamily) Lifecycle() AssessmentLifecycle { return family.lifecycle }
|
||||
|
||||
func (family AssessmentFamily) CreatedAt() time.Time { return family.createdAt }
|
||||
|
||||
// PublishedAt returns the publication time, or false for a draft.
|
||||
func (family AssessmentFamily) PublishedAt() (time.Time, bool) {
|
||||
return family.publishedAt, !family.publishedAt.IsZero()
|
||||
}
|
||||
|
||||
// PublishedBy is the operator who published the version, or empty for a
|
||||
// draft. It is a declared value of the caller, not an authenticated identity,
|
||||
// until operator accounts exist.
|
||||
func (family AssessmentFamily) PublishedBy() AssessmentOperator { return family.publishedBy }
|
||||
|
||||
// RetiredBy is the operator who retired the version, or empty.
|
||||
func (family AssessmentFamily) RetiredBy() AssessmentOperator { return family.retiredBy }
|
||||
|
||||
// IsZero reports an AssessmentFamily not built by RestoreAssessmentFamily.
|
||||
func (family AssessmentFamily) IsZero() bool { return family.id.IsZero() }
|
||||
|
||||
// CheckPublishable reports why the version cannot be published, or nil. A
|
||||
// version is published only while it is a draft and only with an approved
|
||||
// review by a reviewer who is not its author. The database enforces the same
|
||||
// rules.
|
||||
func (family AssessmentFamily) CheckPublishable() error {
|
||||
switch {
|
||||
case family.lifecycle != AssessmentLifecycleDraft:
|
||||
return NewAssessmentRefusal(RefusalNotDraft, "only a draft version can be published")
|
||||
case family.core.Reviewer == "":
|
||||
return NewAssessmentRefusal(RefusalReviewerMissing, "the version has no independent reviewer")
|
||||
case family.core.ReviewStatus != AssessmentReviewApproved:
|
||||
return NewAssessmentRefusal(RefusalReviewNotApproved, "the review of the version is not approved")
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// CheckRetirable reports why the version cannot be retired, or nil.
|
||||
func (family AssessmentFamily) CheckRetirable() error {
|
||||
if family.lifecycle != AssessmentLifecyclePublished {
|
||||
return NewAssessmentRefusal(RefusalNotPublished, "only a published version can be retired")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RequiredPublishedAssessmentFamilies returns how many distinct published
|
||||
// families a category needs under a grading policy: max_scored_items plus
|
||||
// seed_items of the stop rule. The owner accepted this rule on 2026-10-06.
|
||||
// The reason: a family gives at most one item to an attempt, so a full
|
||||
// adaptive attempt, which can run to the maximum of scored items and also
|
||||
// carries the seed items, cannot run out of families. Both numbers are read
|
||||
// from the policy; the bank defines no threshold of its own, and a policy
|
||||
// without them is refused with RefusalGradingPolicyMissing. The trigger of
|
||||
// assessment_category_openings reads the same two document paths; an
|
||||
// integration test keeps them equal.
|
||||
func RequiredPublishedAssessmentFamilies(policy ProductPolicy) (int32, error) {
|
||||
rule := policy.Assessment.StopRule
|
||||
if rule.MaxScoredItems <= 0 || rule.SeedItems < 0 {
|
||||
return 0, NewAssessmentRefusal(RefusalGradingPolicyMissing, "the grading policy has no maximum of scored items")
|
||||
}
|
||||
return rule.MaxScoredItems + rule.SeedItems, nil
|
||||
}
|
||||
|
||||
// AssessmentCategoryOpeningDraft is an opening that is not stored yet.
|
||||
type AssessmentCategoryOpeningDraft struct {
|
||||
id uuid.UUID
|
||||
category AssessmentCategory
|
||||
policyVersionID PolicyVersionID
|
||||
openedBy AssessmentOperator
|
||||
requiredFamilies int32
|
||||
}
|
||||
|
||||
// NewAssessmentCategoryOpeningDraft checks that a category can open under the
|
||||
// referenced grading policy version and returns the opening to store. It
|
||||
// refuses with RefusalGradingPolicyMissing without a policy version and with
|
||||
// RefusalCoverageInsufficient when the published families do not reach the
|
||||
// policy's requirement. publishedFamilies is the count of distinct families
|
||||
// with a published version.
|
||||
func NewAssessmentCategoryOpeningDraft(
|
||||
category AssessmentCategory,
|
||||
policy PolicyVersion,
|
||||
publishedFamilies int32,
|
||||
openedBy AssessmentOperator,
|
||||
) (AssessmentCategoryOpeningDraft, error) {
|
||||
const location = "domain.NewAssessmentCategoryOpeningDraft"
|
||||
if _, err := ParseAssessmentCategory(string(category)); err != nil {
|
||||
return AssessmentCategoryOpeningDraft{}, fmt.Errorf("%s - validate category: %w", location, err)
|
||||
}
|
||||
if _, err := ParseAssessmentOperator(string(openedBy)); err != nil {
|
||||
return AssessmentCategoryOpeningDraft{}, fmt.Errorf("%s - validate operator: %w", location, err)
|
||||
}
|
||||
if policy.IsZero() {
|
||||
return AssessmentCategoryOpeningDraft{}, NewAssessmentRefusal(RefusalGradingPolicyMissing, "a category opens only under a versioned grading policy")
|
||||
}
|
||||
required, err := RequiredPublishedAssessmentFamilies(policy.Policy())
|
||||
if err != nil {
|
||||
return AssessmentCategoryOpeningDraft{}, err
|
||||
}
|
||||
if publishedFamilies < required {
|
||||
return AssessmentCategoryOpeningDraft{}, NewAssessmentRefusal(RefusalCoverageInsufficient,
|
||||
fmt.Sprintf("category has %d published families, grading policy version %d requires %d", publishedFamilies, policy.Version(), required))
|
||||
}
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return AssessmentCategoryOpeningDraft{}, fmt.Errorf("%s - assign ID: %w", location, err)
|
||||
}
|
||||
return AssessmentCategoryOpeningDraft{
|
||||
id: id, category: category, policyVersionID: policy.ID(), openedBy: openedBy, requiredFamilies: required,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (draft AssessmentCategoryOpeningDraft) ID() uuid.UUID { return draft.id }
|
||||
|
||||
func (draft AssessmentCategoryOpeningDraft) Category() AssessmentCategory { return draft.category }
|
||||
|
||||
func (draft AssessmentCategoryOpeningDraft) PolicyVersionID() PolicyVersionID {
|
||||
return draft.policyVersionID
|
||||
}
|
||||
|
||||
func (draft AssessmentCategoryOpeningDraft) OpenedBy() AssessmentOperator { return draft.openedBy }
|
||||
|
||||
func (draft AssessmentCategoryOpeningDraft) RequiredFamilies() int32 { return draft.requiredFamilies }
|
||||
|
||||
// IsZero reports a draft not built by NewAssessmentCategoryOpeningDraft.
|
||||
func (draft AssessmentCategoryOpeningDraft) IsZero() bool { return draft.id == uuid.Nil }
|
||||
|
||||
// AssessmentCategoryOpening is a stored opening: the proof that a category
|
||||
// was available at OpenedAt under one policy version.
|
||||
type AssessmentCategoryOpening struct {
|
||||
ID uuid.UUID
|
||||
Category AssessmentCategory
|
||||
PolicyVersionID PolicyVersionID
|
||||
OpenedBy AssessmentOperator
|
||||
RequiredFamilies int32
|
||||
PublishedFamilies int32
|
||||
OpenedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var testAssessmentCreatedAt = time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
|
||||
|
||||
func testAssessmentInput() NewAssessmentFamilyDraftInput {
|
||||
return NewAssessmentFamilyDraftInput{
|
||||
Key: "unit-test-family",
|
||||
Version: 1,
|
||||
Category: "unit-category",
|
||||
Specialization: "unit-domain",
|
||||
Title: "Unit test family",
|
||||
BundleName: "unit-test-bundle",
|
||||
Author: "ai:unit-test",
|
||||
ReviewStatus: AssessmentReviewPending,
|
||||
Generator: AssessmentSeedGenerator{
|
||||
Algorithm: "lru_hits.v1",
|
||||
Parameters: map[string]AssessmentParameterRange{
|
||||
"accesses": {Min: 10, Max: 30},
|
||||
"keys": {Min: 3, Max: 8},
|
||||
"capacity": {Min: 2, Max: 4},
|
||||
},
|
||||
StatementTemplate: "Capacity {{.capacity}}, reads {{.sequence}}.",
|
||||
},
|
||||
AnswerKey: AssessmentAnswerKey{AnswerFormat: AnswerFormatInteger, ReferenceSolution: "Simulate the cache."},
|
||||
Rubric: AssessmentRubric{
|
||||
Principle: "Compare with the reference answer.",
|
||||
Criteria: []AssessmentRubricCriterion{{ID: "correct_answer", Description: "Matches the reference answer."}},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func storedAssessmentFrom(t *testing.T, draft AssessmentFamilyDraft) StoredAssessmentFamily {
|
||||
t.Helper()
|
||||
generator, err := draft.SeedGeneratorJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("SeedGeneratorJSON() error = %v", err)
|
||||
}
|
||||
key, err := draft.AnswerKeyJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("AnswerKeyJSON() error = %v", err)
|
||||
}
|
||||
rubric, err := draft.RubricJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("RubricJSON() error = %v", err)
|
||||
}
|
||||
core, hash := draft.Core(), draft.ContentHash()
|
||||
return StoredAssessmentFamily{
|
||||
ID: draft.ID(), FamilyKey: string(core.Key), Version: core.Version, Category: string(core.Category),
|
||||
Specialization: string(core.Specialization), Title: core.Title, BundleName: string(core.BundleName),
|
||||
Author: string(core.Author), Reviewer: string(core.Reviewer), ReviewStatus: string(core.ReviewStatus),
|
||||
SeedGenerator: generator, AnswerKey: key, Rubric: rubric, ContentHash: hash[:], HashScheme: draft.HashScheme(),
|
||||
Lifecycle: string(AssessmentLifecycleDraft), CreatedAt: testAssessmentCreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func restoreAssessment(t *testing.T, input NewAssessmentFamilyDraftInput) AssessmentFamily {
|
||||
t.Helper()
|
||||
draft, err := NewAssessmentFamilyDraft(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
|
||||
}
|
||||
family, err := RestoreAssessmentFamily(storedAssessmentFrom(t, draft))
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreAssessmentFamily() error = %v", err)
|
||||
}
|
||||
return family
|
||||
}
|
||||
|
||||
func TestNewAssessmentFamilyDraftRejectsInvalidContent(t *testing.T) {
|
||||
tests := map[string]func(*NewAssessmentFamilyDraftInput){
|
||||
"zero version": func(input *NewAssessmentFamilyDraftInput) { input.Version = 0 },
|
||||
"bad family key": func(input *NewAssessmentFamilyDraftInput) { input.Key = "Bad Key" },
|
||||
"bad category": func(input *NewAssessmentFamilyDraftInput) { input.Category = "x" },
|
||||
"AI author cannot be reviewer": func(input *NewAssessmentFamilyDraftInput) {
|
||||
input.Reviewer, input.ReviewStatus = "ai:unit-test", AssessmentReviewApproved
|
||||
},
|
||||
"pending review with reviewer": func(input *NewAssessmentFamilyDraftInput) { input.Reviewer = "operator:reviewer" },
|
||||
"approved review without person": func(input *NewAssessmentFamilyDraftInput) { input.ReviewStatus = AssessmentReviewApproved },
|
||||
"reviewer is the author": func(input *NewAssessmentFamilyDraftInput) {
|
||||
input.Author, input.Reviewer, input.ReviewStatus = "operator:same", "operator:same", AssessmentReviewApproved
|
||||
},
|
||||
"unknown review status": func(input *NewAssessmentFamilyDraftInput) { input.ReviewStatus = "done" },
|
||||
"unknown algorithm": func(input *NewAssessmentFamilyDraftInput) { input.Generator.Algorithm = "nope.v1" },
|
||||
"missing parameter": func(input *NewAssessmentFamilyDraftInput) { delete(input.Generator.Parameters, "keys") },
|
||||
"parameter out of bounds": func(input *NewAssessmentFamilyDraftInput) {
|
||||
input.Generator.Parameters["capacity"] = AssessmentParameterRange{Min: 1, Max: 51}
|
||||
},
|
||||
"inverted parameter range": func(input *NewAssessmentFamilyDraftInput) {
|
||||
input.Generator.Parameters["capacity"] = AssessmentParameterRange{Min: 4, Max: 2}
|
||||
},
|
||||
"template names unknown data": func(input *NewAssessmentFamilyDraftInput) { input.Generator.StatementTemplate = "{{.missing}}" },
|
||||
"answer format mismatch": func(input *NewAssessmentFamilyDraftInput) { input.AnswerKey.AnswerFormat = AnswerFormatIntegerSequence },
|
||||
"empty rubric": func(input *NewAssessmentFamilyDraftInput) { input.Rubric.Criteria = nil },
|
||||
"duplicate criterion": func(input *NewAssessmentFamilyDraftInput) {
|
||||
input.Rubric.Criteria = append(input.Rubric.Criteria, input.Rubric.Criteria[0])
|
||||
},
|
||||
"multi-line title": func(input *NewAssessmentFamilyDraftInput) { input.Title = "a\nb" },
|
||||
}
|
||||
for name, mutate := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
input := testAssessmentInput()
|
||||
mutate(&input)
|
||||
if _, err := NewAssessmentFamilyDraft(input); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewAssessmentFamilyDraftDoesNotShareInputMaps(t *testing.T) {
|
||||
input := testAssessmentInput()
|
||||
draft, err := NewAssessmentFamilyDraft(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
|
||||
}
|
||||
input.Generator.Parameters["capacity"] = AssessmentParameterRange{Min: 1, Max: 1}
|
||||
if got := draft.Core().Generator.Parameters["capacity"]; got.Min != 2 || got.Max != 4 {
|
||||
t.Fatalf("draft capacity range = %+v after the input changed, want 2 to 4", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreAssessmentFamilyDetectsChangedContent(t *testing.T) {
|
||||
draft, err := NewAssessmentFamilyDraft(testAssessmentInput())
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
|
||||
}
|
||||
stored := storedAssessmentFrom(t, draft)
|
||||
stored.AnswerKey = []byte(strings.Replace(string(stored.AnswerKey), "Simulate the cache.", "Guess.", 1))
|
||||
if _, err := RestoreAssessmentFamily(stored); !errors.Is(err, ErrAssessmentFamilyIntegrity) {
|
||||
t.Fatalf("RestoreAssessmentFamily() error = %v, want ErrAssessmentFamilyIntegrity", err)
|
||||
}
|
||||
stored = storedAssessmentFrom(t, draft)
|
||||
stored.Rubric = []byte(`{"principle":"x","criteria":[],"extra":1}`)
|
||||
if _, err := RestoreAssessmentFamily(stored); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("RestoreAssessmentFamily(unknown field) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
stored = storedAssessmentFrom(t, draft)
|
||||
stored.Lifecycle = string(AssessmentLifecyclePublished)
|
||||
stored.PublishedAt = testAssessmentCreatedAt
|
||||
if _, err := RestoreAssessmentFamily(stored); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("RestoreAssessmentFamily(published without review) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckPublishableNamesTheReason(t *testing.T) {
|
||||
approved := testAssessmentInput()
|
||||
approved.Reviewer, approved.ReviewStatus = "operator:reviewer", AssessmentReviewApproved
|
||||
rejected := approved
|
||||
rejected.ReviewStatus = AssessmentReviewRejected
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
input NewAssessmentFamilyDraftInput
|
||||
want AssessmentRefusalReason
|
||||
}{
|
||||
{name: "pending review has no reviewer", input: testAssessmentInput(), want: RefusalReviewerMissing},
|
||||
{name: "rejected review", input: rejected, want: RefusalReviewNotApproved},
|
||||
{name: "approved review", input: approved},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
err := restoreAssessment(t, test.input).CheckPublishable()
|
||||
if test.want == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("CheckPublishable() error = %v, want nil", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
var refusal *AssessmentRefusalError
|
||||
if !errors.Is(err, ErrAssessmentRefused) || !errors.As(err, &refusal) || refusal.Reason != test.want {
|
||||
t.Fatalf("CheckPublishable() error = %v, want refusal %s", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewVariantIsDeterministicAndKeepsTheRubric(t *testing.T) {
|
||||
family := restoreAssessment(t, testAssessmentInput())
|
||||
first, err := family.NewVariant(7)
|
||||
if err != nil {
|
||||
t.Fatalf("NewVariant(7) error = %v", err)
|
||||
}
|
||||
second, err := family.NewVariant(7)
|
||||
if err != nil {
|
||||
t.Fatalf("NewVariant(7) again error = %v", err)
|
||||
}
|
||||
if first.Statement != second.Statement || first.ReferenceAnswer != second.ReferenceAnswer {
|
||||
t.Fatalf("variants of seed 7 differ:\n%q %q\n%q %q", first.Statement, first.ReferenceAnswer, second.Statement, second.ReferenceAnswer)
|
||||
}
|
||||
statements := map[string]bool{}
|
||||
for seed := VariantSeed(0); seed < 20; seed++ {
|
||||
variant, err := family.NewVariant(seed)
|
||||
if err != nil {
|
||||
t.Fatalf("NewVariant(%d) error = %v", seed, err)
|
||||
}
|
||||
statements[variant.Statement] = true
|
||||
if !slices.Equal(variant.Rubric.Criteria, first.Rubric.Criteria) || variant.Rubric.Principle != first.Rubric.Principle {
|
||||
t.Fatalf("rubric of seed %d differs from the rubric of seed 7", seed)
|
||||
}
|
||||
}
|
||||
if len(statements) < 15 {
|
||||
t.Fatalf("20 seeds produced %d distinct statements, want a spread of variants", len(statements))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEveryRegisteredAlgorithmBuildsVariantsInsideItsBounds(t *testing.T) {
|
||||
for name, algorithm := range assessmentAlgorithms {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
parameters := map[string]AssessmentParameterRange{}
|
||||
var template strings.Builder
|
||||
for _, spec := range algorithm.parameters {
|
||||
parameters[spec.name] = AssessmentParameterRange{Min: spec.lowest, Max: spec.highest}
|
||||
template.WriteString("{{." + spec.name + "}} ")
|
||||
}
|
||||
for _, data := range algorithm.dataNames {
|
||||
template.WriteString("{{." + data + "}} ")
|
||||
}
|
||||
generator := AssessmentSeedGenerator{Algorithm: name, Parameters: parameters, StatementTemplate: strings.TrimSpace(template.String())}
|
||||
for seed := VariantSeed(0); seed < 5; seed++ {
|
||||
statement, err := compileStatementTemplate("test", generator.StatementTemplate, algorithm)
|
||||
if err != nil {
|
||||
t.Fatalf("compileStatementTemplate() error = %v", err)
|
||||
}
|
||||
body, err := generator.instantiate(algorithm, statement, nil, seed)
|
||||
if err != nil {
|
||||
t.Fatalf("instantiate(seed %d) error = %v", seed, err)
|
||||
}
|
||||
if body.answer == "" {
|
||||
t.Fatalf("seed %d produced an empty reference answer", seed)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReferenceSolvers(t *testing.T) {
|
||||
t.Run("rate limiter", func(t *testing.T) {
|
||||
// Limit 2 per half-open window of 5 seconds. Accepted: 0, 1; 2, 3, 4
|
||||
// rejected; 5 is accepted because 0 left the window (5-5 = 0 is not
|
||||
// in (0, 5]); 6 is accepted because 1 left; 7 is rejected.
|
||||
got := rateLimitRejected([]int{0, 1, 2, 3, 4, 5, 6, 7}, 5, 2)
|
||||
if got != 4 {
|
||||
t.Fatalf("rateLimitRejected() = %d, want 4", got)
|
||||
}
|
||||
if got := rateLimitRejected([]int{3, 3, 3}, 1, 3); got != 0 {
|
||||
t.Fatalf("rateLimitRejected(burst within the limit) = %d, want 0", got)
|
||||
}
|
||||
})
|
||||
t.Run("duplicate window", func(t *testing.T) {
|
||||
// Key 0 at 0 is processed; at 2 it is dropped (2 < 3); at 3 it is
|
||||
// processed again because the dropped one did not extend the period.
|
||||
got := dedupProcessed([]int{0, 0, 0, 1}, []int{0, 2, 3, 3}, 3)
|
||||
if got != 3 {
|
||||
t.Fatalf("dedupProcessed() = %d, want 3", got)
|
||||
}
|
||||
})
|
||||
t.Run("lru cache", func(t *testing.T) {
|
||||
// Capacity 2: 1 miss, 2 miss, 1 hit (now 1 is recent), 3 miss evicts
|
||||
// 2, 2 miss evicts 1, 1 miss evicts 3.
|
||||
got := lruHits([]int{1, 2, 1, 3, 2, 1}, 2)
|
||||
if got != 1 {
|
||||
t.Fatalf("lruHits() = %d, want 1", got)
|
||||
}
|
||||
})
|
||||
t.Run("dependency order", func(t *testing.T) {
|
||||
// 3 before 1, 4 before 2: ready first are 3 and 4, so 3 starts; then
|
||||
// 1 and 4 are ready, so 1; then 4; then 2.
|
||||
got := joinInts(smallestDependencyOrder(4, [][2]int{{3, 1}, {4, 2}}))
|
||||
if got != "3 1 4 2" {
|
||||
t.Fatalf("smallestDependencyOrder() = %q, want %q", got, "3 1 4 2")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNewAssessmentCategoryOpeningDraftReadsCoverageFromThePolicy(t *testing.T) {
|
||||
policy := mustRestore(t, storedFrom(mustDraft(t, testDraftInput(), 1)))
|
||||
required, err := RequiredPublishedAssessmentFamilies(policy.Policy())
|
||||
if err != nil {
|
||||
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
|
||||
}
|
||||
rule := policy.Policy().Assessment.StopRule
|
||||
if required != rule.MaxScoredItems+rule.SeedItems {
|
||||
t.Fatalf("required families = %d, want max_scored_items %d + seed_items %d", required, rule.MaxScoredItems, rule.SeedItems)
|
||||
}
|
||||
if _, err := RequiredPublishedAssessmentFamilies(ProductPolicy{}); !errors.Is(err, ErrAssessmentRefused) {
|
||||
t.Fatalf("RequiredPublishedAssessmentFamilies(no stop rule) error = %v, want a refusal", err)
|
||||
}
|
||||
|
||||
if _, err := NewAssessmentCategoryOpeningDraft("unit-category", policy, required, "operator:opener"); err != nil {
|
||||
t.Fatalf("NewAssessmentCategoryOpeningDraft(enough coverage) error = %v", err)
|
||||
}
|
||||
var refusal *AssessmentRefusalError
|
||||
_, err = NewAssessmentCategoryOpeningDraft("unit-category", policy, required-1, "operator:opener")
|
||||
if !errors.As(err, &refusal) || refusal.Reason != RefusalCoverageInsufficient {
|
||||
t.Fatalf("NewAssessmentCategoryOpeningDraft(too few) error = %v, want coverage refusal", err)
|
||||
}
|
||||
_, err = NewAssessmentCategoryOpeningDraft("unit-category", PolicyVersion{}, required, "operator:opener")
|
||||
if !errors.As(err, &refusal) || refusal.Reason != RefusalGradingPolicyMissing {
|
||||
t.Fatalf("NewAssessmentCategoryOpeningDraft(no policy) error = %v, want policy refusal", err)
|
||||
}
|
||||
if _, err := NewAssessmentCategoryOpeningDraft("unit-category", policy, required, "ai:draft"); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("NewAssessmentCategoryOpeningDraft(AI operator) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A row is verified with the scheme it was stored with, so adding a scheme
|
||||
// later does not invalidate old rows or accept a hash of the wrong scheme.
|
||||
func TestRestoreVerifiesARowWithItsOwnHashScheme(t *testing.T) {
|
||||
const testScheme int16 = 2
|
||||
assessmentHashSchemes[testScheme] = func(core AssessmentFamilyCore) (AssessmentContentHash, error) {
|
||||
hash, err := contentHashV1(core)
|
||||
hash[0] ^= 0xff // a different function of the same content
|
||||
return hash, err
|
||||
}
|
||||
t.Cleanup(func() { delete(assessmentHashSchemes, testScheme) })
|
||||
|
||||
draft, err := NewAssessmentFamilyDraft(testAssessmentInput())
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
|
||||
}
|
||||
if draft.HashScheme() != currentAssessmentHashScheme {
|
||||
t.Fatalf("draft scheme = %d, want the current scheme %d", draft.HashScheme(), currentAssessmentHashScheme)
|
||||
}
|
||||
old := storedAssessmentFrom(t, draft)
|
||||
if family, err := RestoreAssessmentFamily(old); err != nil || family.HashScheme() != 1 {
|
||||
t.Fatalf("RestoreAssessmentFamily(scheme 1 row) = scheme %d, %v, want a verified row of scheme 1", family.HashScheme(), err)
|
||||
}
|
||||
|
||||
core := draft.Core()
|
||||
newer, err := core.contentHash(testScheme)
|
||||
if err != nil {
|
||||
t.Fatalf("contentHash(scheme 2) error = %v", err)
|
||||
}
|
||||
row := old
|
||||
row.HashScheme, row.ContentHash = testScheme, newer[:]
|
||||
if family, err := RestoreAssessmentFamily(row); err != nil || family.HashScheme() != testScheme {
|
||||
t.Fatalf("RestoreAssessmentFamily(scheme 2 row) = scheme %d, %v, want a verified row of scheme 2", family.HashScheme(), err)
|
||||
}
|
||||
// The hash of one scheme under the name of the other, and an unknown
|
||||
// scheme, are refused.
|
||||
row.ContentHash = old.ContentHash
|
||||
if _, err := RestoreAssessmentFamily(row); !errors.Is(err, ErrAssessmentFamilyIntegrity) {
|
||||
t.Fatalf("RestoreAssessmentFamily(scheme 1 hash under scheme 2) error = %v, want ErrAssessmentFamilyIntegrity", err)
|
||||
}
|
||||
row.HashScheme = 9
|
||||
if _, err := RestoreAssessmentFamily(row); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("RestoreAssessmentFamily(unknown scheme) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"maps"
|
||||
"strconv"
|
||||
"text/template/parse"
|
||||
)
|
||||
|
||||
// Answer formats of reference answers.
|
||||
const (
|
||||
// AnswerFormatInteger is a single decimal integer.
|
||||
AnswerFormatInteger = "integer"
|
||||
// AnswerFormatIntegerSequence is decimal integers separated by single
|
||||
// spaces.
|
||||
AnswerFormatIntegerSequence = "integer_sequence"
|
||||
)
|
||||
|
||||
// variantSeedDomain separates the seed derivation of variants from any other
|
||||
// use of SHA-256 in the system.
|
||||
const variantSeedDomain = "lincodex.assessment.variant.v1"
|
||||
|
||||
// VariantSeed selects one variant of a family. The same family version and
|
||||
// the same seed always produce the same statement and reference answer.
|
||||
type VariantSeed uint64
|
||||
|
||||
// AssessmentParameterRange is the inclusive range of one generator
|
||||
// parameter.
|
||||
type AssessmentParameterRange struct {
|
||||
Min int32 `json:"min"`
|
||||
Max int32 `json:"max"`
|
||||
}
|
||||
|
||||
// AssessmentSeedGenerator describes how seeds become variants: a named
|
||||
// algorithm, the ranges of its parameters, and the statement template. The
|
||||
// algorithm is code that is registered in this package under a versioned
|
||||
// name, so an old family version keeps its algorithm after a newer one
|
||||
// exists.
|
||||
type AssessmentSeedGenerator struct {
|
||||
Algorithm string `json:"algorithm"`
|
||||
Parameters map[string]AssessmentParameterRange `json:"parameters"`
|
||||
// StatementTemplate is plain text with {{.name}} placeholders for the
|
||||
// parameters and the generated input data of the algorithm. Nothing else
|
||||
// of the text/template language is accepted; see compileStatementTemplate.
|
||||
StatementTemplate string `json:"statement_template"`
|
||||
}
|
||||
|
||||
func (generator AssessmentSeedGenerator) clone() AssessmentSeedGenerator {
|
||||
copied := generator
|
||||
copied.Parameters = maps.Clone(generator.Parameters)
|
||||
return copied
|
||||
}
|
||||
|
||||
// validate checks the algorithm, the parameter ranges against the bounds the
|
||||
// algorithm accepts, and the template. With probe set it also renders the
|
||||
// template at both ends of the ranges and at one seed, which an importer does
|
||||
// once; reading a stored row skips the probes, because the content hash
|
||||
// proves that the content is the one that passed them. It returns the
|
||||
// algorithm.
|
||||
func (generator AssessmentSeedGenerator) validate(location string, probe bool) (assessmentAlgorithm, error) {
|
||||
algorithm, ok := assessmentAlgorithms[generator.Algorithm]
|
||||
if !ok {
|
||||
return assessmentAlgorithm{}, invalidAssessmentFamily(location, "generator algorithm is unknown")
|
||||
}
|
||||
if len(generator.Parameters) != len(algorithm.parameters) {
|
||||
return assessmentAlgorithm{}, invalidAssessmentFamily(location, "generator parameters must be exactly the parameters of the algorithm")
|
||||
}
|
||||
lowest, highest := make(map[string]int32, len(algorithm.parameters)), make(map[string]int32, len(algorithm.parameters))
|
||||
for _, spec := range algorithm.parameters {
|
||||
parameterRange, ok := generator.Parameters[spec.name]
|
||||
if !ok {
|
||||
return assessmentAlgorithm{}, invalidAssessmentFamily(location, "generator parameters must be exactly the parameters of the algorithm")
|
||||
}
|
||||
if parameterRange.Min < spec.lowest || parameterRange.Max > spec.highest || parameterRange.Min > parameterRange.Max {
|
||||
return assessmentAlgorithm{}, invalidAssessmentFamily(location,
|
||||
fmt.Sprintf("generator parameter %s must be a range inside %d to %d", spec.name, spec.lowest, spec.highest))
|
||||
}
|
||||
lowest[spec.name], highest[spec.name] = parameterRange.Min, parameterRange.Max
|
||||
}
|
||||
statement, err := compileStatementTemplate(location, generator.StatementTemplate, algorithm)
|
||||
if err != nil {
|
||||
return assessmentAlgorithm{}, err
|
||||
}
|
||||
if !probe {
|
||||
return algorithm, nil
|
||||
}
|
||||
if _, err := generator.instantiate(algorithm, statement, lowest, 0); err != nil {
|
||||
return assessmentAlgorithm{}, fmt.Errorf("%s - probe generator at the lowest values: %w", location, err)
|
||||
}
|
||||
// The highest values give the largest inputs, and drawn values give the
|
||||
// usual ones; the size of an input varies with its numbers, so each is
|
||||
// rendered for several seeds.
|
||||
for seed := range VariantSeed(probeSeedCount) {
|
||||
for _, fixed := range []map[string]int32{highest, nil} {
|
||||
if _, err := generator.instantiate(algorithm, statement, fixed, seed); err != nil {
|
||||
return assessmentAlgorithm{}, fmt.Errorf("%s - probe generator with seed %d: %w", location, seed, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return algorithm, nil
|
||||
}
|
||||
|
||||
// instantiate builds one variant body. A nil fixed map draws every parameter
|
||||
// from its range with the seed; otherwise the fixed values are used.
|
||||
func (generator AssessmentSeedGenerator) instantiate(
|
||||
algorithm assessmentAlgorithm,
|
||||
statement statementTemplate,
|
||||
fixed map[string]int32,
|
||||
seed VariantSeed,
|
||||
) (variantBody, error) {
|
||||
random := newSeededRandom(generator.Algorithm, seed)
|
||||
values := make(map[string]int32, len(algorithm.parameters))
|
||||
// Parameters are drawn in the declared order, so a seed always meets the
|
||||
// same draws.
|
||||
for _, spec := range algorithm.parameters {
|
||||
parameterRange := generator.Parameters[spec.name]
|
||||
if fixed != nil {
|
||||
values[spec.name] = fixed[spec.name]
|
||||
continue
|
||||
}
|
||||
values[spec.name] = random.between(parameterRange.Min, parameterRange.Max)
|
||||
}
|
||||
data, answer := algorithm.generate(random, values)
|
||||
for name, value := range values {
|
||||
data[name] = strconv.Itoa(int(value))
|
||||
}
|
||||
rendered, err := statement.render(data)
|
||||
if err != nil {
|
||||
return variantBody{}, err
|
||||
}
|
||||
return variantBody{parameters: values, statement: rendered, answer: answer}, nil
|
||||
}
|
||||
|
||||
type variantBody struct {
|
||||
parameters map[string]int32
|
||||
statement string
|
||||
answer string
|
||||
}
|
||||
|
||||
// AssessmentVariant is one generated task of a family version. The rubric is
|
||||
// the family's rubric: no seed changes it.
|
||||
type AssessmentVariant struct {
|
||||
FamilyID AssessmentFamilyID
|
||||
FamilyKey AssessmentFamilyKey
|
||||
FamilyVersion int32
|
||||
Seed VariantSeed
|
||||
Parameters map[string]int32
|
||||
Statement string
|
||||
ReferenceAnswer string
|
||||
AnswerFormat string
|
||||
Rubric AssessmentRubric
|
||||
}
|
||||
|
||||
// NewVariant generates the variant of a seed. It is a pure function of the
|
||||
// family content and the seed.
|
||||
func (family AssessmentFamily) NewVariant(seed VariantSeed) (AssessmentVariant, error) {
|
||||
const location = "AssessmentFamily.NewVariant"
|
||||
if family.IsZero() {
|
||||
return AssessmentVariant{}, invalidAssessmentFamily(location, "family was not built by RestoreAssessmentFamily")
|
||||
}
|
||||
algorithm, ok := assessmentAlgorithms[family.core.Generator.Algorithm]
|
||||
if !ok {
|
||||
return AssessmentVariant{}, invalidAssessmentFamily(location, "generator algorithm is unknown")
|
||||
}
|
||||
statement, err := compileStatementTemplate(location, family.core.Generator.StatementTemplate, algorithm)
|
||||
if err != nil {
|
||||
return AssessmentVariant{}, err
|
||||
}
|
||||
body, err := family.core.Generator.instantiate(algorithm, statement, nil, seed)
|
||||
if err != nil {
|
||||
return AssessmentVariant{}, fmt.Errorf("%s - generate variant: %w", location, err)
|
||||
}
|
||||
return AssessmentVariant{
|
||||
FamilyID: family.id,
|
||||
FamilyKey: family.core.Key,
|
||||
FamilyVersion: family.core.Version,
|
||||
Seed: seed,
|
||||
Parameters: body.parameters,
|
||||
Statement: body.statement,
|
||||
ReferenceAnswer: body.answer,
|
||||
AnswerFormat: algorithm.answerFormat,
|
||||
Rubric: family.core.Rubric.clone(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// seededRandom is SplitMix64. It is written out here instead of taken from
|
||||
// math/rand so that the variants of a stored family stay reproducible across
|
||||
// Go releases.
|
||||
type seededRandom struct {
|
||||
state uint64
|
||||
}
|
||||
|
||||
func newSeededRandom(algorithm string, seed VariantSeed) *seededRandom {
|
||||
material := make([]byte, 0, len(variantSeedDomain)+len(algorithm)+10)
|
||||
material = append(material, variantSeedDomain...)
|
||||
material = append(material, 0)
|
||||
material = append(material, algorithm...)
|
||||
material = append(material, 0)
|
||||
material = binary.BigEndian.AppendUint64(material, uint64(seed))
|
||||
digest := sha256.Sum256(material)
|
||||
return &seededRandom{state: binary.BigEndian.Uint64(digest[:8])}
|
||||
}
|
||||
|
||||
func (random *seededRandom) next() uint64 {
|
||||
random.state += 0x9e3779b97f4a7c15
|
||||
value := random.state
|
||||
value = (value ^ (value >> 30)) * 0xbf58476d1ce4e5b9
|
||||
value = (value ^ (value >> 27)) * 0x94d049bb133111eb
|
||||
return value ^ (value >> 31)
|
||||
}
|
||||
|
||||
// below returns a value in [0, bound). The bias of the modulo is below
|
||||
// 2^-50 for the small bounds used here.
|
||||
func (random *seededRandom) below(bound int) int {
|
||||
return int(random.next() % uint64(bound)) //nolint:gosec // callers pass a positive bound that the parameter bounds keep small.
|
||||
}
|
||||
|
||||
func (random *seededRandom) between(lowest, highest int32) int32 {
|
||||
return lowest + int32(random.below(int(highest-lowest)+1)) //nolint:gosec // the draw is below highest-lowest+1, which fits int32.
|
||||
}
|
||||
|
||||
// assessmentParameterSpec names a generator parameter and the bounds that
|
||||
// every family range must lie in. The bounds keep statements small and the
|
||||
// reference solvers fast; they are not product thresholds.
|
||||
type assessmentParameterSpec struct {
|
||||
name string
|
||||
lowest, highest int32
|
||||
}
|
||||
|
||||
// assessmentAlgorithm is a registered seed algorithm. The registry is
|
||||
// append-only: a changed algorithm gets a new versioned name, because stored
|
||||
// family versions refer to the old name.
|
||||
type assessmentAlgorithm struct {
|
||||
answerFormat string
|
||||
// parameters in the order in which a seed draws them.
|
||||
parameters []assessmentParameterSpec
|
||||
// dataNames lists the generated input data that generate returns.
|
||||
dataNames []string
|
||||
// requiredNames lists the placeholders that a statement template must
|
||||
// contain, because the reference answer depends on them: without them
|
||||
// the candidate would not see the input.
|
||||
requiredNames []string
|
||||
// generate returns the input data for the statement template and the
|
||||
// reference answer.
|
||||
generate func(random *seededRandom, parameters map[string]int32) (data map[string]string, answer string)
|
||||
}
|
||||
|
||||
// probeSeedCount is the number of seeds that an importer renders at the
|
||||
// highest parameter values and at drawn values. A template whose statement is
|
||||
// close to maxStatementBytes must not pass because one lucky seed rendered
|
||||
// short.
|
||||
const probeSeedCount = 8
|
||||
|
||||
const (
|
||||
// maxStatementTemplateBytes bounds the template text.
|
||||
maxStatementTemplateBytes = 2000
|
||||
// maxStatementBytes bounds a rendered statement. The largest input of any
|
||||
// algorithm fits with the template text; a larger result means a
|
||||
// template or an algorithm that outgrew its bounds, and is refused.
|
||||
maxStatementBytes = 8 << 10
|
||||
)
|
||||
|
||||
// statementPart is a literal text, or a placeholder when field is set.
|
||||
type statementPart struct {
|
||||
literal string
|
||||
field string
|
||||
}
|
||||
|
||||
// statementTemplate is a statement template that passed the whitelist below.
|
||||
type statementTemplate []statementPart
|
||||
|
||||
// compileStatementTemplate accepts plain text with {{.name}} placeholders and
|
||||
// nothing else. The text/template parser reads it with no functions, and the
|
||||
// walk below rejects every node other than text and a single field action:
|
||||
// define, template, block, range, with, if, variables, pipelines, and
|
||||
// calls. A statement therefore cannot loop, recurse, or ask for a width, and
|
||||
// its size is bounded by the template and the data. The names must belong to
|
||||
// the algorithm, and the template must use every name that the reference
|
||||
// answer depends on.
|
||||
func compileStatementTemplate(location, text string, algorithm assessmentAlgorithm) (statementTemplate, error) {
|
||||
if len(text) > maxStatementTemplateBytes {
|
||||
return nil, invalidAssessmentFamily(location, fmt.Sprintf("statement template must be at most %d bytes", maxStatementTemplateBytes))
|
||||
}
|
||||
if err := checkAssessmentText(location, "statement template", text); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
trees, err := parse.Parse("statement", text, "{{", "}}")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: parse statement template: %w", ErrInvalidAssessmentFamily, err)
|
||||
}
|
||||
tree, ok := trees["statement"]
|
||||
if !ok || len(trees) != 1 || tree.Root == nil {
|
||||
return nil, invalidAssessmentFamily(location, "statement template must not define other templates")
|
||||
}
|
||||
parts, used, err := statementParts(location, tree, algorithm)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, name := range algorithm.requiredNames {
|
||||
if !used[name] {
|
||||
return nil, invalidAssessmentFamily(location, "statement template must contain the placeholder {{."+name+"}}")
|
||||
}
|
||||
}
|
||||
return parts, nil
|
||||
}
|
||||
|
||||
// placeholderName returns the name of an action that is exactly {{.name}}.
|
||||
func placeholderName(action *parse.ActionNode) (string, bool) {
|
||||
pipe := action.Pipe
|
||||
if pipe == nil || len(pipe.Decl) != 0 || pipe.IsAssign || len(pipe.Cmds) != 1 {
|
||||
return "", false
|
||||
}
|
||||
command := pipe.Cmds[0]
|
||||
if len(command.Args) != 1 {
|
||||
return "", false
|
||||
}
|
||||
field, ok := command.Args[0].(*parse.FieldNode)
|
||||
if !ok || len(field.Ident) != 1 {
|
||||
return "", false
|
||||
}
|
||||
return field.Ident[0], true
|
||||
}
|
||||
|
||||
// render fills the placeholders and refuses a statement above the size
|
||||
// bound.
|
||||
func (statement statementTemplate) render(data map[string]string) (string, error) {
|
||||
var rendered []byte
|
||||
for _, part := range statement {
|
||||
text := part.literal
|
||||
if part.field != "" {
|
||||
text = data[part.field]
|
||||
}
|
||||
if len(rendered)+len(text) > maxStatementBytes {
|
||||
return "", fmt.Errorf("%w: rendered statement exceeds %d bytes", ErrInvalidAssessmentFamily, maxStatementBytes)
|
||||
}
|
||||
rendered = append(rendered, text...)
|
||||
}
|
||||
return string(rendered), nil
|
||||
}
|
||||
|
||||
// statementParts walks the parsed template and returns its parts and the set
|
||||
// of placeholders it uses.
|
||||
func statementParts(location string, tree *parse.Tree, algorithm assessmentAlgorithm) (statementTemplate, map[string]bool, error) {
|
||||
allowed := make(map[string]bool)
|
||||
for _, spec := range algorithm.parameters {
|
||||
allowed[spec.name] = true
|
||||
}
|
||||
for _, name := range algorithm.dataNames {
|
||||
allowed[name] = true
|
||||
}
|
||||
used := make(map[string]bool)
|
||||
var parts statementTemplate
|
||||
for _, node := range tree.Root.Nodes {
|
||||
switch typed := node.(type) {
|
||||
case *parse.TextNode:
|
||||
parts = append(parts, statementPart{literal: string(typed.Text)})
|
||||
case *parse.ActionNode:
|
||||
field, ok := placeholderName(typed)
|
||||
if !ok {
|
||||
return nil, nil, invalidAssessmentFamily(location, "statement template allows only {{.name}} placeholders")
|
||||
}
|
||||
if !allowed[field] {
|
||||
return nil, nil, invalidAssessmentFamily(location, "statement template names an unknown placeholder")
|
||||
}
|
||||
used[field] = true
|
||||
parts = append(parts, statementPart{field: field})
|
||||
default:
|
||||
return nil, nil, invalidAssessmentFamily(location, "statement template allows only text and {{.name}} placeholders")
|
||||
}
|
||||
}
|
||||
return parts, used, nil
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// maxRejectionTime is a generous bound for refusing a hostile template. The
|
||||
// refusal reads at most a few kilobytes and never runs the template, so it
|
||||
// takes microseconds; a template that was executed would not finish.
|
||||
const maxRejectionTime = time.Second
|
||||
|
||||
func TestStatementTemplateAllowsOnlyPlaceholders(t *testing.T) {
|
||||
algorithm := assessmentAlgorithms["lru_hits.v1"]
|
||||
const complete = "{{.capacity}} {{.sequence}}"
|
||||
tests := map[string]string{
|
||||
"define": complete + `{{define "x"}}y{{end}}`,
|
||||
"template call": complete + `{{template "x"}}`,
|
||||
"block": complete + `{{block "x" .}}y{{end}}`,
|
||||
"range": complete + `{{range .}}x{{end}}`,
|
||||
"with": complete + `{{with .capacity}}x{{end}}`,
|
||||
"if": complete + `{{if .capacity}}x{{end}}`,
|
||||
"variable": complete + `{{$x := .capacity}}`,
|
||||
"printf call": complete + `{{printf "%d" 1}}`,
|
||||
"pipeline": complete + `{{.capacity | len}}`,
|
||||
"nested field": complete + `{{.capacity.x}}`,
|
||||
"dot": complete + `{{.}}`,
|
||||
"string literal": complete + `{{"x"}}`,
|
||||
"unknown placeholder": complete + `{{.nothing}}`,
|
||||
"placeholder of another": complete + `{{.timestamps}}`,
|
||||
"unclosed action": complete + `{{.keys`,
|
||||
"template above size cap": complete + strings.Repeat("x", maxStatementTemplateBytes),
|
||||
}
|
||||
for name, text := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if _, err := compileStatementTemplate("test", text, algorithm); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("compileStatementTemplate() error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
if _, err := compileStatementTemplate("test", "Capacity {{.capacity}}; reads {{.sequence}}; keys 1..{{.keys}}.", algorithm); err != nil {
|
||||
t.Fatalf("compileStatementTemplate(plain placeholders) error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatementTemplateBombsAreRefusedFast(t *testing.T) {
|
||||
algorithm := assessmentAlgorithms["lru_hits.v1"]
|
||||
// Each template calls the one below it twice: executed, the last of 20
|
||||
// levels would run about a million bodies.
|
||||
var nested strings.Builder
|
||||
nested.WriteString(`{{define "t0"}}x{{end}}`)
|
||||
for level := 1; level < 20; level++ {
|
||||
fmt.Fprintf(&nested, `{{define "t%d"}}{{template "t%d"}}{{template "t%d"}}{{end}}`, level, level-1, level-1)
|
||||
}
|
||||
nested.WriteString(`{{template "t19"}}`)
|
||||
// A width of a hundred million spaces from a few bytes of template.
|
||||
widthBomb := `{{.capacity}} {{.sequence}}{{printf "%99999999d" 1}}`
|
||||
for name, text := range map[string]string{
|
||||
"nested define bomb": nested.String(),
|
||||
"printf width bomb": widthBomb,
|
||||
"small nested define": `{{.capacity}} {{.sequence}}{{define "a"}}{{template "a"}}{{end}}{{template "a"}}`,
|
||||
"range over a number": `{{.capacity}} {{.sequence}}{{range 100000000}}x{{end}}`,
|
||||
"recursive block call": `{{.capacity}} {{.sequence}}{{block "b" .}}{{template "b" .}}{{end}}`,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
started := time.Now()
|
||||
_, err := compileStatementTemplate("test", text, algorithm)
|
||||
if !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("compileStatementTemplate() error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed > maxRejectionTime {
|
||||
t.Fatalf("compileStatementTemplate() took %s, want a refusal within %s", elapsed, maxRejectionTime)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatementTemplateMustShowTheInput(t *testing.T) {
|
||||
for name, algorithm := range assessmentAlgorithms {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
var all strings.Builder
|
||||
for _, required := range algorithm.requiredNames {
|
||||
all.WriteString("{{." + required + "}} ")
|
||||
}
|
||||
if _, err := compileStatementTemplate("test", strings.TrimSpace(all.String()), algorithm); err != nil {
|
||||
t.Fatalf("compileStatementTemplate(all required names) error = %v", err)
|
||||
}
|
||||
for index, missing := range algorithm.requiredNames {
|
||||
var partial strings.Builder
|
||||
for other, required := range algorithm.requiredNames {
|
||||
if other != index {
|
||||
partial.WriteString("{{." + required + "}} ")
|
||||
}
|
||||
}
|
||||
partial.WriteString("Compute the answer.")
|
||||
if _, err := compileStatementTemplate("test", partial.String(), algorithm); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("compileStatementTemplate(without %s) error = %v, want ErrInvalidAssessmentFamily", missing, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatementRenderIsBounded(t *testing.T) {
|
||||
statement := statementTemplate{{literal: strings.Repeat("x", maxStatementBytes)}, {field: "name"}}
|
||||
if _, err := statement.render(map[string]string{"name": "y"}); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("render(above the bound) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
if got, err := (statementTemplate{{literal: "a"}, {field: "name"}}).render(map[string]string{"name": "b"}); err != nil || got != "ab" {
|
||||
t.Fatalf("render() = %q, %v, want %q", got, err, "ab")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvisibleFormatCharactersAreRefused(t *testing.T) {
|
||||
for name, mutate := range map[string]func(*NewAssessmentFamilyDraftInput){
|
||||
"bidi override in the title": func(input *NewAssessmentFamilyDraftInput) { input.Title = "Cache \u202Etest" },
|
||||
"zero width space in the title": func(input *NewAssessmentFamilyDraftInput) { input.Title = "Cache\u200Btest" },
|
||||
"bidi override in the template": func(input *NewAssessmentFamilyDraftInput) { input.Generator.StatementTemplate += "\u202E" },
|
||||
"format character in the rubric": func(input *NewAssessmentFamilyDraftInput) { input.Rubric.Principle = "Compare\u2066 it." },
|
||||
"line separator in the title": func(input *NewAssessmentFamilyDraftInput) { input.Title = "Cache\u2028test" },
|
||||
"paragraph separator in the rubric": func(input *NewAssessmentFamilyDraftInput) {
|
||||
input.Rubric.Criteria[0].Description = "Matches\u2029the answer."
|
||||
},
|
||||
"line separator in the template": func(input *NewAssessmentFamilyDraftInput) { input.Generator.StatementTemplate += "\u2028" },
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
input := testAssessmentInput()
|
||||
mutate(&input)
|
||||
if _, err := NewAssessmentFamilyDraft(input); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// goldenVariant is one fixed seed of one algorithm with its exact output.
|
||||
// The statements and answers are the contract that stored families depend
|
||||
// on: a change of an algorithm that moves any of them must be a new
|
||||
// versioned algorithm, not an edit.
|
||||
type goldenVariant struct {
|
||||
algorithm string
|
||||
parameters map[string]AssessmentParameterRange
|
||||
template string
|
||||
seed VariantSeed
|
||||
statement string
|
||||
answer string
|
||||
}
|
||||
|
||||
func TestGoldenVariantsOfEveryAlgorithm(t *testing.T) {
|
||||
golden := []goldenVariant{
|
||||
{
|
||||
algorithm: "rate_limit_window.v1",
|
||||
parameters: map[string]AssessmentParameterRange{"requests": {Min: 8, Max: 8}, "window": {Min: 4, Max: 4}, "limit": {Min: 2, Max: 2}, "max_gap": {Min: 0, Max: 3}},
|
||||
template: "n={{.requests}} w={{.window}} l={{.limit}} t={{.timestamps}}",
|
||||
seed: 12345,
|
||||
statement: "n=8 w=4 l=2 t=0 0 1 2 2 3 4 6",
|
||||
answer: "4",
|
||||
},
|
||||
{
|
||||
algorithm: "dedup_window.v1",
|
||||
parameters: map[string]AssessmentParameterRange{"events": {Min: 8, Max: 8}, "keys": {Min: 3, Max: 3}, "ttl": {Min: 5, Max: 5}, "max_gap": {Min: 1, Max: 3}},
|
||||
template: "n={{.events}} k={{.keys}} ttl={{.ttl}} s={{.stream}}",
|
||||
seed: 12345,
|
||||
statement: "n=8 k=3 ttl=5 s=C@2 A@4 A@6 C@6 C@8 C@9 A@12 A@12",
|
||||
answer: "4",
|
||||
},
|
||||
{
|
||||
algorithm: "lru_hits.v1",
|
||||
parameters: map[string]AssessmentParameterRange{"accesses": {Min: 10, Max: 10}, "keys": {Min: 4, Max: 4}, "capacity": {Min: 2, Max: 2}},
|
||||
template: "n={{.accesses}} k={{.keys}} c={{.capacity}} s={{.sequence}}",
|
||||
seed: 12345,
|
||||
statement: "n=10 k=4 c=2 s=4 1 1 1 4 3 4 2 4 2",
|
||||
answer: "6",
|
||||
},
|
||||
{
|
||||
algorithm: "dependency_order.v1",
|
||||
parameters: map[string]AssessmentParameterRange{"tasks": {Min: 6, Max: 6}, "links": {Min: 5, Max: 5}},
|
||||
template: "n={{.tasks}} l={{.links}} d={{.dependencies}}",
|
||||
seed: 12345,
|
||||
statement: "n=6 l=5 d=3->4 1->3 2->5 2->3",
|
||||
answer: "1 2 3 4 5 6",
|
||||
},
|
||||
}
|
||||
for _, want := range golden {
|
||||
t.Run(want.algorithm, func(t *testing.T) {
|
||||
input := testAssessmentInput()
|
||||
input.Generator = AssessmentSeedGenerator{Algorithm: want.algorithm, Parameters: want.parameters, StatementTemplate: want.template}
|
||||
input.AnswerKey.AnswerFormat = assessmentAlgorithms[want.algorithm].answerFormat
|
||||
variant, err := restoreAssessment(t, input).NewVariant(want.seed)
|
||||
if err != nil {
|
||||
t.Fatalf("NewVariant() error = %v", err)
|
||||
}
|
||||
if variant.Statement != want.statement || variant.ReferenceAnswer != want.answer {
|
||||
t.Fatalf("seed %d of %s:\nstatement %q\nanswer %q\nwant\nstatement %q\nanswer %q",
|
||||
want.seed, want.algorithm, variant.Statement, variant.ReferenceAnswer, want.statement, want.answer)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestContentHashOfSchemeOneIsPinned(t *testing.T) {
|
||||
draft, err := NewAssessmentFamilyDraft(testAssessmentInput())
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentFamilyDraft() error = %v", err)
|
||||
}
|
||||
const want = "398d109255623c6bdadfa10974b523ca2f661913061746f0862ffaf1bca5a9d3"
|
||||
hash := draft.ContentHash()
|
||||
if got := fmt.Sprintf("%x", hash[:]); got != want {
|
||||
t.Fatalf("content hash = %s, want %s: a changed canonical layout of scheme 1 needs a new scheme, not an edit", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A template close to the size bound must be judged on the largest inputs
|
||||
// and on several seeds: here the highest parameter values render within the
|
||||
// bound for the shortest seed and beyond it for another, and the importer
|
||||
// refuses the template.
|
||||
func TestImportProbesSeveralSeedsAtTheLargestInputs(t *testing.T) {
|
||||
const algorithmName = "dedup_window.v1"
|
||||
algorithm := assessmentAlgorithms[algorithmName]
|
||||
parameters := map[string]AssessmentParameterRange{}
|
||||
highest := map[string]int32{}
|
||||
for _, spec := range algorithm.parameters {
|
||||
parameters[spec.name] = AssessmentParameterRange{Min: spec.lowest, Max: spec.highest}
|
||||
highest[spec.name] = spec.highest
|
||||
}
|
||||
generator := AssessmentSeedGenerator{Algorithm: algorithmName, Parameters: parameters}
|
||||
|
||||
// The stream placeholder twice, the ttl placeholder once, and a literal
|
||||
// that is sized below so that the shortest probe seed renders exactly at
|
||||
// the bound.
|
||||
body := "{{.stream}} {{.stream}} {{.ttl}}"
|
||||
statement, err := compileStatementTemplate("test", body, algorithm)
|
||||
if err != nil {
|
||||
t.Fatalf("compileStatementTemplate() error = %v", err)
|
||||
}
|
||||
shortest, longest := maxStatementBytes*2, 0
|
||||
for seed := range VariantSeed(probeSeedCount) {
|
||||
rendered, err := generator.instantiate(algorithm, statement, highest, seed)
|
||||
if err != nil {
|
||||
t.Fatalf("instantiate(seed %d) error = %v", seed, err)
|
||||
}
|
||||
shortest, longest = min(shortest, len(rendered.statement)), max(longest, len(rendered.statement))
|
||||
}
|
||||
if shortest == longest {
|
||||
t.Skip("every probe seed renders the same size, so the boundary cannot be placed between them")
|
||||
}
|
||||
padding := maxStatementBytes - shortest
|
||||
if padding < 0 || padding+len(body) > maxStatementTemplateBytes {
|
||||
t.Fatalf("padding %d does not fit the template bound: the test needs another shape", padding)
|
||||
}
|
||||
generator.StatementTemplate = strings.Repeat("x", padding) + body
|
||||
|
||||
input := testAssessmentInput()
|
||||
input.Generator = generator
|
||||
input.AnswerKey.AnswerFormat = algorithm.answerFormat
|
||||
if _, err := NewAssessmentFamilyDraft(input); !errors.Is(err, ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("NewAssessmentFamilyDraft(template at the bound for one seed only) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
// Rendered with the shortest probe seed alone it would have passed.
|
||||
for seed := range VariantSeed(probeSeedCount) {
|
||||
compiled, err := compileStatementTemplate("test", generator.StatementTemplate, algorithm)
|
||||
if err != nil {
|
||||
t.Fatalf("compileStatementTemplate(padded) error = %v", err)
|
||||
}
|
||||
if rendered, err := generator.instantiate(algorithm, compiled, highest, seed); err == nil && len(rendered.statement) == maxStatementBytes {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatal("no probe seed renders the padded template exactly at the bound: the boundary test is not exercising the edge")
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrAssessmentFamilyNotFound reports that no family version matches.
|
||||
ErrAssessmentFamilyNotFound = errors.New("assessment family not found")
|
||||
|
||||
// ErrAssessmentFamilyConflict reports that the family key already has a
|
||||
// version with that number, or the ID is taken. Nothing was stored and
|
||||
// the surrounding transaction stays usable.
|
||||
ErrAssessmentFamilyConflict = errors.New("assessment family version already exists")
|
||||
|
||||
// ErrAssessmentFamilyImmutable reports an attempt to change the content
|
||||
// of a stored version or to remove one. The database refuses every such
|
||||
// UPDATE, DELETE, and TRUNCATE; import a new version instead.
|
||||
ErrAssessmentFamilyImmutable = errors.New("assessment family version is immutable")
|
||||
|
||||
// ErrAssessmentFamilyLifecycle reports a lifecycle step that is not
|
||||
// allowed: not draft to published to retired, or from a state that
|
||||
// changed in the meantime.
|
||||
ErrAssessmentFamilyLifecycle = errors.New("assessment family lifecycle step is not allowed")
|
||||
|
||||
// ErrAssessmentFamilyNotPublishable reports a publication that the
|
||||
// database refuses because the version has no approved review.
|
||||
ErrAssessmentFamilyNotPublishable = errors.New("assessment family has no approved review")
|
||||
|
||||
// ErrAssessmentCoverageInsufficient reports an opening that the database
|
||||
// refuses because the category has fewer published families than
|
||||
// required.
|
||||
ErrAssessmentCoverageInsufficient = errors.New("assessment category has insufficient coverage")
|
||||
|
||||
// ErrAssessmentGradingPolicyNotFound reports an opening that references
|
||||
// a policy version that is not stored.
|
||||
ErrAssessmentGradingPolicyNotFound = errors.New("assessment grading policy version not found")
|
||||
|
||||
// ErrAssessmentLockOutsideTransaction reports a LockCategory call on the
|
||||
// standalone repository: an advisory lock that is scoped to a
|
||||
// transaction would be released at once.
|
||||
ErrAssessmentLockOutsideTransaction = errors.New("assessment category lock needs a transaction")
|
||||
|
||||
// ErrAssessmentCategoryNotOpen reports that the category has no opening.
|
||||
ErrAssessmentCategoryNotOpen = errors.New("assessment category is not open")
|
||||
)
|
||||
|
||||
// MaxAssessmentFamilyPageSize is the largest page that ListFamilies returns.
|
||||
const MaxAssessmentFamilyPageSize = 200
|
||||
|
||||
// AssessmentFamilyCursor is the position after which ListFamilies continues:
|
||||
// the last key and version of the previous page. The zero value starts at the
|
||||
// beginning.
|
||||
type AssessmentFamilyCursor struct {
|
||||
Key domain.AssessmentFamilyKey
|
||||
Version int32
|
||||
}
|
||||
|
||||
// AssessmentBankRepositories exposes the assessment bank. UnitOfWork binds it
|
||||
// to one transaction; an adapter may also provide it outside a transaction,
|
||||
// where every call is its own statement. A returned family passed
|
||||
// domain.RestoreAssessmentFamily, including the content hash check. The
|
||||
// repository has no method that edits the content of a stored version.
|
||||
type AssessmentBankRepositories interface {
|
||||
AssessmentBank() AssessmentBankRepository
|
||||
}
|
||||
|
||||
// AssessmentBankRepository stores immutable family versions and category
|
||||
// openings.
|
||||
type AssessmentBankRepository interface {
|
||||
// CreateFamily stores a draft and returns the stored version. It returns
|
||||
// an error wrapping ErrAssessmentFamilyConflict for a taken ID or
|
||||
// (key, version), without aborting a surrounding transaction.
|
||||
CreateFamily(ctx context.Context, draft domain.AssessmentFamilyDraft) (domain.AssessmentFamily, error)
|
||||
|
||||
// GetFamilyVersion returns ErrAssessmentFamilyNotFound for an unknown
|
||||
// version.
|
||||
GetFamilyVersion(ctx context.Context, key domain.AssessmentFamilyKey, version int32) (domain.AssessmentFamily, error)
|
||||
|
||||
// GetLatestFamily returns the version with the highest number of the
|
||||
// key, or ErrAssessmentFamilyNotFound.
|
||||
GetLatestFamily(ctx context.Context, key domain.AssessmentFamilyKey) (domain.AssessmentFamily, error)
|
||||
|
||||
// ListFamilies returns up to limit versions of the category after the
|
||||
// cursor, ordered by key and version. limit must be between 1 and
|
||||
// MaxAssessmentFamilyPageSize.
|
||||
ListFamilies(ctx context.Context, category domain.AssessmentCategory, after AssessmentFamilyCursor, limit int32) ([]domain.AssessmentFamily, error)
|
||||
|
||||
// GetPublishedFamily returns the one published version of the key, or
|
||||
// ErrAssessmentFamilyNotFound when none is published.
|
||||
GetPublishedFamily(ctx context.Context, key domain.AssessmentFamilyKey) (domain.AssessmentFamily, error)
|
||||
|
||||
// LockCategory takes a transaction-scoped advisory lock of the category.
|
||||
// Openings, publications, and retirements of one category take it first,
|
||||
// so the coverage that the database counts cannot miss a concurrent
|
||||
// change. It is released when the transaction ends, so it works only
|
||||
// inside a transaction: the repository of a UnitOfWork takes it, and the
|
||||
// standalone repository returns ErrAssessmentLockOutsideTransaction.
|
||||
LockCategory(ctx context.Context, category domain.AssessmentCategory) error
|
||||
|
||||
// CountPublishedFamilies counts the families of the category that have a
|
||||
// published version.
|
||||
CountPublishedFamilies(ctx context.Context, category domain.AssessmentCategory) (int32, error)
|
||||
|
||||
// MarkPublished moves a draft to published and records the operator. It
|
||||
// returns an error wrapping
|
||||
// ErrAssessmentFamilyLifecycle when the version is not a draft and
|
||||
// ErrAssessmentFamilyNotPublishable when the database refuses it for
|
||||
// lack of an approved review.
|
||||
MarkPublished(ctx context.Context, id domain.AssessmentFamilyID, by domain.AssessmentOperator) (domain.AssessmentFamily, error)
|
||||
|
||||
// MarkRetired moves a published version to retired and records the
|
||||
// operator, or returns an error
|
||||
// wrapping ErrAssessmentFamilyLifecycle.
|
||||
MarkRetired(ctx context.Context, id domain.AssessmentFamilyID, by domain.AssessmentOperator) (domain.AssessmentFamily, error)
|
||||
|
||||
// CreateCategoryOpening stores an opening and returns it with the
|
||||
// coverage the database counted. It returns
|
||||
// ErrAssessmentCoverageInsufficient or ErrAssessmentGradingPolicyNotFound
|
||||
// when the database refuses the row. The database derives the required
|
||||
// coverage from the policy document and counts the published families;
|
||||
// the draft's own numbers are not stored.
|
||||
CreateCategoryOpening(ctx context.Context, draft domain.AssessmentCategoryOpeningDraft) (domain.AssessmentCategoryOpening, error)
|
||||
|
||||
// DatabaseTime returns the database clock. It stamps the effective time
|
||||
// of a policy version, so the version in force now is judged against it
|
||||
// and not against the application clock.
|
||||
DatabaseTime(ctx context.Context) (time.Time, error)
|
||||
|
||||
// GetCurrentCategoryOpening returns the newest opening of the category,
|
||||
// or ErrAssessmentCategoryNotOpen.
|
||||
GetCurrentCategoryOpening(ctx context.Context, category domain.AssessmentCategory) (domain.AssessmentCategoryOpening, error)
|
||||
}
|
||||
@@ -51,6 +51,7 @@ type UnitOfWork interface {
|
||||
IdentityRepositories
|
||||
ConsentRepositories
|
||||
OrganizationRepositories
|
||||
AssessmentBankRepositories
|
||||
Policies() PolicyRepository
|
||||
Deliveries() DeliveryRepository
|
||||
MailRequests() MailRequestRepository
|
||||
|
||||
@@ -0,0 +1,476 @@
|
||||
// Package assessment loads the assessment bank: immutable family versions
|
||||
// from reviewed bundles, their publication, and the opening of a category.
|
||||
//
|
||||
// The package builds the storage and the loading rules. It does not author
|
||||
// or review content: a bundle that nobody reviewed is imported as a draft
|
||||
// and keeps its category closed.
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// Bank imports family versions and decides publication and category
|
||||
// availability. It holds no state; the same instance serves concurrent
|
||||
// callers. Each method runs in one transaction and does not retry a
|
||||
// transaction conflict: the caller may repeat the whole call, and every
|
||||
// method is safe to repeat.
|
||||
//
|
||||
// Publishing, retiring, and opening take an advisory lock of the category
|
||||
// first, so they run one after another per category and the coverage that
|
||||
// the database counts cannot miss a concurrent change.
|
||||
type Bank struct {
|
||||
transactor outbound.Transactor
|
||||
}
|
||||
|
||||
// NewBank panics on a nil transactor: a wiring mistake should fail at
|
||||
// construction, not at the first import. Which grading policy version is in
|
||||
// force is judged against the database clock, which stamps the effective time
|
||||
// of a policy version, and not against an application clock.
|
||||
func NewBank(transactor outbound.Transactor) *Bank {
|
||||
if transactor == nil {
|
||||
panic("assessment.NewBank - transactor must not be nil")
|
||||
}
|
||||
return &Bank{transactor: transactor}
|
||||
}
|
||||
|
||||
// ImportResult lists what ImportBundle did. A version that was already
|
||||
// stored with identical content is Unchanged.
|
||||
type ImportResult struct {
|
||||
Created []domain.AssessmentFamily
|
||||
Unchanged []domain.AssessmentFamily
|
||||
}
|
||||
|
||||
// ImportBundle stores every family version of the bundle as a draft, in one
|
||||
// transaction: either all versions are stored or none. A version must be the
|
||||
// next one of its family, keep the family's category, and, when the number
|
||||
// is already stored, have identical content; a stored version is never
|
||||
// edited. Importing the same bundle again, also at the same time from
|
||||
// another transaction, changes nothing and reports the versions as
|
||||
// unchanged.
|
||||
//
|
||||
// It does not publish: a version becomes visible to the bank's coverage only
|
||||
// through PublishFamily. The reviewer in a bundle is a declared value, not
|
||||
// an authenticated identity, until reviewer accounts exist. 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. Refusals are *domain.AssessmentRefusalError
|
||||
// with RefusalVersionConflict, RefusalVersionGap, or RefusalCategoryChanged;
|
||||
// an invalid bundle wraps domain.ErrInvalidAssessmentFamily.
|
||||
func (bank *Bank) ImportBundle(ctx context.Context, bundle Bundle) (ImportResult, error) {
|
||||
drafts, err := bundle.Drafts()
|
||||
if err != nil {
|
||||
return ImportResult{}, fmt.Errorf("Bank.ImportBundle - validate bundle: %w", err)
|
||||
}
|
||||
var result ImportResult
|
||||
err = bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
result = ImportResult{}
|
||||
repository := unit.AssessmentBank()
|
||||
for _, draft := range drafts {
|
||||
family, created, err := importDraft(ctx, repository, draft)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if created {
|
||||
result.Created = append(result.Created, family)
|
||||
} else {
|
||||
result.Unchanged = append(result.Unchanged, family)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return ImportResult{}, fmt.Errorf("Bank.ImportBundle - import in transaction: %w", err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func importDraft(ctx context.Context, repository outbound.AssessmentBankRepository, draft domain.AssessmentFamilyDraft) (domain.AssessmentFamily, bool, error) {
|
||||
core := draft.Core()
|
||||
stored, found, err := readSameVersion(ctx, repository, draft)
|
||||
if err != nil || found {
|
||||
return stored, false, err
|
||||
}
|
||||
if err := checkNextVersion(ctx, repository, core); err != nil {
|
||||
return domain.AssessmentFamily{}, false, err
|
||||
}
|
||||
family, err := repository.CreateFamily(ctx, draft)
|
||||
if errors.Is(err, outbound.ErrAssessmentFamilyConflict) {
|
||||
// A concurrent import stored the version after the read above. The
|
||||
// insert did not abort the transaction, so read the winner and accept
|
||||
// it when its content is the same.
|
||||
stored, found, readErr := readSameVersion(ctx, repository, draft)
|
||||
if readErr != nil {
|
||||
return domain.AssessmentFamily{}, false, readErr
|
||||
}
|
||||
if found {
|
||||
return stored, false, nil
|
||||
}
|
||||
return domain.AssessmentFamily{}, false, fmt.Errorf("importDraft - store version: %w", err)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, false, fmt.Errorf("importDraft - store version: %w", err)
|
||||
}
|
||||
return family, true, nil
|
||||
}
|
||||
|
||||
// readSameVersion returns the stored version with the draft's key and number
|
||||
// when it exists and has the draft's content, and a refusal when its content
|
||||
// differs.
|
||||
func readSameVersion(ctx context.Context, repository outbound.AssessmentBankRepository, draft domain.AssessmentFamilyDraft) (domain.AssessmentFamily, bool, error) {
|
||||
core := draft.Core()
|
||||
stored, err := repository.GetFamilyVersion(ctx, core.Key, core.Version)
|
||||
if errors.Is(err, outbound.ErrAssessmentFamilyNotFound) {
|
||||
return domain.AssessmentFamily{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, false, fmt.Errorf("readSameVersion - read stored version: %w", err)
|
||||
}
|
||||
if stored.ContentHash() != draft.ContentHash() {
|
||||
return domain.AssessmentFamily{}, false, domain.NewAssessmentRefusal(domain.RefusalVersionConflict,
|
||||
fmt.Sprintf("family %s version %d is stored with different content; import a new version instead", core.Key, core.Version))
|
||||
}
|
||||
return stored, true, nil
|
||||
}
|
||||
|
||||
// checkNextVersion requires version 1 for a new family and the successor of
|
||||
// the latest version, in the same category, for an existing one.
|
||||
func checkNextVersion(ctx context.Context, repository outbound.AssessmentBankRepository, core domain.AssessmentFamilyCore) error {
|
||||
latest, err := repository.GetLatestFamily(ctx, core.Key)
|
||||
if errors.Is(err, outbound.ErrAssessmentFamilyNotFound) {
|
||||
if core.Version != 1 {
|
||||
return domain.NewAssessmentRefusal(domain.RefusalVersionGap,
|
||||
fmt.Sprintf("family %s has no stored version, so version %d cannot be imported; start at version 1", core.Key, core.Version))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("checkNextVersion - read latest version: %w", err)
|
||||
}
|
||||
if core.Version != latest.Version()+1 {
|
||||
return domain.NewAssessmentRefusal(domain.RefusalVersionGap,
|
||||
fmt.Sprintf("family %s is at version %d, so version %d cannot be imported; the next version is %d", core.Key, latest.Version(), core.Version, latest.Version()+1))
|
||||
}
|
||||
if core.Category != latest.Category() {
|
||||
return domain.NewAssessmentRefusal(domain.RefusalCategoryChanged,
|
||||
fmt.Sprintf("family %s belongs to category %s and cannot move to %s", core.Key, latest.Category(), core.Category))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// lockedFamily reads a version, takes the advisory lock of its category, and
|
||||
// reads the version again, so that its state is the one that no other
|
||||
// publication, retirement, or opening of the category can change until the
|
||||
// transaction ends.
|
||||
func lockedFamily(ctx context.Context, repository outbound.AssessmentBankRepository, key domain.AssessmentFamilyKey, version int32) (domain.AssessmentFamily, error) {
|
||||
family, err := repository.GetFamilyVersion(ctx, key, version)
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("read version: %w", err)
|
||||
}
|
||||
if err := repository.LockCategory(ctx, family.Category()); err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("lock category: %w", err)
|
||||
}
|
||||
family, err = repository.GetFamilyVersion(ctx, key, version)
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("reread version: %w", err)
|
||||
}
|
||||
return family, nil
|
||||
}
|
||||
|
||||
// PublishFamily publishes a draft version as the operator's decision. The
|
||||
// operator is a declared value of the caller, recorded with the publication.
|
||||
// A family has at most one published version: publishing version N retires
|
||||
// the published older version of the same key in the same transaction, and
|
||||
// any newer version of the key, in any state, refuses it.
|
||||
//
|
||||
// It refuses, with a *domain.AssessmentRefusalError that names the reason, a
|
||||
// version without a reviewer (RefusalReviewerMissing), with a review that is
|
||||
// not approved (RefusalReviewNotApproved), that is not a draft
|
||||
// (RefusalNotDraft), or whose family has a newer version (RefusalNewerVersionPublished). A pending draft is never approved in place:
|
||||
// import a new version that carries the review.
|
||||
func (bank *Bank) PublishFamily(ctx context.Context, key domain.AssessmentFamilyKey, version int32, by domain.AssessmentOperator) (domain.AssessmentFamily, error) {
|
||||
if _, err := domain.ParseAssessmentOperator(string(by)); err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("Bank.PublishFamily - validate operator: %w", err)
|
||||
}
|
||||
var published domain.AssessmentFamily
|
||||
err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
repository := unit.AssessmentBank()
|
||||
family, err := lockedFamily(ctx, repository, key, version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := family.CheckPublishable(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkNoNewerVersion(ctx, repository, family); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := retireOlderPublished(ctx, repository, family, by); err != nil {
|
||||
return err
|
||||
}
|
||||
published, err = repository.MarkPublished(ctx, family.ID(), by)
|
||||
if err != nil {
|
||||
return storageRefusal(fmt.Errorf("mark published: %w", err), domain.RefusalNotDraft)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("Bank.PublishFamily - publish %s version %d: %w", key, version, err)
|
||||
}
|
||||
return published, nil
|
||||
}
|
||||
|
||||
// checkNoNewerVersion refuses to publish a version while a newer version of
|
||||
// the family exists in any state, even a draft or a retired one: publishing
|
||||
// the older one would put superseded content back in the bank. To publish
|
||||
// earlier content again, import it as a new version.
|
||||
func checkNoNewerVersion(ctx context.Context, repository outbound.AssessmentBankRepository, family domain.AssessmentFamily) error {
|
||||
latest, err := repository.GetLatestFamily(ctx, family.Key())
|
||||
if err != nil {
|
||||
return fmt.Errorf("read latest version: %w", err)
|
||||
}
|
||||
if latest.Version() > family.Version() {
|
||||
return domain.NewAssessmentRefusal(domain.RefusalNewerVersionPublished,
|
||||
fmt.Sprintf("version %d of family %s exists, so version %d cannot be published; import the content as a new version", latest.Version(), family.Key(), family.Version()))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// retireOlderPublished retires the published version of the family that
|
||||
// precedes the one being published. Having passed checkNoNewerVersion, the
|
||||
// published version, if any, is older.
|
||||
func retireOlderPublished(ctx context.Context, repository outbound.AssessmentBankRepository, family domain.AssessmentFamily, by domain.AssessmentOperator) error {
|
||||
active, err := repository.GetPublishedFamily(ctx, family.Key())
|
||||
if errors.Is(err, outbound.ErrAssessmentFamilyNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("read published version: %w", err)
|
||||
}
|
||||
if _, err := repository.MarkRetired(ctx, active.ID(), by); err != nil {
|
||||
return storageRefusal(fmt.Errorf("retire older version: %w", err), domain.RefusalNotPublished)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RetireFamily withdraws a published version as the operator's decision. It
|
||||
// refuses a version that is not published with RefusalNotPublished.
|
||||
func (bank *Bank) RetireFamily(ctx context.Context, key domain.AssessmentFamilyKey, version int32, by domain.AssessmentOperator) (domain.AssessmentFamily, error) {
|
||||
if _, err := domain.ParseAssessmentOperator(string(by)); err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("Bank.RetireFamily - validate operator: %w", err)
|
||||
}
|
||||
var retired domain.AssessmentFamily
|
||||
err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
repository := unit.AssessmentBank()
|
||||
family, err := lockedFamily(ctx, repository, key, version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := family.CheckRetirable(); err != nil {
|
||||
return err
|
||||
}
|
||||
retired, err = repository.MarkRetired(ctx, family.ID(), by)
|
||||
if err != nil {
|
||||
return storageRefusal(fmt.Errorf("mark retired: %w", err), domain.RefusalNotPublished)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("Bank.RetireFamily - retire %s version %d: %w", key, version, err)
|
||||
}
|
||||
return retired, nil
|
||||
}
|
||||
|
||||
// ActiveFamily returns the one published version of the family, or an error
|
||||
// wrapping outbound.ErrAssessmentFamilyNotFound when none is published.
|
||||
func (bank *Bank) ActiveFamily(ctx context.Context, key domain.AssessmentFamilyKey) (domain.AssessmentFamily, error) {
|
||||
var active domain.AssessmentFamily
|
||||
err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
active, err = unit.AssessmentBank().GetPublishedFamily(ctx, key)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("Bank.ActiveFamily - read published version of %s: %w", key, err)
|
||||
}
|
||||
return active, nil
|
||||
}
|
||||
|
||||
// storageRefusal turns the sentinels of a race that the database decided
|
||||
// into the refusal a caller would have got without the race. lifecycle is
|
||||
// the reason for a lifecycle step that the state no longer allows. Other
|
||||
// errors pass through.
|
||||
func storageRefusal(err error, lifecycle domain.AssessmentRefusalReason) error {
|
||||
var refusal *domain.AssessmentRefusalError
|
||||
switch {
|
||||
case errors.As(err, &refusal):
|
||||
return err
|
||||
case errors.Is(err, outbound.ErrAssessmentFamilyLifecycle):
|
||||
refusal = domain.NewAssessmentRefusal(lifecycle, "the version changed state while the operation ran")
|
||||
case errors.Is(err, outbound.ErrAssessmentFamilyNotPublishable):
|
||||
refusal = domain.NewAssessmentRefusal(domain.RefusalReviewNotApproved, "the database found no approved review of the version")
|
||||
case errors.Is(err, outbound.ErrAssessmentCoverageInsufficient):
|
||||
refusal = domain.NewAssessmentRefusal(domain.RefusalCoverageInsufficient, "the database counted fewer published families than the policy requires")
|
||||
case errors.Is(err, outbound.ErrAssessmentGradingPolicyNotFound):
|
||||
refusal = domain.NewAssessmentRefusal(domain.RefusalGradingPolicyMissing, "the database found no usable grading policy version")
|
||||
default:
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%w: %w", refusal, err)
|
||||
}
|
||||
|
||||
// OpenCategoryInput names the category to open, the agreed basic grading
|
||||
// policy by reference, and the operator who agreed to open it.
|
||||
type OpenCategoryInput struct {
|
||||
Category domain.AssessmentCategory
|
||||
// GradingPolicyID is the stored policy version whose assessment thresholds
|
||||
// apply. A zero ID, an ID that is not stored, and a stored version that
|
||||
// is not the one in force are refused.
|
||||
GradingPolicyID domain.PolicyVersionID
|
||||
OpenedBy domain.AssessmentOperator
|
||||
}
|
||||
|
||||
// OpenCategory makes a category available. It reads the referenced policy
|
||||
// version, which must be the version of the product policy in force now
|
||||
// (RefusalGradingPolicyNotCurrent otherwise), and counts the distinct
|
||||
// published families of the category; the number of families the category
|
||||
// needs is read from that policy, never defined here. It refuses, with a
|
||||
// *domain.AssessmentRefusalError, a missing or unknown policy reference
|
||||
// (RefusalGradingPolicyMissing) and a category with too few published
|
||||
// families (RefusalCoverageInsufficient). A refusal stores nothing.
|
||||
func (bank *Bank) OpenCategory(ctx context.Context, input OpenCategoryInput) (domain.AssessmentCategoryOpening, error) {
|
||||
category, err := domain.ParseAssessmentCategory(string(input.Category))
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryOpening{}, fmt.Errorf("Bank.OpenCategory - validate category: %w", err)
|
||||
}
|
||||
var opening domain.AssessmentCategoryOpening
|
||||
err = bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
repository := unit.AssessmentBank()
|
||||
if err := repository.LockCategory(ctx, category); err != nil {
|
||||
return fmt.Errorf("lock category: %w", err)
|
||||
}
|
||||
policy, err := readGradingPolicy(ctx, unit, input.GradingPolicyID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
published, err := repository.CountPublishedFamilies(ctx, category)
|
||||
if err != nil {
|
||||
return fmt.Errorf("count published families: %w", err)
|
||||
}
|
||||
draft, err := domain.NewAssessmentCategoryOpeningDraft(category, policy, published, input.OpenedBy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opening, err = repository.CreateCategoryOpening(ctx, draft)
|
||||
if err != nil {
|
||||
return storageRefusal(fmt.Errorf("store opening: %w", err), domain.RefusalNotDraft)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryOpening{}, fmt.Errorf("Bank.OpenCategory - open category %s: %w", category, err)
|
||||
}
|
||||
return opening, nil
|
||||
}
|
||||
|
||||
// readGradingPolicy reads the referenced policy version and requires it to
|
||||
// be the version of the product policy in force now.
|
||||
func readGradingPolicy(ctx context.Context, unit outbound.UnitOfWork, id domain.PolicyVersionID) (domain.PolicyVersion, error) {
|
||||
if id.IsZero() {
|
||||
return domain.PolicyVersion{}, domain.NewAssessmentRefusal(domain.RefusalGradingPolicyMissing, "a category opens only under a referenced versioned grading policy")
|
||||
}
|
||||
policy, err := unit.Policies().GetByID(ctx, id)
|
||||
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
|
||||
return domain.PolicyVersion{}, domain.NewAssessmentRefusal(domain.RefusalGradingPolicyMissing, "the referenced grading policy version is not stored")
|
||||
}
|
||||
if err != nil {
|
||||
return domain.PolicyVersion{}, fmt.Errorf("read grading policy: %w", err)
|
||||
}
|
||||
if err := checkPolicyInForce(ctx, unit, policy); err != nil {
|
||||
return domain.PolicyVersion{}, err
|
||||
}
|
||||
return policy, nil
|
||||
}
|
||||
|
||||
// checkPolicyInForce refuses a policy version that is not the one in force
|
||||
// for its family now. "Now" is the database clock of the same transaction,
|
||||
// the clock that stamped the effective time of the versions.
|
||||
func checkPolicyInForce(ctx context.Context, unit outbound.UnitOfWork, policy domain.PolicyVersion) error {
|
||||
now, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read database time: %w", err)
|
||||
}
|
||||
current, err := unit.Policies().GetEffective(ctx, policy.Key(), now)
|
||||
if errors.Is(err, outbound.ErrPolicyVersionNotFound) || (err == nil && current.ID() != policy.ID()) {
|
||||
return domain.NewAssessmentRefusal(domain.RefusalGradingPolicyNotCurrent,
|
||||
fmt.Sprintf("grading policy version %d is not the version in force", policy.Version()))
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("read policy in force: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CategoryAvailability returns the current opening of the category while the
|
||||
// category is available, which is live: the published families are counted
|
||||
// now and must still reach the coverage that the opening recorded. A
|
||||
// category without an opening returns an error wrapping
|
||||
// outbound.ErrAssessmentCategoryNotOpen, a category whose coverage fell below
|
||||
// the requirement, for example after a retirement, is refused with
|
||||
// RefusalCoverageInsufficient, and a category whose opening was made under a
|
||||
// policy version that is no longer the one in force is refused with
|
||||
// RefusalGradingPolicyNotCurrent: a policy change needs a new opening.
|
||||
func (bank *Bank) CategoryAvailability(ctx context.Context, category domain.AssessmentCategory) (domain.AssessmentCategoryOpening, error) {
|
||||
var opening domain.AssessmentCategoryOpening
|
||||
err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
repository := unit.AssessmentBank()
|
||||
var err error
|
||||
opening, err = repository.GetCurrentCategoryOpening(ctx, category)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
published, err := repository.CountPublishedFamilies(ctx, category)
|
||||
if err != nil {
|
||||
return fmt.Errorf("count published families: %w", err)
|
||||
}
|
||||
if published < opening.RequiredFamilies {
|
||||
return domain.NewAssessmentRefusal(domain.RefusalCoverageInsufficient,
|
||||
fmt.Sprintf("category has %d published families, its opening requires %d", published, opening.RequiredFamilies))
|
||||
}
|
||||
policy, err := unit.Policies().GetByID(ctx, opening.PolicyVersionID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read the opening's grading policy: %w", err)
|
||||
}
|
||||
return checkPolicyInForce(ctx, unit, policy)
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryOpening{}, fmt.Errorf("Bank.CategoryAvailability - check category %s: %w", category, err)
|
||||
}
|
||||
return opening, nil
|
||||
}
|
||||
|
||||
// GenerateVariant reads a stored version and generates the variant of a seed.
|
||||
// The same version and seed always return the same statement and reference
|
||||
// answer. A draft can be generated, so a reviewer can see what a version
|
||||
// produces before approving it.
|
||||
func (bank *Bank) GenerateVariant(ctx context.Context, key domain.AssessmentFamilyKey, version int32, seed domain.VariantSeed) (domain.AssessmentVariant, error) {
|
||||
var family domain.AssessmentFamily
|
||||
err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
family, err = unit.AssessmentBank().GetFamilyVersion(ctx, key, version)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentVariant{}, fmt.Errorf("Bank.GenerateVariant - read %s version %d: %w", key, version, err)
|
||||
}
|
||||
variant, err := family.NewVariant(seed)
|
||||
if err != nil {
|
||||
return domain.AssessmentVariant{}, fmt.Errorf("Bank.GenerateVariant - generate variant: %w", err)
|
||||
}
|
||||
return variant, nil
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
testOperator = domain.AssessmentOperator("operator:unit-publisher")
|
||||
testCategory = domain.AssessmentCategory("backend")
|
||||
)
|
||||
|
||||
// fakeBank is an in-memory outbound.AssessmentBankRepository. Methods that a
|
||||
// test does not need panic through the nil embedded interface.
|
||||
type fakeBank struct {
|
||||
outbound.AssessmentBankRepository
|
||||
|
||||
calls []string
|
||||
families map[string]domain.AssessmentFamily
|
||||
// onCreate runs inside CreateFamily, to store a version as a concurrent
|
||||
// import that wins the insert would.
|
||||
onCreate func()
|
||||
createErr error
|
||||
markPubErr error
|
||||
markRetErr error
|
||||
openErr error
|
||||
published int32
|
||||
publishedFam *domain.AssessmentFamily
|
||||
opening *domain.AssessmentCategoryOpening
|
||||
}
|
||||
|
||||
func versionKey(key domain.AssessmentFamilyKey, version int32) string {
|
||||
return fmt.Sprintf("%s/%d", key, version)
|
||||
}
|
||||
|
||||
func (bank *fakeBank) GetFamilyVersion(_ context.Context, key domain.AssessmentFamilyKey, version int32) (domain.AssessmentFamily, error) {
|
||||
bank.calls = append(bank.calls, "get")
|
||||
if family, ok := bank.families[versionKey(key, version)]; ok {
|
||||
return family, nil
|
||||
}
|
||||
return domain.AssessmentFamily{}, outbound.ErrAssessmentFamilyNotFound
|
||||
}
|
||||
|
||||
func (bank *fakeBank) GetLatestFamily(_ context.Context, key domain.AssessmentFamilyKey) (domain.AssessmentFamily, error) {
|
||||
var latest domain.AssessmentFamily
|
||||
for _, family := range bank.families {
|
||||
if family.Key() == key && (latest.IsZero() || family.Version() > latest.Version()) {
|
||||
latest = family
|
||||
}
|
||||
}
|
||||
if latest.IsZero() {
|
||||
return domain.AssessmentFamily{}, outbound.ErrAssessmentFamilyNotFound
|
||||
}
|
||||
return latest, nil
|
||||
}
|
||||
|
||||
func (bank *fakeBank) DatabaseTime(context.Context) (time.Time, error) { return time.Now(), nil }
|
||||
|
||||
func (bank *fakeBank) CreateFamily(context.Context, domain.AssessmentFamilyDraft) (domain.AssessmentFamily, error) {
|
||||
bank.calls = append(bank.calls, "create")
|
||||
if bank.onCreate != nil {
|
||||
bank.onCreate()
|
||||
}
|
||||
return domain.AssessmentFamily{}, bank.createErr
|
||||
}
|
||||
|
||||
func (bank *fakeBank) LockCategory(context.Context, domain.AssessmentCategory) error {
|
||||
bank.calls = append(bank.calls, "lock")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bank *fakeBank) GetPublishedFamily(context.Context, domain.AssessmentFamilyKey) (domain.AssessmentFamily, error) {
|
||||
if bank.publishedFam == nil {
|
||||
return domain.AssessmentFamily{}, outbound.ErrAssessmentFamilyNotFound
|
||||
}
|
||||
return *bank.publishedFam, nil
|
||||
}
|
||||
|
||||
func (bank *fakeBank) MarkPublished(_ context.Context, id domain.AssessmentFamilyID, _ domain.AssessmentOperator) (domain.AssessmentFamily, error) {
|
||||
bank.calls = append(bank.calls, "publish:"+id.String())
|
||||
return domain.AssessmentFamily{}, bank.markPubErr
|
||||
}
|
||||
|
||||
func (bank *fakeBank) MarkRetired(_ context.Context, id domain.AssessmentFamilyID, _ domain.AssessmentOperator) (domain.AssessmentFamily, error) {
|
||||
bank.calls = append(bank.calls, "retire:"+id.String())
|
||||
return domain.AssessmentFamily{}, bank.markRetErr
|
||||
}
|
||||
|
||||
func (bank *fakeBank) CountPublishedFamilies(context.Context, domain.AssessmentCategory) (int32, error) {
|
||||
bank.calls = append(bank.calls, "count")
|
||||
return bank.published, nil
|
||||
}
|
||||
|
||||
func (bank *fakeBank) CreateCategoryOpening(context.Context, domain.AssessmentCategoryOpeningDraft) (domain.AssessmentCategoryOpening, error) {
|
||||
bank.calls = append(bank.calls, "open")
|
||||
return domain.AssessmentCategoryOpening{}, bank.openErr
|
||||
}
|
||||
|
||||
func (bank *fakeBank) GetCurrentCategoryOpening(context.Context, domain.AssessmentCategory) (domain.AssessmentCategoryOpening, error) {
|
||||
if bank.opening == nil {
|
||||
return domain.AssessmentCategoryOpening{}, outbound.ErrAssessmentCategoryNotOpen
|
||||
}
|
||||
return *bank.opening, nil
|
||||
}
|
||||
|
||||
type fakePolicies struct {
|
||||
outbound.PolicyRepository
|
||||
|
||||
stored map[domain.PolicyVersionID]domain.PolicyVersion
|
||||
effective domain.PolicyVersion
|
||||
}
|
||||
|
||||
func (policies fakePolicies) GetByID(_ context.Context, id domain.PolicyVersionID) (domain.PolicyVersion, error) {
|
||||
if version, ok := policies.stored[id]; ok {
|
||||
return version, nil
|
||||
}
|
||||
return domain.PolicyVersion{}, outbound.ErrPolicyVersionNotFound
|
||||
}
|
||||
|
||||
func (policies fakePolicies) GetEffective(context.Context, domain.PolicyKey, time.Time) (domain.PolicyVersion, error) {
|
||||
if policies.effective.IsZero() {
|
||||
return domain.PolicyVersion{}, outbound.ErrPolicyVersionNotFound
|
||||
}
|
||||
return policies.effective, nil
|
||||
}
|
||||
|
||||
type fakeUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
bank *fakeBank
|
||||
policies fakePolicies
|
||||
}
|
||||
|
||||
func (unit *fakeUnit) AssessmentBank() outbound.AssessmentBankRepository { return unit.bank }
|
||||
|
||||
func (unit *fakeUnit) Policies() outbound.PolicyRepository { return unit.policies }
|
||||
|
||||
type fakeTransactor struct{ unit *fakeUnit }
|
||||
|
||||
func (transactor fakeTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error {
|
||||
return fn(ctx, transactor.unit)
|
||||
}
|
||||
|
||||
func newTestBank(t *testing.T) (*Bank, *fakeUnit) {
|
||||
t.Helper()
|
||||
unit := &fakeUnit{bank: &fakeBank{families: map[string]domain.AssessmentFamily{}}, policies: fakePolicies{stored: map[domain.PolicyVersionID]domain.PolicyVersion{}}}
|
||||
return NewBank(fakeTransactor{unit: unit}), unit
|
||||
}
|
||||
|
||||
// testPolicyVersion builds a stored policy version in force.
|
||||
func testPolicyVersion(t *testing.T, number int32) domain.PolicyVersion {
|
||||
t.Helper()
|
||||
values := domain.DemoProductPolicyV1()
|
||||
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: values,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
|
||||
}
|
||||
numbered, err := draft.WithVersion(number)
|
||||
if err != nil {
|
||||
t.Fatalf("WithVersion() error = %v", err)
|
||||
}
|
||||
hash, at := numbered.DocumentHash(), time.Now().Add(-time.Hour)
|
||||
version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{
|
||||
ID: numbered.ID(), Key: string(numbered.Key()), Version: number, Kind: string(numbered.Kind()), Author: string(numbered.Author()),
|
||||
EffectiveAt: at, CreatedAt: at, Document: numbered.Document(), DocumentHash: hash[:],
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestorePolicyVersion() error = %v", err)
|
||||
}
|
||||
return version
|
||||
}
|
||||
|
||||
// storedFamily builds a stored version of the first demo family with the
|
||||
// given number and lifecycle, approved by a reviewer unless pending.
|
||||
func storedFamily(t *testing.T, bundle Bundle, version int32, approved bool, lifecycle domain.AssessmentLifecycle) domain.AssessmentFamily {
|
||||
t.Helper()
|
||||
bundle.Families = bundle.Families[:1]
|
||||
bundle.Families[0].Version = version
|
||||
if approved {
|
||||
bundle.Author = "operator:unit-author"
|
||||
bundle.Review = BundleReview{Status: "approved", Reviewer: "operator:unit-reviewer"}
|
||||
}
|
||||
drafts, err := bundle.Drafts()
|
||||
if err != nil {
|
||||
t.Fatalf("Drafts() error = %v", err)
|
||||
}
|
||||
draft := drafts[0]
|
||||
core, hash := draft.Core(), draft.ContentHash()
|
||||
generator, _ := draft.SeedGeneratorJSON()
|
||||
key, _ := draft.AnswerKeyJSON()
|
||||
rubric, _ := draft.RubricJSON()
|
||||
stored := domain.StoredAssessmentFamily{
|
||||
ID: draft.ID(), FamilyKey: string(core.Key), Version: core.Version, Category: string(core.Category),
|
||||
Specialization: string(core.Specialization), Title: core.Title, BundleName: string(core.BundleName), Author: string(core.Author),
|
||||
Reviewer: string(core.Reviewer), ReviewStatus: string(core.ReviewStatus), SeedGenerator: generator, AnswerKey: key, Rubric: rubric,
|
||||
ContentHash: hash[:], HashScheme: draft.HashScheme(), Lifecycle: string(lifecycle), CreatedAt: time.Now(),
|
||||
}
|
||||
if lifecycle != domain.AssessmentLifecycleDraft {
|
||||
stored.PublishedAt, stored.PublishedBy = time.Now(), string(testOperator)
|
||||
}
|
||||
if lifecycle == domain.AssessmentLifecycleRetired {
|
||||
stored.RetiredAt, stored.RetiredBy = time.Now(), string(testOperator)
|
||||
}
|
||||
family, err := domain.RestoreAssessmentFamily(stored)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreAssessmentFamily() error = %v", err)
|
||||
}
|
||||
return family
|
||||
}
|
||||
|
||||
func assertRefusal(t *testing.T, operation string, err error, want domain.AssessmentRefusalReason) {
|
||||
t.Helper()
|
||||
var refusal *domain.AssessmentRefusalError
|
||||
if !errors.As(err, &refusal) || refusal.Reason != want || !errors.Is(err, domain.ErrAssessmentRefused) {
|
||||
t.Fatalf("%s error = %v, want a refusal with reason %s", operation, err, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportAcceptsAConcurrentIdenticalImport(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
bundle := loadDemoBundle(t)
|
||||
bundle.Families = bundle.Families[:1]
|
||||
drafts, err := bundle.Drafts()
|
||||
if err != nil {
|
||||
t.Fatalf("Drafts() error = %v", err)
|
||||
}
|
||||
winner := storedFamily(t, bundle, 1, false, domain.AssessmentLifecycleDraft)
|
||||
unit.bank.createErr = outbound.ErrAssessmentFamilyConflict
|
||||
unit.bank.onCreate = func() { unit.bank.families[versionKey(drafts[0].Core().Key, 1)] = winner }
|
||||
|
||||
result, err := bank.ImportBundle(t.Context(), bundle)
|
||||
if err != nil || len(result.Created) != 0 || len(result.Unchanged) != 1 {
|
||||
t.Fatalf("ImportBundle(concurrent identical import) = %+v, %v, want one unchanged version", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportRefusesAConcurrentImportWithOtherContent(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
bundle := loadDemoBundle(t)
|
||||
bundle.Families = bundle.Families[:1]
|
||||
other := bundle
|
||||
other.Families = append([]BundleFamily(nil), bundle.Families...)
|
||||
other.Families[0].AnswerKey.ReferenceSolution = "A different approach."
|
||||
winner := storedFamily(t, other, 1, false, domain.AssessmentLifecycleDraft)
|
||||
unit.bank.createErr = outbound.ErrAssessmentFamilyConflict
|
||||
unit.bank.onCreate = func() { unit.bank.families[versionKey(winner.Key(), 1)] = winner }
|
||||
|
||||
_, err := bank.ImportBundle(t.Context(), bundle)
|
||||
assertRefusal(t, "ImportBundle(concurrent import with other content)", err, domain.RefusalVersionConflict)
|
||||
}
|
||||
|
||||
func TestDatabaseRacesBecomeRefusalsWithTheMatchingReason(t *testing.T) {
|
||||
bundle := loadDemoBundle(t)
|
||||
draft := storedFamily(t, bundle, 1, true, domain.AssessmentLifecycleDraft)
|
||||
published := storedFamily(t, bundle, 1, true, domain.AssessmentLifecyclePublished)
|
||||
|
||||
t.Run("publication lost to a state change", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
unit.bank.families[versionKey(draft.Key(), 1)] = draft
|
||||
unit.bank.markPubErr = outbound.ErrAssessmentFamilyLifecycle
|
||||
_, err := bank.PublishFamily(t.Context(), draft.Key(), 1, testOperator)
|
||||
assertRefusal(t, "PublishFamily(lifecycle race)", err, domain.RefusalNotDraft)
|
||||
if !errors.Is(err, outbound.ErrAssessmentFamilyLifecycle) {
|
||||
t.Fatalf("PublishFamily() error = %v, want the storage sentinel kept", err)
|
||||
}
|
||||
})
|
||||
t.Run("publication refused by the review constraint", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
unit.bank.families[versionKey(draft.Key(), 1)] = draft
|
||||
unit.bank.markPubErr = outbound.ErrAssessmentFamilyNotPublishable
|
||||
_, err := bank.PublishFamily(t.Context(), draft.Key(), 1, testOperator)
|
||||
assertRefusal(t, "PublishFamily(review constraint)", err, domain.RefusalReviewNotApproved)
|
||||
})
|
||||
t.Run("retirement lost to a state change", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
unit.bank.families[versionKey(published.Key(), 1)] = published
|
||||
unit.bank.markRetErr = outbound.ErrAssessmentFamilyLifecycle
|
||||
_, err := bank.RetireFamily(t.Context(), published.Key(), 1, testOperator)
|
||||
assertRefusal(t, "RetireFamily(lifecycle race)", err, domain.RefusalNotPublished)
|
||||
})
|
||||
t.Run("opening refused by the coverage constraint", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
version := testPolicyVersion(t, 1)
|
||||
unit.policies.stored[version.ID()], unit.policies.effective = version, version
|
||||
required, err := domain.RequiredPublishedAssessmentFamilies(version.Policy())
|
||||
if err != nil {
|
||||
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
|
||||
}
|
||||
unit.bank.published = required
|
||||
unit.bank.openErr = outbound.ErrAssessmentCoverageInsufficient
|
||||
_, err = bank.OpenCategory(t.Context(), OpenCategoryInput{Category: testCategory, GradingPolicyID: version.ID(), OpenedBy: "operator:opener"})
|
||||
assertRefusal(t, "OpenCategory(coverage race)", err, domain.RefusalCoverageInsufficient)
|
||||
})
|
||||
t.Run("opening refused for an unusable policy", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
version := testPolicyVersion(t, 1)
|
||||
unit.policies.stored[version.ID()], unit.policies.effective = version, version
|
||||
required, _ := domain.RequiredPublishedAssessmentFamilies(version.Policy())
|
||||
unit.bank.published = required
|
||||
unit.bank.openErr = outbound.ErrAssessmentGradingPolicyNotFound
|
||||
_, err := bank.OpenCategory(t.Context(), OpenCategoryInput{Category: testCategory, GradingPolicyID: version.ID(), OpenedBy: "operator:opener"})
|
||||
assertRefusal(t, "OpenCategory(policy race)", err, domain.RefusalGradingPolicyMissing)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPublishRetiresTheOlderVersionAndRefusesWhenANewerOneIsPublished(t *testing.T) {
|
||||
bundle := loadDemoBundle(t)
|
||||
older := storedFamily(t, bundle, 1, true, domain.AssessmentLifecyclePublished)
|
||||
next := storedFamily(t, bundle, 2, true, domain.AssessmentLifecycleDraft)
|
||||
newer := storedFamily(t, bundle, 3, true, domain.AssessmentLifecyclePublished)
|
||||
|
||||
t.Run("older published version", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
unit.bank.families[versionKey(next.Key(), 2)] = next
|
||||
unit.bank.publishedFam = &older
|
||||
if _, err := bank.PublishFamily(t.Context(), next.Key(), 2, testOperator); err != nil {
|
||||
t.Fatalf("PublishFamily() error = %v", err)
|
||||
}
|
||||
want := []string{"get", "lock", "get", "retire:" + older.ID().String(), "publish:" + next.ID().String()}
|
||||
if !slices.Equal(unit.bank.calls, want) {
|
||||
t.Fatalf("calls = %v, want %v: lock first, retire the older version, then publish", unit.bank.calls, want)
|
||||
}
|
||||
})
|
||||
t.Run("newer published version", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
unit.bank.families[versionKey(next.Key(), 2)] = next
|
||||
unit.bank.families[versionKey(newer.Key(), 3)] = newer
|
||||
unit.bank.publishedFam = &newer
|
||||
_, err := bank.PublishFamily(t.Context(), next.Key(), 2, testOperator)
|
||||
assertRefusal(t, "PublishFamily(newer is published)", err, domain.RefusalNewerVersionPublished)
|
||||
if slices.ContainsFunc(unit.bank.calls, func(call string) bool { return len(call) > 6 && call[:6] == "retire" }) {
|
||||
t.Fatalf("calls = %v, want nothing retired after a refusal", unit.bank.calls)
|
||||
}
|
||||
})
|
||||
t.Run("an operator that is not an operator", func(t *testing.T) {
|
||||
bank, _ := newTestBank(t)
|
||||
if _, err := bank.PublishFamily(t.Context(), next.Key(), 2, "ai:draft"); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("PublishFamily(ai operator) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestOpenCategoryRequiresThePolicyInForce(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
first, second := testPolicyVersion(t, 1), testPolicyVersion(t, 2)
|
||||
unit.policies.stored[first.ID()], unit.policies.stored[second.ID()] = first, second
|
||||
unit.policies.effective = second
|
||||
required, _ := domain.RequiredPublishedAssessmentFamilies(second.Policy())
|
||||
unit.bank.published = required
|
||||
|
||||
_, err := bank.OpenCategory(t.Context(), OpenCategoryInput{Category: testCategory, GradingPolicyID: first.ID(), OpenedBy: "operator:opener"})
|
||||
assertRefusal(t, "OpenCategory(superseded policy)", err, domain.RefusalGradingPolicyNotCurrent)
|
||||
if _, err := bank.OpenCategory(t.Context(), OpenCategoryInput{Category: testCategory, GradingPolicyID: second.ID(), OpenedBy: "operator:opener"}); err != nil {
|
||||
t.Fatalf("OpenCategory(policy in force) error = %v", err)
|
||||
}
|
||||
if unit.bank.calls[0] != "lock" {
|
||||
t.Fatalf("calls = %v, want the category lock first", unit.bank.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCategoryAvailabilityIsLive(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
if _, err := bank.CategoryAvailability(t.Context(), testCategory); !errors.Is(err, outbound.ErrAssessmentCategoryNotOpen) {
|
||||
t.Fatalf("CategoryAvailability(no opening) error = %v, want ErrAssessmentCategoryNotOpen", err)
|
||||
}
|
||||
inForce := testPolicyVersion(t, 1)
|
||||
unit.policies.stored[inForce.ID()], unit.policies.effective = inForce, inForce
|
||||
unit.bank.opening = &domain.AssessmentCategoryOpening{Category: testCategory, PolicyVersionID: inForce.ID(), RequiredFamilies: 5, PublishedFamilies: 5}
|
||||
unit.bank.published = 5
|
||||
if _, err := bank.CategoryAvailability(t.Context(), testCategory); err != nil {
|
||||
t.Fatalf("CategoryAvailability(enough coverage) error = %v", err)
|
||||
}
|
||||
unit.bank.published = 4
|
||||
_, err := bank.CategoryAvailability(t.Context(), testCategory)
|
||||
assertRefusal(t, "CategoryAvailability(coverage fell)", err, domain.RefusalCoverageInsufficient)
|
||||
}
|
||||
|
||||
func TestPublishRefusesAnOlderVersionWhileANewerOneExistsInAnyState(t *testing.T) {
|
||||
bundle := loadDemoBundle(t)
|
||||
older := storedFamily(t, bundle, 1, true, domain.AssessmentLifecycleDraft)
|
||||
for name, newer := range map[string]domain.AssessmentFamily{
|
||||
"draft": storedFamily(t, bundle, 2, true, domain.AssessmentLifecycleDraft),
|
||||
"published": storedFamily(t, bundle, 2, true, domain.AssessmentLifecyclePublished),
|
||||
"retired": storedFamily(t, bundle, 2, true, domain.AssessmentLifecycleRetired),
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
unit.bank.families[versionKey(older.Key(), 1)] = older
|
||||
unit.bank.families[versionKey(newer.Key(), 2)] = newer
|
||||
_, err := bank.PublishFamily(t.Context(), older.Key(), 1, testOperator)
|
||||
assertRefusal(t, "PublishFamily(older than an existing version)", err, domain.RefusalNewerVersionPublished)
|
||||
if slices.ContainsFunc(unit.bank.calls, func(call string) bool { return strings.HasPrefix(call, "publish") || strings.HasPrefix(call, "retire") }) {
|
||||
t.Fatalf("calls = %v, want nothing published or retired after a refusal", unit.bank.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAvailabilityRequiresTheOpeningPolicyToStayInForce(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
opened, replacement := testPolicyVersion(t, 1), testPolicyVersion(t, 2)
|
||||
unit.policies.stored[opened.ID()], unit.policies.stored[replacement.ID()] = opened, replacement
|
||||
unit.policies.effective = opened
|
||||
unit.bank.opening = &domain.AssessmentCategoryOpening{Category: testCategory, PolicyVersionID: opened.ID(), RequiredFamilies: 5, PublishedFamilies: 5}
|
||||
unit.bank.published = 5
|
||||
if _, err := bank.CategoryAvailability(t.Context(), testCategory); err != nil {
|
||||
t.Fatalf("CategoryAvailability(policy in force) error = %v", err)
|
||||
}
|
||||
// A new policy version takes force: the opening no longer applies.
|
||||
unit.policies.effective = replacement
|
||||
_, err := bank.CategoryAvailability(t.Context(), testCategory)
|
||||
assertRefusal(t, "CategoryAvailability(policy superseded)", err, domain.RefusalGradingPolicyNotCurrent)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxBundleBytes bounds the size of a bundle document that ParseBundle
|
||||
// reads.
|
||||
maxBundleBytes = 1 << 20
|
||||
// maxBundleFamilies bounds the family versions in one bundle, so one
|
||||
// import stays one reasonably sized transaction.
|
||||
maxBundleFamilies = 200
|
||||
)
|
||||
|
||||
// Bundle is a named set of family versions of one category: one author, one
|
||||
// independent review of the whole set, and the content of each version. It
|
||||
// is the input of the loader and carries no grading policy: the policy is
|
||||
// referenced when a category is opened.
|
||||
//
|
||||
// A bundle that someone prepared is not thereby reviewed. The review block
|
||||
// records what a reviewer decided; a pending review has no reviewer.
|
||||
type Bundle struct {
|
||||
Name string `json:"name"`
|
||||
Category string `json:"category"`
|
||||
Author string `json:"author"`
|
||||
Review BundleReview `json:"review"`
|
||||
Families []BundleFamily `json:"families"`
|
||||
}
|
||||
|
||||
// BundleReview is the independent review of a bundle. Reviewer is empty while
|
||||
// Status is "pending".
|
||||
type BundleReview struct {
|
||||
Status string `json:"status"`
|
||||
Reviewer string `json:"reviewer"`
|
||||
}
|
||||
|
||||
// BundleFamily is the content of one family version in a bundle.
|
||||
type BundleFamily struct {
|
||||
Key string `json:"key"`
|
||||
Version int32 `json:"version"`
|
||||
Specialization string `json:"specialization"`
|
||||
Title string `json:"title"`
|
||||
SeedGenerator domain.AssessmentSeedGenerator `json:"seed_generator"`
|
||||
AnswerKey domain.AssessmentAnswerKey `json:"answer_key"`
|
||||
Rubric domain.AssessmentRubric `json:"rubric"`
|
||||
}
|
||||
|
||||
// ParseBundle reads a bundle document strictly: an unknown field, trailing
|
||||
// data, or a document above the size bound is an error wrapping
|
||||
// domain.ErrInvalidAssessmentFamily. It does not validate the content; Drafts
|
||||
// does.
|
||||
func ParseBundle(reader io.Reader) (Bundle, error) {
|
||||
const location = "assessment.ParseBundle"
|
||||
content, err := io.ReadAll(io.LimitReader(reader, maxBundleBytes+1))
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("%s - read bundle: %w", location, err)
|
||||
}
|
||||
if len(content) > maxBundleBytes {
|
||||
return Bundle{}, fmt.Errorf("%s - bundle exceeds %d bytes: %w", location, maxBundleBytes, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(content))
|
||||
decoder.DisallowUnknownFields()
|
||||
var bundle Bundle
|
||||
if err := decoder.Decode(&bundle); err != nil {
|
||||
return Bundle{}, fmt.Errorf("%s - decode bundle: %w: %w", location, domain.ErrInvalidAssessmentFamily, err)
|
||||
}
|
||||
if decoder.More() {
|
||||
return Bundle{}, fmt.Errorf("%s - trailing data after the bundle: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
// Drafts builds the validated drafts of every family version, ordered by key
|
||||
// and version, so that two versions of one family are stored in order. It
|
||||
// returns an error wrapping domain.ErrInvalidAssessmentFamily for an invalid
|
||||
// bundle, a repeated key and version, or a family set that is empty or too
|
||||
// large. Every draft is imported as a draft whatever its review says;
|
||||
// publication is a separate decision.
|
||||
func (bundle Bundle) Drafts() ([]domain.AssessmentFamilyDraft, error) {
|
||||
const location = "Bundle.Drafts"
|
||||
name, err := domain.ParseAssessmentBundleName(bundle.Name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - validate name: %w", location, err)
|
||||
}
|
||||
category, err := domain.ParseAssessmentCategory(bundle.Category)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - validate category: %w", location, err)
|
||||
}
|
||||
author, err := domain.ParseAssessmentAuthor(bundle.Author)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - validate author: %w", location, err)
|
||||
}
|
||||
if len(bundle.Families) == 0 || len(bundle.Families) > maxBundleFamilies {
|
||||
return nil, fmt.Errorf("%s - bundle must have 1 to %d families: %w", location, maxBundleFamilies, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
families := slices.Clone(bundle.Families)
|
||||
slices.SortFunc(families, func(left, right BundleFamily) int {
|
||||
if byKey := strings.Compare(left.Key, right.Key); byKey != 0 {
|
||||
return byKey
|
||||
}
|
||||
return int(left.Version) - int(right.Version)
|
||||
})
|
||||
drafts := make([]domain.AssessmentFamilyDraft, 0, len(families))
|
||||
for index, family := range families {
|
||||
if index > 0 && family.Key == families[index-1].Key && family.Version == families[index-1].Version {
|
||||
return nil, fmt.Errorf("%s - family %s version %d appears twice: %w", location, family.Key, family.Version, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
draft, err := domain.NewAssessmentFamilyDraft(domain.NewAssessmentFamilyDraftInput{
|
||||
Key: domain.AssessmentFamilyKey(family.Key),
|
||||
Version: family.Version,
|
||||
Category: category,
|
||||
Specialization: domain.AssessmentSpecialization(family.Specialization),
|
||||
Title: family.Title,
|
||||
BundleName: name,
|
||||
Author: author,
|
||||
Reviewer: domain.AssessmentOperator(bundle.Review.Reviewer),
|
||||
ReviewStatus: domain.AssessmentReviewStatus(bundle.Review.Status),
|
||||
Generator: family.SeedGenerator,
|
||||
AnswerKey: family.AnswerKey,
|
||||
Rubric: family.Rubric,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - family %s version %d: %w", location, family.Key, family.Version, err)
|
||||
}
|
||||
drafts = append(drafts, draft)
|
||||
}
|
||||
return drafts, nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
const demoBundlePath = "../../../testdata/assessment/backend_demo_bundle.json"
|
||||
|
||||
func loadDemoBundle(t *testing.T) Bundle {
|
||||
t.Helper()
|
||||
file, err := os.Open(filepath.FromSlash(demoBundlePath))
|
||||
if err != nil {
|
||||
t.Fatalf("open demo bundle: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
bundle, err := ParseBundle(file)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseBundle() error = %v", err)
|
||||
}
|
||||
return bundle
|
||||
}
|
||||
|
||||
// The demo bundle is an AI draft without a human review. The test pins that
|
||||
// status, so filling the reviewer in is a visible decision.
|
||||
func TestDemoBundleIsAnUnreviewedAIDraft(t *testing.T) {
|
||||
bundle := loadDemoBundle(t)
|
||||
if bundle.Review.Status != "pending" || bundle.Review.Reviewer != "" {
|
||||
t.Fatalf("demo bundle review = %+v, want pending with an empty reviewer", bundle.Review)
|
||||
}
|
||||
if !strings.HasPrefix(bundle.Author, "ai:") {
|
||||
t.Fatalf("demo bundle author = %q, want an ai: identity", bundle.Author)
|
||||
}
|
||||
drafts, err := bundle.Drafts()
|
||||
if err != nil {
|
||||
t.Fatalf("Drafts() error = %v", err)
|
||||
}
|
||||
if len(drafts) != len(bundle.Families) {
|
||||
t.Fatalf("Drafts() returned %d drafts for %d families", len(drafts), len(bundle.Families))
|
||||
}
|
||||
for _, draft := range drafts {
|
||||
core := draft.Core()
|
||||
if core.Reviewer != "" || core.ReviewStatus != domain.AssessmentReviewPending {
|
||||
t.Fatalf("draft %s has review %q/%s, want pending without reviewer", core.Key, core.Reviewer, core.ReviewStatus)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBundleRejectsInvalidDocuments(t *testing.T) {
|
||||
if _, err := ParseBundle(strings.NewReader(`{"name":"x","unknown":1}`)); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("ParseBundle(unknown field) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
if _, err := ParseBundle(strings.NewReader(`{} {}`)); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("ParseBundle(trailing data) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
|
||||
duplicate := loadDemoBundle(t)
|
||||
duplicate.Families = append(duplicate.Families, duplicate.Families[0])
|
||||
if _, err := duplicate.Drafts(); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("Drafts(repeated version) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
|
||||
selfReviewed := loadDemoBundle(t)
|
||||
selfReviewed.Author = "operator:same-person"
|
||||
selfReviewed.Review = BundleReview{Status: "approved", Reviewer: "operator:same-person"}
|
||||
if _, err := selfReviewed.Drafts(); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("Drafts(reviewer is the author) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
|
||||
empty := loadDemoBundle(t)
|
||||
empty.Families = nil
|
||||
if _, err := empty.Drafts(); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("Drafts(no families) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
# Assessment demo bundle status
|
||||
|
||||
`backend_demo_bundle.json` is the input of the assessment bank loader
|
||||
(`internal/usecase/assessment`) for the category `backend`. It holds four
|
||||
families of original practice problems with deterministic seed generators,
|
||||
reference solutions, and rubrics.
|
||||
|
||||
## Status: AI-generated draft, pending human review
|
||||
|
||||
- Author: `ai:claude-draft`. The problems were written by an AI assistant for
|
||||
the loader task; they are not copies or paraphrases of problems from any
|
||||
coding-practice site.
|
||||
- Review: `pending`. The reviewer field is empty on purpose. No human has
|
||||
checked the statements, the reference solutions, the rubrics, or the
|
||||
difficulty. Do not fill the field to make the bundle pass.
|
||||
- Consequences, which the integration tests rely on:
|
||||
- The loader imports every family as a `draft`.
|
||||
- A family without a reviewer cannot be published
|
||||
(`reviewer_missing`).
|
||||
- The category `backend` cannot be opened: it has no published family, and
|
||||
four families are below the coverage that the grading policy requires.
|
||||
- The bundle makes no claim about difficulty, validity, or grade
|
||||
calibration.
|
||||
|
||||
## What the bundle does not contain
|
||||
|
||||
- No grading policy. A category opens only under a versioned grading policy
|
||||
that is referenced by `policy_versions.id` when the category is opened. The
|
||||
rubrics list criteria without points or thresholds.
|
||||
- No reviewer. A real review produces a new bundle version in which the
|
||||
family versions carry an approved review by an operator who is not the
|
||||
author; stored versions are never edited.
|
||||
|
||||
## Format
|
||||
|
||||
Documented by the types `assessment.Bundle` and `domain.AssessmentFamily`.
|
||||
Seed algorithms are registered in `internal/domain/assessment_algorithms.go`
|
||||
under versioned names (`rate_limit_window.v1`, `dedup_window.v1`,
|
||||
`lru_hits.v1`, `dependency_order.v1`); the statement templates use the
|
||||
parameter names and the data names of the chosen algorithm.
|
||||
@@ -0,0 +1,211 @@
|
||||
{
|
||||
"name": "backend-demo-ai-draft-v1",
|
||||
"category": "backend",
|
||||
"author": "ai:claude-draft",
|
||||
"review": {
|
||||
"status": "pending",
|
||||
"reviewer": ""
|
||||
},
|
||||
"families": [
|
||||
{
|
||||
"key": "backend-rate-limit-window",
|
||||
"version": 1,
|
||||
"specialization": "rate-limiting",
|
||||
"title": "Sliding-window request limiter",
|
||||
"seed_generator": {
|
||||
"algorithm": "rate_limit_window.v1",
|
||||
"parameters": {
|
||||
"requests": {
|
||||
"min": 12,
|
||||
"max": 40
|
||||
},
|
||||
"window": {
|
||||
"min": 3,
|
||||
"max": 15
|
||||
},
|
||||
"limit": {
|
||||
"min": 2,
|
||||
"max": 6
|
||||
},
|
||||
"max_gap": {
|
||||
"min": 1,
|
||||
"max": 5
|
||||
}
|
||||
},
|
||||
"statement_template": "A gateway protects an endpoint with a sliding-window limiter. A request arriving at second t is accepted only when fewer than {{.limit}} previously accepted requests have an arrival time in the half-open interval (t - {{.window}}, t]. A rejected request is not remembered and does not count against later requests. The gateway receives {{.requests}} requests at these arrival times, in seconds and in non-decreasing order: {{.timestamps}}. How many requests does the gateway reject?"
|
||||
},
|
||||
"answer_key": {
|
||||
"answer_format": "integer",
|
||||
"reference_solution": "Keep the arrival times of accepted requests in a queue. Before handling a request at time t, drop queued times that are at most t - window. If the queue holds fewer than limit entries, append t; otherwise count a rejection. Each time enters and leaves the queue once, so the cost is linear in the number of requests."
|
||||
},
|
||||
"rubric": {
|
||||
"principle": "A submission is first compared with the reference answer of its variant and then judged against the criteria below. This rubric defines no points and no pass mark: how criteria turn into a grade is decided by the versioned grading policy.",
|
||||
"criteria": [
|
||||
{
|
||||
"id": "correct_answer",
|
||||
"description": "The submitted number equals the reference answer of the variant."
|
||||
},
|
||||
{
|
||||
"id": "window_boundary",
|
||||
"description": "The solution treats the window as half-open: a request exactly window seconds old no longer counts."
|
||||
},
|
||||
{
|
||||
"id": "rejected_not_counted",
|
||||
"description": "Rejected requests are not stored and do not occupy window capacity."
|
||||
},
|
||||
{
|
||||
"id": "approach",
|
||||
"description": "The solution states an approach that handles each request in amortized constant time or explains why a slower one is enough for the input sizes."
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "backend-idempotent-consumer-window",
|
||||
"version": 1,
|
||||
"specialization": "messaging",
|
||||
"title": "Idempotent consumer with a duplicate window",
|
||||
"seed_generator": {
|
||||
"algorithm": "dedup_window.v1",
|
||||
"parameters": {
|
||||
"events": {
|
||||
"min": 10,
|
||||
"max": 40
|
||||
},
|
||||
"keys": {
|
||||
"min": 2,
|
||||
"max": 6
|
||||
},
|
||||
"ttl": {
|
||||
"min": 3,
|
||||
"max": 20
|
||||
},
|
||||
"max_gap": {
|
||||
"min": 1,
|
||||
"max": 6
|
||||
}
|
||||
},
|
||||
"statement_template": "A consumer receives {{.events}} messages written as KEY@TIME, where TIME is the arrival second and times never decrease. It processes a message unless the same KEY was processed less than {{.ttl}} seconds earlier; such a message is dropped as a duplicate. A dropped message does not postpone the next processing of its KEY. The stream is: {{.stream}}. How many messages does the consumer process?"
|
||||
},
|
||||
"answer_key": {
|
||||
"answer_format": "integer",
|
||||
"reference_solution": "Keep a map from key to the time of its last processed message. For each message, if the key is present and the time difference is smaller than ttl, drop it; otherwise record the time and count the message as processed. One pass, constant work per message."
|
||||
},
|
||||
"rubric": {
|
||||
"principle": "A submission is first compared with the reference answer of its variant and then judged against the criteria below. This rubric defines no points and no pass mark: how criteria turn into a grade is decided by the versioned grading policy.",
|
||||
"criteria": [
|
||||
{
|
||||
"id": "correct_answer",
|
||||
"description": "The submitted number equals the reference answer of the variant."
|
||||
},
|
||||
{
|
||||
"id": "duplicate_boundary",
|
||||
"description": "A message exactly ttl seconds after the last processed one with the same key is processed, not dropped."
|
||||
},
|
||||
{
|
||||
"id": "dropped_not_extending",
|
||||
"description": "A dropped duplicate does not move the time stored for its key."
|
||||
},
|
||||
{
|
||||
"id": "approach",
|
||||
"description": "The solution keeps state per key instead of rescanning earlier messages."
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "backend-lru-cache-hits",
|
||||
"version": 1,
|
||||
"specialization": "caching",
|
||||
"title": "Hit count of a least-recently-used cache",
|
||||
"seed_generator": {
|
||||
"algorithm": "lru_hits.v1",
|
||||
"parameters": {
|
||||
"accesses": {
|
||||
"min": 15,
|
||||
"max": 50
|
||||
},
|
||||
"keys": {
|
||||
"min": 3,
|
||||
"max": 10
|
||||
},
|
||||
"capacity": {
|
||||
"min": 2,
|
||||
"max": 5
|
||||
}
|
||||
},
|
||||
"statement_template": "An in-memory cache holds at most {{.capacity}} entries and evicts the least recently used entry when it is full and a missing key must be stored. Reading a key that is present is a hit; reading a key that is absent is a miss, after which the key is stored. Both a hit and a miss make the key the most recently used one. The cache starts empty and serves these {{.accesses}} reads, drawn from {{.keys}} possible keys numbered from 1 to {{.keys}}: {{.sequence}}. How many reads are hits?"
|
||||
},
|
||||
"answer_key": {
|
||||
"answer_format": "integer",
|
||||
"reference_solution": "Maintain the cached keys ordered from least to most recently used, for example with a hash map plus a doubly linked list. On a hit move the key to the recent end; on a miss evict from the old end when the cache is full, then add the key at the recent end. Count the hits."
|
||||
},
|
||||
"rubric": {
|
||||
"principle": "A submission is first compared with the reference answer of its variant and then judged against the criteria below. This rubric defines no points and no pass mark: how criteria turn into a grade is decided by the versioned grading policy.",
|
||||
"criteria": [
|
||||
{
|
||||
"id": "correct_answer",
|
||||
"description": "The submitted number equals the reference answer of the variant."
|
||||
},
|
||||
{
|
||||
"id": "recency_on_hit",
|
||||
"description": "A hit refreshes the recency of the key, so it is evicted later."
|
||||
},
|
||||
{
|
||||
"id": "eviction_order",
|
||||
"description": "On a miss in a full cache the least recently used key is evicted before the new key is stored."
|
||||
},
|
||||
{
|
||||
"id": "approach",
|
||||
"description": "The solution names a structure that makes lookup and recency updates cheap, or justifies a simple list for the input sizes."
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "backend-job-dependency-order",
|
||||
"version": 1,
|
||||
"specialization": "scheduling",
|
||||
"title": "Smallest valid job execution order",
|
||||
"seed_generator": {
|
||||
"algorithm": "dependency_order.v1",
|
||||
"parameters": {
|
||||
"tasks": {
|
||||
"min": 5,
|
||||
"max": 9
|
||||
},
|
||||
"links": {
|
||||
"min": 4,
|
||||
"max": 14
|
||||
}
|
||||
},
|
||||
"statement_template": "A worker runs {{.tasks}} jobs numbered from 1 to {{.tasks}}, one at a time. A dependency A->B means job A must finish before job B starts. The dependencies are: {{.dependencies}}. The dependencies contain no cycle, so at least one valid order exists. Among all execution orders that respect every dependency, choose the one that is smallest when compared number by number from the first position. Write that order as job numbers separated by single spaces."
|
||||
},
|
||||
"answer_key": {
|
||||
"answer_format": "integer_sequence",
|
||||
"reference_solution": "Count unmet dependencies for every job. Repeatedly start the smallest-numbered job whose count is zero, then lower the counts of the jobs that depended on it. A priority queue keeps the choice cheap; the dependencies never form a cycle."
|
||||
},
|
||||
"rubric": {
|
||||
"principle": "A submission is first compared with the reference answer of its variant and then judged against the criteria below. This rubric defines no points and no pass mark: how criteria turn into a grade is decided by the versioned grading policy.",
|
||||
"criteria": [
|
||||
{
|
||||
"id": "correct_answer",
|
||||
"description": "The submitted sequence equals the reference answer of the variant."
|
||||
},
|
||||
{
|
||||
"id": "all_dependencies_respected",
|
||||
"description": "Every job appears after every job it depends on."
|
||||
},
|
||||
{
|
||||
"id": "smallest_choice",
|
||||
"description": "Whenever several jobs are ready, the smallest number is chosen, which is not the same as sorting the jobs by number."
|
||||
},
|
||||
{
|
||||
"id": "approach",
|
||||
"description": "The solution explains how it finds ready jobs without rescanning all dependencies at every step, or justifies the simple scan for the input sizes."
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -512,6 +512,21 @@ Grade state rules:
|
||||
|
||||
These intervals are the accepted initial policy, stored as demo version 1 of the [product policy](#product-policy-versions); its thresholds are uncalibrated and are not a validated psychometric model. Task rotation and attempt limits reduce the value of leaked answers but do not prove resistance to hints or LLMs. Difficulty comparability needs measurement.
|
||||
|
||||
### Assessment bank
|
||||
|
||||
Implemented as storage and a loader (TASK-154), not as a candidate-facing feature: migration `backend/db/migrations/00011_create_assessment_bank.sql`, queries in `backend/db/queries/assessment_bank.sql`, the domain types in `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), the `outbound.AssessmentBankRepository` port (`port/outbound/assessment_bank.go`, reachable through `UnitOfWork.AssessmentBank()`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/assessment_bank.go`, and the loader in `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Nothing in bootstrap or the HTTP API calls it yet, and no category is open.
|
||||
|
||||
- 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`, `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.
|
||||
- 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`).
|
||||
- Category availability. `Bank.OpenCategory` records an opening in `assessment_category_openings` under a referenced policy version (`policy_versions.id`); it refuses with `grading_policy_missing` for a missing or unknown reference and with `grading_policy_not_current` unless the version is the one of the `product` family in force now, judged against the database clock of the same transaction (`clock_timestamp()`), the clock that stamps the effective time of a policy version, so the bank defines no thresholds of its own and no application clock enters the decision. The number of distinct published families that a category needs is read from that policy: `RequiredPublishedAssessmentFamilies` returns `assessment.stop_rule.max_scored_items` plus `assessment.stop_rule.seed_items`. The owner accepted this rule as a product decision on 2026-10-06. The reason: one family gives at most one item to an attempt, so a full adaptive attempt, which can run to the maximum of scored items and also carries the seed items, cannot run out of families. The insert trigger derives the same number from the stored policy document itself (the same two JSON paths; an integration test keeps the SQL and the domain equal) and checks both values as plain non-negative integers of at most four digits before the cast, so a malformed document written around the application raises the `assessment_category_openings_policy_thresholds` refusal instead of a cast error. The trigger also counts the published families, and the CHECK constraint refuses the row when they are fewer, so a call written around the usecase cannot open a category with a lower requirement. The opening stores the policy version, the operator (`operator:<handle>`), and the required and counted families, and is never edited. Availability is live: `Bank.CategoryAvailability` returns the current opening only while the published families counted now still reach the opening's requirement, and otherwise refuses with `coverage_insufficient` (or `ErrAssessmentCategoryNotOpen` without an opening), so a retirement can close a category. It also refuses with `grading_policy_not_current` when the opening's policy version is no longer the one in force, so a policy change requires a new opening. The table checks the policy reference in the trigger instead of a foreign key, because PostgreSQL refuses TRUNCATE of a referenced table before the `policy_versions` trigger can refuse it with its own error. `ListFamilies` pages by (key, version) cursor with a hard limit of 200.
|
||||
- Demo bundle. `backend/testdata/assessment/backend_demo_bundle.json` holds four original practice problems for the category `backend`. They are an AI-generated draft (author `ai:claude-draft`) with a pending review and no reviewer, so the loader imports them as drafts, publication is refused, and the category stays closed. No human has reviewed the statements, solutions, rubrics, or difficulty; the bundle makes no validity or calibration claim. A real review produces a new version of the families that carries the approval.
|
||||
- Not implemented: authorship and review of a real task bank, blueprints per specialty and grade, selection of tasks for an attempt, the storage of attempts and answers, grading, an HTTP or admin interface, authenticated reviewer and operator identities, and a wiring of the loader in bootstrap.
|
||||
|
||||
## Matching and explanations
|
||||
|
||||
Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent.
|
||||
|
||||
@@ -179,6 +179,10 @@ At startup the backend publishes `domain.DemoProductPolicyV1()` as version 1 of
|
||||
|
||||
A record that depends on policy values adds `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)`, stores the version it used, and reads it back by ID; do not recompute an existing record through `GetEffective`. Tests use their own values and do not stand in for the demo policy. Since `product` is the only family and the table refuses TRUNCATE, the integration tests give every case its own database. A new document layout needs a new `schema_version` and decoder; do not edit the golden document in `backend/internal/domain/policy_test.go` to accept a changed canonical form. See [ARCHITECTURE.md](ARCHITECTURE.md#product-policy-versions).
|
||||
|
||||
### 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. 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
|
||||
|
||||
The relay moves committed `outbox_events` rows to Kafka. The loop lives in `backend/internal/worker/outboxrelay/` and its backoff in `backend/internal/worker/retry/`; it depends on the `outbound.OutboxRelayStore` and `outbound.EventPublisher` ports in `backend/internal/port/outbound/outbox_relay.go`. `postgres.OutboxRelayStore` runs the claim transaction with the `LockPendingOutboxEvents` and `MarkOutboxEventsPublished` queries from `backend/db/queries/outbox.sql`, and `kafka.Publisher` in `backend/internal/adapter/secondary/kafka/` builds the record envelope, provisions the topic, and produces with franz-go. `bootstrap.newOutboxRelay` creates the relay with its own PostgreSQL pool of at most two connections and its own Kafka client, and the application runs it while the HTTP servers run. Product code never calls the relay: a usecase only appends events with `UnitOfWork.Outbox()` in its business transaction.
|
||||
|
||||
@@ -312,6 +312,26 @@ Unit tests (`make -C backend test`) cover the organization rules without a datab
|
||||
|
||||
`TestPostgresMigrations` rolls migration 00010 back with the others, checks that its three tables and its function disappear while the identity tables stay, and checks them again after the second migration. The tests that truncate `users` name `usersDependentTables` (identity, delivery, consent, and organization tables), the one list to extend when a migration adds a table that references users. The suite does not cover the usecases, the handlers, the session and CSRF mapping, or the claim that the contract is enforced end to end, because none of them exists yet; the atomicity of the single-statement read of the organization with its representatives is not proven by a test, because the window between two statements cannot be reproduced deterministically.
|
||||
|
||||
## 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. 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:
|
||||
|
||||
- Two versions of one family are imported and version 1 is read back with its original key, while version 2 has a different key; a repeated import changes nothing, the same version with other content and a skipped version number are refused with reasons, and raw SQL cannot edit the key, the version, or the review, delete, or truncate (SQLSTATE 23000 on `assessment_families_immutable`).
|
||||
- One seed gives the same statement and reference answer from the stored version, and a different seed keeps the rubric of every demo family.
|
||||
- The demo bundle imports as drafts; publishing each family is refused with `reviewer_missing`, the table refuses publication without an approved review, and opening `backend` is refused with `coverage_insufficient` and stores no opening.
|
||||
- An opening without a policy reference, with an unknown one, or with a policy version that is not the one in force is refused with the matching reason.
|
||||
- A test bundle that carries an approved review by a reviewer who is not its author (a fixture of the loader rules, not demo content) is published one family at a time; the category opens only when the published families reach the policy's `max_scored_items` plus `seed_items`; the opening records the policy version, the operator, and the counts, the required number the database derived equals the one the domain computes, and the opening cannot be edited. Retiring one family afterwards makes the availability read refuse with `coverage_insufficient`. A published version cannot be published again, can be retired once, and cannot move backward.
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
`TestPostgresMigrations` rolls migration 00011 back with the others and checks that its two tables and five functions disappear while the policy table stays. The suite proves the storage and loader rules only: it does not validate the content of the demo bundle, task difficulty, or any grade, it does not prove the serialization of concurrent publications beyond the held-lock case, and it does not cover a candidate-facing flow, because none exists yet. Integration tests need Docker.
|
||||
|
||||
## Future software validation
|
||||
|
||||
Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter.
|
||||
|
||||
@@ -512,6 +512,21 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
Эти интервалы - принятая начальная политика, сохраненная как демонстрационная версия 1 [продуктовой политики](#версии-продуктовой-политики); ее пороги не откалиброваны и не являются проверенной психометрической моделью. Ротация задач и лимиты попыток уменьшают пользу утечки, но не доказывают защиту от подсказок или LLM. Уровни сложности нужно измерить.
|
||||
|
||||
### Банк заданий оценки
|
||||
|
||||
Реализованы хранилище и загрузчик (TASK-154), а не функция для кандидата: миграция `backend/db/migrations/00011_create_assessment_bank.sql`, запросы в `backend/db/queries/assessment_bank.sql`, доменные типы в `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), порт `outbound.AssessmentBankRepository` (`port/outbound/assessment_bank.go`, доступен через `UnitOfWork.AssessmentBank()`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/assessment_bank.go` и загрузчик в `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Bootstrap и HTTP API его пока не вызывают, и ни одна категория не открыта.
|
||||
|
||||
- Версия семейства. Одна строка `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`, `dependency_order.v1`), диапазоны его параметров и шаблон условия. Seed выбирает вариант: одинаковые версия и seed всегда дают одинаковые условие и эталонный ответ (источник псевдослучайных чисел - SplitMix64, записанный в домене, поэтому варианты воспроизводимы между версиями Go; golden-тесты фиксируют по одному условию и ответу на алгоритм), а рубрика - свойство семейства, поэтому seed ее не меняет. Эталонный ответ считает решатель алгоритма; для него есть unit-тесты с посчитанными вручную случаями. Реестр только растет: измененный алгоритм получает новое имя, потому что сохраненные версии ссылаются на старое.
|
||||
- Шаблоны условий. Шаблон - обычный текст с подстановками `{{.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`).
|
||||
- Доступность категории. `Bank.OpenCategory` записывает открытие в `assessment_category_openings` под указанной версией политики (`policy_versions.id`); отказ `grading_policy_missing` для отсутствующей или неизвестной ссылки и `grading_policy_not_current`, если версия не действует сейчас для семейства `product`; "сейчас" берется по часам базы данных в той же транзакции (`clock_timestamp()`), теми же часами, которые ставят время вступления в силу версии политики, поэтому банк не задает собственных порогов и часы приложения в решении не участвуют. Число различных опубликованных семейств, которое нужно категории, читается из этой политики: `RequiredPublishedAssessmentFamilies` возвращает `assessment.stop_rule.max_scored_items` плюс `assessment.stop_rule.seed_items`. Это правило принято владельцем как продуктовое решение 2026-10-06. Причина: одно семейство дает в попытку не больше одного задания, поэтому полная адаптивная попытка, которая может дойти до максимума оцениваемых заданий и еще несет seed-задания, не может остаться без семейств. Триггер вставки сам выводит то же число из сохраненного документа политики (те же два JSON-пути; интеграционный тест держит SQL и домен равными) и проверяет оба значения как неотрицательные целые не длиннее четырех цифр до приведения типа, поэтому некорректный документ, записанный в обход приложения, дает отказ `assessment_category_openings_policy_thresholds`, а не ошибку приведения. Триггер также считает опубликованные семейства, а CHECK-ограничение отклоняет строку, если их меньше, поэтому вызов в обход usecase не откроет категорию с заниженным требованием. Открытие хранит версию политики, оператора (`operator:<handle>`), требуемое и посчитанное число семейств и не редактируется. Доступность живая: `Bank.CategoryAvailability` возвращает текущее открытие, только пока опубликованных сейчас семейств все еще не меньше требования открытия, иначе отказ `coverage_insufficient` (или `ErrAssessmentCategoryNotOpen`, если открытия нет), поэтому вывод из обращения может закрыть категорию. Он же отказывает с `grading_policy_not_current`, если версия политики открытия больше не действует, поэтому смена политики требует нового открытия. Таблица проверяет ссылку на политику в триггере, а не внешним ключом, потому что PostgreSQL отклоняет TRUNCATE таблицы, на которую есть ссылка, раньше, чем триггер `policy_versions` успевает отклонить его своей ошибкой. `ListFamilies` листает по курсору (ключ, версия) с жестким пределом 200.
|
||||
- Демонстрационный пакет. `backend/testdata/assessment/backend_demo_bundle.json` содержит четыре оригинальные практические задачи категории `backend`. Это черновик, созданный ИИ (автор `ai:claude-draft`), с рецензией `pending` и без рецензента, поэтому загрузчик импортирует их черновиками, публикация отклоняется, а категория остается закрытой. Условия, решения, рубрики и сложность никто из людей не проверял; пакет не заявляет ни валидности, ни калибровки. Настоящая рецензия порождает новую версию семейств с одобрением.
|
||||
- Не реализовано: авторство и рецензирование настоящего банка, blueprint по специализации и уровню, выбор задач для попытки, хранение попыток и ответов, проверка ответов, HTTP- или административный интерфейс, аутентифицированные личности рецензентов и операторов и подключение загрузчика в bootstrap.
|
||||
|
||||
## Подбор и объяснение
|
||||
|
||||
До ранжирования Go применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия.
|
||||
|
||||
@@ -179,6 +179,10 @@ goose выполняет каждую миграцию в отдельной т
|
||||
|
||||
Запись, которая зависит от значений политики, добавляет `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)`, хранит использованную версию и читает ее обратно по ID; не пересчитывайте существующую запись через `GetEffective`. Тесты используют собственные значения и не подменяют демонстрационную политику. Поскольку `product` - единственное семейство, а таблица отклоняет TRUNCATE, интеграционные тесты дают каждому случаю отдельную базу данных. Новой структуре документа нужны новая `schema_version` и свой декодер; не меняйте golden-документ в `backend/internal/domain/policy_test.go`, чтобы принять измененную каноническую форму. См. [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-тест; зарегистрированный алгоритм не меняйте. Шаблоны условий - обычный текст только с подстановками `{{.name}}`. Демонстрационный пакет в `backend/testdata/assessment/` - непроверенный черновик ИИ: не заполняйте в нем рецензента, чтобы открыть категорию. См. [ARCHITECTURE.md](ARCHITECTURE.md#банк-заданий-оценки).
|
||||
|
||||
### Relay outbox
|
||||
|
||||
Relay переносит зафиксированные строки `outbox_events` в Kafka. Цикл находится в `backend/internal/worker/outboxrelay/`, а его backoff - в `backend/internal/worker/retry/`; он зависит от портов `outbound.OutboxRelayStore` и `outbound.EventPublisher` в `backend/internal/port/outbound/outbox_relay.go`. `postgres.OutboxRelayStore` выполняет транзакцию захвата запросами `LockPendingOutboxEvents` и `MarkOutboxEventsPublished` из `backend/db/queries/outbox.sql`, а `kafka.Publisher` в `backend/internal/adapter/secondary/kafka/` собирает конверт записи, создает топик и публикует через franz-go. `bootstrap.newOutboxRelay` создает relay с собственным пулом PostgreSQL не больше чем на два соединения и собственным клиентом Kafka, а приложение запускает его, пока работают HTTP-серверы. Продуктовый код relay не вызывает: usecase только добавляет события через `UnitOfWork.Outbox()` в своей бизнес-транзакции.
|
||||
|
||||
@@ -312,6 +312,26 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
|
||||
|
||||
`TestPostgresMigrations` откатывает миграцию 00010 вместе с остальными, проверяет, что три ее таблицы и функция исчезают, а таблицы identity остаются, и проверяет их снова после второго применения. Тесты, очищающие `users`, называют `usersDependentTables` (таблицы identity, доставок, согласий и организаций) - единственный список, который нужно расширять, когда миграция добавляет таблицу со ссылкой на users. Набор не покрывает usecase, обработчики, сопоставление сессии и CSRF и утверждение, что контракт соблюдается сквозным путем, потому что ничего из этого еще нет; атомарность чтения организации с представителями одним оператором тестом не доказана, потому что окно между двумя операторами нельзя воспроизвести детерминированно.
|
||||
|
||||
## Тесты банка заданий
|
||||
|
||||
`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` и без рецензента. С in-memory подделками репозитория и единицы работы usecase-тесты доказывают: одновременный идентичный импорт сообщает версию как неизмененную, а одновременный импорт с другим содержимым отклоняется; sentinel-ошибки гонок базы становятся отказами с подходящей причиной; публикация после взятия блокировки категории выводит из обращения более старую опубликованную версию и отклоняется, если опубликована более новая; открытие требует действующую версию политики; доступность отклоняется, когда число опубликованных семейств падает ниже требования открытия или когда версия политики открытия больше не действует; более старый одобренный черновик отклоняется, пока существует более новая версия: черновик, опубликованная или выведенная из обращения. `internal/adapter/secondary/postgres/assessment_bank_test.go` проверяет, что ограничения банка преобразуются в свои sentinel-ошибки без строки с нарушением, что страница списка вне предела падает до любого запроса и что блокировка категории отклоняется вне транзакции.
|
||||
|
||||
`TestAssessmentBank` в `backend/integration_test/assessment_bank_test.go` использует `bootstrap(t, postgresService)` и дает каждому случаю свою мигрированную базу:
|
||||
|
||||
- Две версии одного семейства импортируются, версия 1 читается с исходным ключом, а у версии 2 ключ другой; повторный импорт ничего не меняет, та же версия с другим содержимым и пропущенный номер версии отклоняются с причиной, а сырой SQL не может изменить ключ, версию или рецензию, удалить или очистить таблицу (SQLSTATE 23000 на `assessment_families_immutable`).
|
||||
- Один seed дает одинаковые условие и эталонный ответ из сохраненной версии, а другой seed сохраняет рубрику каждого демонстрационного семейства.
|
||||
- Демонстрационный пакет импортируется черновиками; публикация каждого семейства отклоняется с `reviewer_missing`, таблица отклоняет публикацию без одобренной рецензии, а открытие `backend` отклоняется с `coverage_insufficient` и не сохраняет открытия.
|
||||
- Открытие без ссылки на политику, с неизвестной ссылкой или с версией политики, которая сейчас не действует, отклоняется с подходящей причиной.
|
||||
- Тестовый пакет с одобренной рецензией рецензента, который не является автором (фикстура правил загрузчика, а не демонстрационное содержимое), публикуется по одному семейству; категория открывается, только когда опубликованных семейств становится не меньше `max_scored_items` плюс `seed_items` политики; открытие хранит версию политики, оператора и числа, требуемое число, выведенное базой, равно числу из домена, а открытие не редактируется. Вывод из обращения одного семейства после этого заставляет чтение доступности отказывать с `coverage_insufficient`. Опубликованную версию нельзя опубликовать снова, можно один раз вывести из обращения, а назад она не идет.
|
||||
- Публикация более поздней версии семейства выводит из обращения опубликованную более старую и записывает обоих операторов; публикация более старой версии при опубликованной более новой отклоняется; таблица допускает одну опубликованную версию на семейство и отклоняет перезапись записанного публикатора.
|
||||
- Транзакция, держащая блокировку категории, заставляет открытие ждать до срока, а после освобождения блокировки открытие проходит.
|
||||
- Более старый одобренный черновик нельзя опубликовать, когда существует более новая версия, в том числе выведенная из обращения. Проверки действующей политики используют часы базы данных, без сдвига часов в тесте.
|
||||
- Сырые строки политики, в документе которых нет границ оцениваемых заданий, они заданы текстом, слишком большим, дробным или отрицательным числом или нет seed-заданий, отклоняются триггером открытия отказом по порогам, а не ошибкой приведения типа; сохраненная схема хеша вне списка CHECK отклоняется, а саму схему изменить нельзя.
|
||||
- В обход usecase таблица отклоняет открытие с заниженным требованием, открытие ниже покрытия, открытие под неизвестной версией политики и название с переопределением направления текста.
|
||||
- Семейства выводятся страницами по две после курсора, каждое один раз и по порядку.
|
||||
|
||||
`TestPostgresMigrations` откатывает миграцию 00011 вместе с остальными и проверяет, что две ее таблицы и пять функций исчезают, а таблица политик остается. Набор доказывает только правила хранилища и загрузчика: он не проверяет содержимое демонстрационного пакета, сложность задач и какие-либо грейды, не доказывает сериализацию одновременных публикаций сверх случая с удерживаемой блокировкой и не покрывает сценарий кандидата, потому что его еще нет. Интеграционным тестам нужен Docker.
|
||||
|
||||
## Будущая программная валидация
|
||||
|
||||
Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером.
|
||||
|
||||
Reference in new issue
Block a user