feat(assessment): add table families that pick a variant row by seed

This commit is contained in:
shira committed 2026-10-11 08:19:17 +03:00
1 parent f1147b1885
commit 5e1db37746
16 files changed
+1023 -56

No files matched your search

+2 -1
View File
@@ -667,8 +667,9 @@ Implemented as storage and a loader, not as a candidate-facing feature: migratio
- Family version. One `assessment_families` row is one version of one family (`family_key`, `version`): category, specialization (the domain inside the category), title, author (`ai:<name>` or `operator:<handle>`), reviewer (`operator:<handle>` or NULL), `review_status` (`pending`, `approved`, `rejected`), the seed generator, the answer key, the rubric, a content hash with its `hash_scheme`, a lifecycle (`draft`, `published`, `retired`), and the operators and times of publication and retirement. The reviewer is never the author, and a review is pending exactly while there is no reviewer (CHECK constraints; the domain applies the same rules). The reviewer in a bundle and the operator of a publication are declared values, not authenticated identities, until reviewer and operator accounts exist.
- Immutability. The content of a stored version never changes: the trigger `assessment_families_guard_update` refuses every UPDATE that changes a column other than the lifecycle columns (`lifecycle`, `published_at`, `published_by`, `retired_at`, `retired_by`), and `assessment_families_refuse_removal` refuses DELETE and TRUNCATE, all with SQLSTATE 23000 and the constraint name `assessment_families_immutable`, which the adapter maps to `outbound.ErrAssessmentFamilyImmutable`. The lifecycle moves only forward (draft, published, retired), the trigger sets the times and keeps the publisher through a retirement, and a version is published only with an approved review by a reviewer (`assessment_families_published_requires_review`). A change is a new version with the next number; the loader accepts only version 1 for a new family and the successor of the latest version otherwise. A pending draft is never approved in place: its review is recorded by importing a new version of the family that carries the review, and the pending version stays an unpublished draft. The domain recomputes the content hash when it reads a row and returns `ErrAssessmentFamilyIntegrity` for a row changed outside the application. The hash is the SHA-256 of a canonical JSON document that holds the content without the bundle name, ID, lifecycle, and publication fields. The `hash_scheme` column (a smallint with a CHECK of the known values, one of the immutable columns) names the layout: the domain verifies a row with the hash function of the scheme the row was stored with, so a later scheme (a new function and a new CHECK value, never an edit of scheme 1) verifies new rows without invalidating old ones, and a row with an unknown scheme is refused; tests verify a row with its own scheme and pin the scheme 1 hash of a fixed input. As for `policy_versions`, a role that owns the table can still disable the triggers.
- One published version per family. A partial unique index (`assessment_families_one_published_key`) allows at most one published version of a key. `Bank.PublishFamily` retires the published older version in the same transaction and refuses with `newer_version_published` when a newer version of the key exists in any state, a draft or a retired one included, so superseded content is never put back in the bank (earlier content is published again by importing it as a new version); `Bank.ActiveFamily` reads the single published version. Coverage counts each family once.
- Seed generator and variants. A generator names a registered algorithm with a versioned name (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`), the ranges of its parameters, and a statement template. A seed selects a variant: the same version and seed always give the same statement and reference answer (the pseudo-random source is SplitMix64 written out in the domain, so variants stay reproducible across Go releases; golden tests pin one statement and answer per algorithm), and the rubric is a property of the family, so no seed changes it. The reference answer comes from the algorithm's solver, which has unit tests with hand-computed cases. The registry only grows: a changed algorithm gets a new name, because stored versions refer to the old one.
- Seed generator and variants. A generator is either algorithmic or a table (see "Table generators" below). An algorithmic generator names a registered algorithm with a versioned name (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`), the ranges of its parameters, and a statement template. A seed selects a variant: the same version and seed always give the same statement and reference answer (the pseudo-random source is SplitMix64 written out in the domain, so variants stay reproducible across Go releases; golden tests pin one statement and answer per algorithm), and the rubric is a property of the family, so no seed changes it. The reference answer comes from the algorithm's solver, which has unit tests with hand-computed cases. The registry only grows: a changed algorithm gets a new name, because stored versions refer to the old one.
- Choice answer format. The answer format `choice` offers options instead of asking for a value. A choice variant stores its options and the key on the server: the frozen variant holds the options in presentation order, each with an opaque ID and a text, and the reference answer is the decimal index of the correct one. The candidate receives the option IDs and texts in that order (`ChoiceItemContent` of the public contract, `multiple` false) and nothing else: not the index, not the seed, and not how a distractor was made (the allowlisted projection and the response snapshot are checked for this). The seed decides the order of the options and the IDs: the order is a seeded Fisher-Yates shuffle, and each ID is drawn after the shuffle, so an ID says nothing about the position or the correctness of its option; the same family version and seed give the same options in the same order. A choice answer names the selected option IDs (`{"format":"choice","option_ids":[...]}`); the server grades it against the key. An ID that is not an option of the item, a second option, or an answer of another format is an invalid answer (400), not a wrong one. Distractors come from the algorithm, not from chance: a choice algorithm returns the correct value and the wrong values of known error models, and the shared code removes duplicates and the correct value, lets the seed choose among the mistakes, and tops up from plausible nearby values only when the mistakes give too few distinct ones. The registered `lru_hits_choice.v1` asks for the number of cache hits and offers wrong counts from an off-by-one count in either direction, counting misses instead of hits, a cache where a hit does not renew a key (FIFO), a cache that evicts the most recently used key, and a capacity off by one in either direction; its parameter bounds guarantee enough distinct values. The signals observe a choice answer as an answer of a small answer space, like an integer (`domain.SignalAnswerFormat`), so the observation column keeps its two classes. A choice variant is stored with an `Options` field in the frozen variant document, which is omitted for the other formats, so stored attempts keep decoding.
- Table generators. A family can declare its variants as data instead of naming an algorithm: `seed_generator.table.rows` is a list of rows, each with `values` (the text of every placeholder), an `answer`, and for the answer format `choice` the `distractors`. The seed selects one row (SplitMix64 under the fixed name `table.v1`, so the selection is reproducible and changes only with a new name), the statement template substitutes the row values exactly as it does for an algorithm (the same text and `{{.name}}` whitelist, so a table cannot carry code), and the answer is the one written in the row: nothing is computed from the table. The table is validated at import, and a failure names the row by its zero-based index in the array (`rows[2]`) without quoting content: 2 to 500 rows, 1 to 16 columns with lowercase names, the same columns in every row, values of 1 to 1000 bytes without control or format characters, no repeated row, every column present in the template and no other placeholder, a rendered statement of at most 8 KiB for every row, at most 64 KiB of text in all, an answer format of `integer` (a canonical decimal integer of at most 15 digits, so a JSON number carries it exactly, and no distractors) or `choice` (a one-line answer of at most 500 bytes and 1 to 9 distinct distractors that do not repeat the answer). The answer key must name the same format. A table family has no algorithm and no parameters, is hashed with scheme 2, and is as immutable as any version. Algorithms in Go remain for tasks whose answer must be computed. The variant keeps the row index as a private parameter `row`.
- Statement templates. A template is plain text with `{{.name}}` placeholders and nothing else: the text/template parser reads it without functions, and a whitelist walk refuses every node except text and a single field action (so `define`, `template`, `block`, `range`, `with`, `if`, variables, pipelines, and calls such as `printf` are refused). The loader renders the placeholders itself, never runs the template engine, and caps the template at 2000 bytes and the rendered statement at 8 KiB. Every placeholder must belong to the algorithm, and the template must contain the placeholders the answer depends on (the input data and the answer-relevant parameters), so a statement always shows the input. A bundle is validated fully at import, with probe renders at the lowest parameter values and, for eight seeds each, at the highest values (the largest inputs) and at drawn values, so a template close to the size cap cannot pass on one lucky seed; reading a stored row does not repeat the probes, because the content hash proves the content is the one that passed them. Titles, templates, and rubric texts refuse control characters, Unicode format characters (for example bidirectional overrides), and the line and paragraph separators U+2028 and U+2029; the title CHECK constraint also refuses the common ones.
- Rubric. A rubric holds a principle and a list of criteria. It has no points, weights, or pass mark; how criteria become a grade is not decided in the bank.
- Lifecycle and the loader. `Bank.ImportBundle` stores every family of a bundle as a draft in one transaction and never publishes, whatever the review says; importing the same bundle again, also concurrently, reports the versions as unchanged. `Bank.PublishFamily` and `Bank.RetireFamily` take the operator, and refuse with a reason (`reviewer_missing`, `review_not_approved`, `not_draft`, `not_published`, `newer_version_published`); the refusal is a `*domain.AssessmentRefusalError` that carries the reason, and the sentinels of a race that the database decided (a lifecycle step that lost to another, a missing approved review, insufficient coverage) become the same refusals. Publishing, retiring, and opening take a transaction-scoped advisory lock of the category first, so they run one after another per category; `LockCategory` works only inside a transaction (the repository of a unit of work takes it, the standalone store returns `ErrAssessmentLockOutsideTransaction`).
+1 -1
View File
@@ -183,7 +183,7 @@ A record that depends on policy values adds `policy_version_id uuid NOT NULL REF
### Assessment bank
Migration `00011_create_assessment_bank.sql` creates `assessment_families` (immutable family versions) and `assessment_category_openings`; the queries are in `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` is available through `UnitOfWork.AssessmentBank()` and `postgres.AssessmentBankStore` outside a transaction; `assessment.Bank` imports a `Bundle`, publishes a version as an operator (retiring the published older one), retires it, opens a category under the policy version in force, reports live availability, and generates a variant of a seed. To change a family, import a new version; a stored version is never edited, and a pending draft is approved by importing a new version that carries the review. A new seed algorithm gets a new versioned name in `domain/assessment_algorithms.go`, its required placeholders, a solver test with hand-computed cases, and a golden test; never change a registered algorithm. An algorithm with the answer format `choice` sets `generateChoice` instead of `generate` and returns the correct value with the wrong values of named error models (`lru_hits_choice.v1` is the example); its tests recompute the error models from the statement. The demo bundle in `backend/testdata/assessment/` is an unreviewed AI draft: do not fill in its reviewer to open the category. See [ARCHITECTURE.md](ARCHITECTURE.md#assessment-bank).
Migration `00011_create_assessment_bank.sql` creates `assessment_families` (immutable family versions) and `assessment_category_openings`; the queries are in `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` is available through `UnitOfWork.AssessmentBank()` and `postgres.AssessmentBankStore` outside a transaction; `assessment.Bank` imports a `Bundle`, publishes a version as an operator (retiring the published older one), retires it, opens a category under the policy version in force, reports live availability, and generates a variant of a seed. To change a family, import a new version; a stored version is never edited, and a pending draft is approved by importing a new version that carries the review. A new seed algorithm gets a new versioned name in `domain/assessment_algorithms.go`, its required placeholders, a solver test with hand-computed cases, and a golden test; never change a registered algorithm. An algorithm with the answer format `choice` sets `generateChoice` instead of `generate` and returns the correct value with the wrong values of named error models (`lru_hits_choice.v1` is the example); its tests recompute the error models from the statement. A family whose variants are fixed data uses a table generator instead of an algorithm: `seed_generator.table.rows` with `values`, `answer`, and for `choice` the `distractors`, validated at import with the row index in the error and stored with hash scheme 2; use a Go algorithm when the answer must be computed. Migration `00047_allow_table_hash_scheme.sql` allows scheme 2. Statement templates are plain text with `{{.name}}` placeholders only. The demo bundle in `backend/testdata/assessment/` is an unreviewed AI draft: do not fill in its reviewer to open the category. See [ARCHITECTURE.md](ARCHITECTURE.md#assessment-bank).
### Outbox relay
+3 -2
View File
@@ -498,7 +498,7 @@ Unit tests (`make -C backend test`) check the visibility rules without a databas
## Assessment bank tests
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go`, and `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) check without a database: invalid family content is refused (review rules, unknown algorithm, parameter bounds, answer format mismatch, rubric shape, Unicode format characters); statement templates accept only text and `{{.name}}` placeholders, and a nested `define` bomb, a `printf` width bomb, a `range` over a number, and a recursive `block` are refused within a second without being run; a template without the placeholders its answer depends on is refused; the rendered statement size is bounded; a changed stored document fails the hash check; each publication refusal names its reason; one seed gives one variant while the rubric stays the same across seeds; golden tests pin the exact statement and reference answer of a fixed seed for each of the four algorithms and the scheme 1 content hash of a fixed input; a row is verified with the hash scheme it was stored with (a test registers a second scheme, and a hash of one scheme under the name of the other, or an unknown scheme, is refused); a template whose statement reaches the size bound for one probe seed only is refused at import, because the highest parameter values are rendered for eight seeds; the line and paragraph separators are refused like format characters; the four solvers match hand-computed cases; the coverage required for an opening is `max_scored_items` plus `seed_items` of the policy; and the demo bundle parses as an AI draft with a pending review and no reviewer. `assessment_choice_test.go` covers the choice format without a database: the same seed gives identical options, IDs, and order, and across 400 seeds the correct option appears at every position; every distractor of `lru_hits_choice.v1` is recomputed from the statement as the result of a named error model (and the nearby fill-in is used only when the models give fewer than three distinct values), the options never repeat a text, the cache models match hand-computed cases and the LRU model equals the solver of `lru_hits.v1`, and a golden test pins the options, their IDs, and the key of one seed; the correct option, a wrong option, an option of no item, two options, a number answer for a choice item, and a choice answer for an integer item are graded or refused as stated, the candidate projection holds only the opaque IDs and texts, and a broken key or repeated option of a frozen variant is refused.
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go`, and `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) check without a database: invalid family content is refused (review rules, unknown algorithm, parameter bounds, answer format mismatch, rubric shape, Unicode format characters); statement templates accept only text and `{{.name}}` placeholders, and a nested `define` bomb, a `printf` width bomb, a `range` over a number, and a recursive `block` are refused within a second without being run; a template without the placeholders its answer depends on is refused; the rendered statement size is bounded; a changed stored document fails the hash check; each publication refusal names its reason; one seed gives one variant while the rubric stays the same across seeds; golden tests pin the exact statement and reference answer of a fixed seed for each of the four algorithms and the scheme 1 content hash of a fixed input; a row is verified with the hash scheme it was stored with (a test registers a second scheme, and a hash of one scheme under the name of the other, or an unknown scheme, is refused); a template whose statement reaches the size bound for one probe seed only is refused at import, because the highest parameter values are rendered for eight seeds; the line and paragraph separators are refused like format characters; the four solvers match hand-computed cases; the coverage required for an opening is `max_scored_items` plus `seed_items` of the policy; and the demo bundle parses as an AI draft with a pending review and no reviewer. `assessment_choice_test.go` covers the choice format without a database: the same seed gives identical options, IDs, and order, and across 400 seeds the correct option appears at every position; every distractor of `lru_hits_choice.v1` is recomputed from the statement as the result of a named error model (and the nearby fill-in is used only when the models give fewer than three distinct values), the options never repeat a text, the cache models match hand-computed cases and the LRU model equals the solver of `lru_hits.v1`, and a golden test pins the options, their IDs, and the key of one seed; the correct option, a wrong option, an option of no item, two options, a number answer for a choice item, and a choice answer for an integer item are graded or refused as stated, the candidate projection holds only the opaque IDs and texts, and a broken key or repeated option of a frozen variant is refused. `assessment_table_test.go` covers table families: rows are selected by seed, the answer is the written one, the selection of fixed seeds is pinned, each of 39 format errors (missing column, repeated row, bad answer, duplicate distractor, oversized statement, a call or pipeline in the template, an algorithm beside a table, and so on) is refused with the index of the row, the scheme 2 hash of a fixed table is pinned against its canonical document, any change of the table changes the hash, scheme 1 and scheme 2 each refuse the other kind of generator, and an edited stored table fails the integrity check. `bundle_test.go` reads a table bundle and refuses a row with an unknown field. With in-memory fakes of the repository and the unit of work, the usecase tests prove that a concurrent identical import reports the version as unchanged and a concurrent import with other content is refused, that the sentinels of database races become refusals with the matching reason, that publishing retires the older published version after taking the category lock and is refused when a newer one is published, that opening requires the policy version in force, that availability is refused when the published count falls below the opening's requirement or when the opening's policy version is no longer in force, and that an older approved draft is refused while a newer version exists as a draft, a published, or a retired one. `internal/adapter/secondary/postgres/assessment_bank_test.go` checks that the bank constraints map to their sentinels without the failing row, that a list page outside its limit fails before any statement, and that the category lock is refused outside a transaction.
`TestAssessmentBank` in `backend/integration_test/assessment_bank_test.go` uses `bootstrap(t, postgresService)` and gives every case its own migrated database:
@@ -510,7 +510,8 @@ Unit tests (`make -C backend test`) check the visibility rules without a databas
- Publishing a later version of a family retires the published older version and records both operators; publishing an older version while a newer one is published is refused; the table allows one published version per family and refuses a rewrite of the recorded publisher.
- A transaction that holds the category lock makes an opening wait until the deadline, and the opening succeeds after the lock is released.
- An older approved draft cannot be published once a newer version exists, also when that version is retired. Policy-in-force checks use the database clock, with no clock offset in the test.
- `TestAssessmentChoiceFamiliesAreServedAndGradedOverHTTP` in `backend/integration_test/assessment_choice_http_test.go` runs a real attempt over a bank of a choice algorithm and an integer algorithm: every item the candidate receives has only the allowlisted fields (for a choice the option IDs and texts in the stored order, and no key, seed, or distractor field), an option of no item and two options are refused with 400, a wrong choice scores nothing and a right one scores through the key, the result matches the expected points, and every answer left a signal observation.
- A bundle with a table family and a choice family is imported with hash scheme 2 for the tables and scheme 1 for the algorithm, imported again as unchanged, and the stored rows generate the same variants twice; a raw edit of a stored table is refused as an edit of a stored version.
- `TestAssessmentChoiceAndTableFamiliesAreServedAndGradedOverHTTP` in `backend/integration_test/assessment_choice_http_test.go` runs a real attempt over a bank of a choice algorithm, an integer table, and a choice table: every item the candidate receives has only the allowlisted fields (for a choice the option IDs and texts in the stored order, and no key, seed, or distractor field), an option of no item and two options are refused with 400, a wrong choice scores nothing and a right one scores through the key, the result matches the expected points, and every answer left a signal observation.
- Raw policy rows whose document lacks the scored item bounds or holds them as text, as an oversized, fractional, or negative number, or without the seed items are refused by the opening trigger with the thresholds refusal, not with a cast error; a stored hash scheme outside the CHECK list is refused, and the scheme cannot be edited.
- Written around the usecase, an opening that claims a lower requirement, an opening below the coverage, an opening under an unknown policy version, and a title with a bidirectional override are refused by the table.
- Families are listed in pages of two after a cursor, each once and in order.
+2 -1
View File
@@ -667,8 +667,9 @@ contact_grant относится к паре кандидат-компания
- Версия семейства. Одна строка `assessment_families` - одна версия одного семейства (`family_key`, `version`): категория, специализация (область внутри категории), название, автор (`ai:<name>` или `operator:<handle>`), рецензент (`operator:<handle>` или NULL), `review_status` (`pending`, `approved`, `rejected`), генератор по seed, ключ ответа, рубрика, хеш содержимого с его `hash_scheme`, жизненный цикл (`draft`, `published`, `retired`) и операторы и время публикации и вывода из обращения. Рецензент не бывает автором, а рецензия остается `pending`, пока рецензента нет (CHECK-ограничения; домен применяет те же правила). Рецензент в пакете и оператор публикации - заявленные значения, а не аутентифицированные личности, пока нет учетных записей рецензентов и операторов.
- Неизменяемость. Содержимое сохраненной версии не меняется: триггер `assessment_families_guard_update` отклоняет любой UPDATE, который меняет колонки кроме колонок жизненного цикла (`lifecycle`, `published_at`, `published_by`, `retired_at`, `retired_by`), а `assessment_families_refuse_removal` отклоняет DELETE и TRUNCATE, все с SQLSTATE 23000 и именем ограничения `assessment_families_immutable`, которое адаптер преобразует в `outbound.ErrAssessmentFamilyImmutable`. Жизненный цикл идет только вперед (draft, published, retired), время ставит триггер и он же сохраняет публикатора при выводе из обращения, а версия публикуется только с одобренной рецензией рецензента (`assessment_families_published_requires_review`). Изменение - это новая версия со следующим номером: загрузчик принимает версию 1 для нового семейства и преемника последней версии для существующего. Черновик с рецензией `pending` никогда не одобряется на месте: рецензия записывается импортом новой версии семейства, которая ее несет, а версия `pending` остается неопубликованным черновиком. Домен пересчитывает хеш содержимого при чтении строки и возвращает `ErrAssessmentFamilyIntegrity`, если строку изменили вне приложения. Хеш - это SHA-256 канонического JSON-документа, который содержит содержимое без имени пакета, ID, жизненного цикла и полей публикации. Колонка `hash_scheme` (smallint с CHECK известных значений, одна из неизменяемых колонок) называет формат: домен проверяет строку хеш-функцией той схемы, с которой строка сохранена, поэтому следующая схема (новая функция и новое значение CHECK, а не правка схемы 1) проверяет новые строки и не ломает старые, а строка с неизвестной схемой отклоняется; тесты проверяют строку ее собственной схемой и фиксируют хеш схемы 1 для заданного входа. Как и для `policy_versions`, роль-владелец таблицы все еще может отключить триггеры.
- Одна опубликованная версия на семейство. Частичный уникальный индекс (`assessment_families_one_published_key`) допускает не более одной опубликованной версии ключа. `Bank.PublishFamily` в той же транзакции выводит из обращения опубликованную более старую версию и отказывает с `newer_version_published`, если существует более новая версия ключа в любом состоянии, включая черновик и выведенную из обращения, поэтому устаревшее содержимое не возвращается в банк (прежнее содержимое публикуется снова импортом как новая версия); `Bank.ActiveFamily` читает единственную опубликованную версию. Покрытие считает каждое семейство один раз.
- Генератор и варианты. Генератор называет зарегистрированный алгоритм с версионным именем (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`), диапазоны его параметров и шаблон условия. Seed выбирает вариант: одинаковые версия и seed всегда дают одинаковые условие и эталонный ответ (источник псевдослучайных чисел - SplitMix64, записанный в домене, поэтому варианты воспроизводимы между версиями Go; golden-тесты фиксируют по одному условию и ответу на алгоритм), а рубрика - свойство семейства, поэтому seed ее не меняет. Эталонный ответ считает решатель алгоритма; для него есть unit-тесты с посчитанными вручную случаями. Реестр только растет: измененный алгоритм получает новое имя, потому что сохраненные версии ссылаются на старое.
- Генератор и варианты. Генератор бывает алгоритмическим или табличным (см. "Табличные генераторы" ниже). Алгоритмический генератор называет зарегистрированный алгоритм с версионным именем (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`), диапазоны его параметров и шаблон условия. Seed выбирает вариант: одинаковые версия и seed всегда дают одинаковые условие и эталонный ответ (источник псевдослучайных чисел - SplitMix64, записанный в домене, поэтому варианты воспроизводимы между версиями Go; golden-тесты фиксируют по одному условию и ответу на алгоритм), а рубрика - свойство семейства, поэтому seed ее не меняет. Эталонный ответ считает решатель алгоритма; для него есть unit-тесты с посчитанными вручную случаями. Реестр только растет: измененный алгоритм получает новое имя, потому что сохраненные версии ссылаются на старое.
- Формат ответа с выбором. Формат ответа `choice` предлагает варианты вместо ввода значения. Вариант с выбором хранит варианты ответа и ключ на сервере: замороженный вариант содержит варианты в порядке показа, у каждого непрозрачный ID и текст, а эталонный ответ - десятичный индекс правильного. Кандидат получает ID и тексты вариантов в этом порядке (`ChoiceItemContent` публичного контракта, `multiple` равно false) и ничего больше: ни индекса, ни seed, ни того, как сделан отвлекающий вариант (для этого проверяются проекция по белому списку и снимок ответа). Seed определяет порядок вариантов и ID: порядок - перемешивание Фишера-Йетса по seed, а каждый ID выбирается после перемешивания, поэтому ID ничего не говорит о позиции и правильности варианта; одинаковые версия семейства и seed дают одинаковые варианты в одинаковом порядке. Ответ с выбором называет выбранные ID (`{"format":"choice","option_ids":[...]}`), сервер оценивает его по ключу. ID, которого нет среди вариантов задания, второй вариант или ответ другого формата - это некорректный ответ (400), а не неверный. Отвлекающие варианты дает алгоритм, а не случай: алгоритм с выбором возвращает правильное значение и неверные значения известных моделей ошибок, а общий код убирает повторы и правильное значение, дает seed выбрать среди ошибок и добирает правдоподобными соседними значениями, только если ошибки дали слишком мало различных. Зарегистрированный `lru_hits_choice.v1` спрашивает число попаданий в кэш и предлагает неверные числа из ошибки на единицу в обе стороны, подсчета промахов вместо попаданий, кэша, где попадание не обновляет ключ (FIFO), кэша, вытесняющего самый недавний ключ, и емкости, неверной на единицу в обе стороны; границы его параметров гарантируют достаточно различных значений. Сигналы наблюдают ответ с выбором как ответ с малым пространством ответов, как целое число (`domain.SignalAnswerFormat`), поэтому колонка наблюдений сохраняет свои два класса. Вариант с выбором хранится с полем `Options` в документе замороженного варианта; для других форматов поле опускается, поэтому сохраненные попытки продолжают читаться.
- Табличные генераторы. Семейство может задать варианты данными вместо имени алгоритма: `seed_generator.table.rows` - список строк, в каждой `values` (текст каждой подстановки), `answer` и для формата ответа `choice` еще `distractors`. Seed выбирает одну строку (SplitMix64 под фиксированным именем `table.v1`, поэтому выбор воспроизводим и меняется только вместе с новым именем), шаблон условия подставляет значения строки так же, как для алгоритма (тот же текст и белый список `{{.name}}`, так что таблица не может нести код), а ответ - тот, что записан в строке: из таблицы ничего не вычисляется. Таблица проверяется при импорте, и ошибка называет строку ее индексом в массиве от нуля (`rows[2]`) без цитирования содержимого: от 2 до 500 строк, от 1 до 16 столбцов со строчными именами, одинаковые столбцы в каждой строке, значения от 1 до 1000 байт без управляющих символов и символов формата, нет повторяющихся строк, каждый столбец есть в шаблоне и других подстановок нет, готовое условие каждой строки не больше 8 КиБ, всего не больше 64 КиБ текста, формат ответа `integer` (каноническое десятичное целое не длиннее 15 цифр, которое JSON-число передает точно, и без отвлекающих вариантов) или `choice` (ответ в одну строку не длиннее 500 байт и от 1 до 9 различных отвлекающих вариантов, не повторяющих ответ). Ключ ответа должен называть тот же формат. У табличного семейства нет алгоритма и параметров, оно хешируется схемой 2 и неизменяемо, как любая версия. Алгоритмы на Go остаются для заданий, ответ которых нужно вычислять. Вариант хранит индекс строки как закрытый параметр `row`.
- Шаблоны условий. Шаблон - обычный текст с подстановками `{{.name}}` и ничем больше: парсер text/template читает его без функций, а обход по белому списку отклоняет любой узел кроме текста и одного обращения к полю (то есть `define`, `template`, `block`, `range`, `with`, `if`, переменные, конвейеры и вызовы вроде `printf` отклоняются). Загрузчик подставляет значения сам и не запускает движок шаблонов, ограничивает шаблон 2000 байтами, а готовое условие 8 КиБ. Каждая подстановка должна принадлежать алгоритму, а шаблон обязан содержать подстановки, от которых зависит ответ (входные данные и параметры, влияющие на ответ), поэтому условие всегда показывает вход. Пакет проверяется полностью при импорте, с пробными подстановками на наименьших значениях параметров и, по восемь seed каждая, на наибольших значениях (самые большие входы) и на выбранных значениях, поэтому шаблон у границы размера не пройдет из-за одного удачного seed; чтение сохраненной строки проб не повторяет, потому что хеш содержимого доказывает, что это то самое содержимое, которое их прошло. Названия, шаблоны и тексты рубрики отклоняют управляющие символы, символы формата Unicode (например, переопределения направления текста) и разделители строки и абзаца U+2028 и U+2029; CHECK-ограничение названия отклоняет самые распространенные из них.
- Рубрика. Рубрика содержит принцип и список критериев. В ней нет баллов, весов и проходного порога; как критерии превращаются в грейд, банк не решает.
- Жизненный цикл и загрузчик. `Bank.ImportBundle` сохраняет все семейства пакета как черновики в одной транзакции и никогда не публикует, что бы ни говорила рецензия; повторный импорт того же пакета, в том числе одновременный, сообщает версии как неизмененные. `Bank.PublishFamily` и `Bank.RetireFamily` принимают оператора и отказывают с причиной (`reviewer_missing`, `review_not_approved`, `not_draft`, `not_published`, `newer_version_published`); отказ - это `*domain.AssessmentRefusalError` с причиной, а sentinel-ошибки гонки, которую решила база (шаг жизненного цикла проиграл другому, нет одобренной рецензии, недостаточное покрытие), становятся теми же отказами. Публикация, вывод из обращения и открытие сначала берут транзакционную advisory-блокировку категории, поэтому выполняются по очереди в пределах категории; `LockCategory` работает только внутри транзакции (репозиторий единицы работы берет блокировку, автономное хранилище возвращает `ErrAssessmentLockOutsideTransaction`).
+1 -1
View File
@@ -183,7 +183,7 @@ goose выполняет каждую миграцию в отдельной т
### Банк заданий оценки
Миграция `00011_create_assessment_bank.sql` создает `assessment_families` (неизменяемые версии семейств) и `assessment_category_openings`; запросы лежат в `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` доступен через `UnitOfWork.AssessmentBank()` и через `postgres.AssessmentBankStore` вне транзакции; `assessment.Bank` импортирует `Bundle`, публикует версию от имени оператора (выводя из обращения опубликованную более старую), выводит ее из обращения, открывает категорию под действующей версией политики, сообщает живую доступность и генерирует вариант по seed. Чтобы изменить семейство, импортируйте новую версию; сохраненная версия не редактируется, а черновик `pending` одобряется импортом новой версии с рецензией. Новый алгоритм seed получает новое версионное имя в `domain/assessment_algorithms.go`, обязательные подстановки, тест решателя с посчитанными вручную случаями и golden-тест; зарегистрированный алгоритм не меняйте. Алгоритм с форматом ответа `choice` задает `generateChoice` вместо `generate` и возвращает правильное значение вместе с неверными значениями именованных моделей ошибок (пример - `lru_hits_choice.v1`); его тесты пересчитывают модели ошибок по условию. Демонстрационный пакет в `backend/testdata/assessment/` - непроверенный черновик ИИ: не заполняйте в нем рецензента, чтобы открыть категорию. См. [ARCHITECTURE.md](ARCHITECTURE.md#банк-заданий-оценки).
Миграция `00011_create_assessment_bank.sql` создает `assessment_families` (неизменяемые версии семейств) и `assessment_category_openings`; запросы лежат в `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` доступен через `UnitOfWork.AssessmentBank()` и через `postgres.AssessmentBankStore` вне транзакции; `assessment.Bank` импортирует `Bundle`, публикует версию от имени оператора (выводя из обращения опубликованную более старую), выводит ее из обращения, открывает категорию под действующей версией политики, сообщает живую доступность и генерирует вариант по seed. Чтобы изменить семейство, импортируйте новую версию; сохраненная версия не редактируется, а черновик `pending` одобряется импортом новой версии с рецензией. Новый алгоритм seed получает новое версионное имя в `domain/assessment_algorithms.go`, обязательные подстановки, тест решателя с посчитанными вручную случаями и golden-тест; зарегистрированный алгоритм не меняйте. Алгоритм с форматом ответа `choice` задает `generateChoice` вместо `generate` и возвращает правильное значение вместе с неверными значениями именованных моделей ошибок (пример - `lru_hits_choice.v1`); его тесты пересчитывают модели ошибок по условию. Семейство, варианты которого - фиксированные данные, использует табличный генератор вместо алгоритма: `seed_generator.table.rows` с `values`, `answer` и для `choice` еще `distractors`; при импорте таблица проверяется, ошибка называет индекс строки, а версия хранится со схемой хеша 2. Если ответ нужно вычислять, используйте алгоритм на Go. Схему 2 разрешает миграция `00047_allow_table_hash_scheme.sql`. Шаблоны условий - обычный текст только с подстановками `{{.name}}`. Демонстрационный пакет в `backend/testdata/assessment/` - непроверенный черновик ИИ: не заполняйте в нем рецензента, чтобы открыть категорию. См. [ARCHITECTURE.md](ARCHITECTURE.md#банк-заданий-оценки).
### Relay outbox
+3 -2
View File
@@ -498,7 +498,7 @@ Spec не проверяет запланированные переходы б
## Тесты банка заданий
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go` и `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) проверяют без базы: отклоняется некорректное содержимое семейства (правила рецензии, неизвестный алгоритм, границы параметров, несоответствие формата ответа, форма рубрики, символы формата Unicode); шаблоны условий принимают только текст и подстановки `{{.name}}`, а бомба из вложенных `define`, бомба ширины `printf`, `range` по числу и рекурсивный `block` отклоняются быстрее секунды и не запускаются; шаблон без подстановок, от которых зависит ответ, отклоняется; размер готового условия ограничен; измененный сохраненный документ не проходит проверку хеша; каждый отказ в публикации называет причину; один seed дает один вариант, а рубрика одинакова для всех seed; golden-тесты фиксируют точное условие и эталонный ответ для заданного seed у каждого из четырех алгоритмов и хеш содержимого схемы 1 для заданного входа; строка проверяется схемой хеша, с которой она сохранена (тест регистрирует вторую схему, а хеш одной схемы под именем другой и неизвестная схема отклоняются); шаблон, чье условие достигает границы размера только для одного пробного seed, отклоняется при импорте, потому что наибольшие значения параметров подставляются для восьми seed; разделители строки и абзаца отклоняются как символы формата; четыре решателя совпадают с посчитанными вручную случаями; покрытие для открытия равно `max_scored_items` плюс `seed_items` политики; демонстрационный пакет читается как черновик ИИ с рецензией `pending` и без рецензента. `assessment_choice_test.go` проверяет формат с выбором без базы: один seed дает одинаковые варианты, ID и порядок, а по 400 seed правильный вариант встречается на каждой позиции; каждый отвлекающий вариант `lru_hits_choice.v1` пересчитывается по условию как результат именованной модели ошибки (а добор соседними значениями используется, только если модели дали меньше трех различных значений), варианты не повторяют текст, модели кэша совпадают с посчитанными вручную случаями, а модель LRU равна решателю `lru_hits.v1`, golden-тест фиксирует варианты, их ID и ключ одного seed; правильный вариант, неверный вариант, вариант чужого задания, два варианта, числовой ответ на задание с выбором и ответ с выбором на целочисленное задание оцениваются или отклоняются, как описано, проекция для кандидата содержит только непрозрачные ID и тексты, а поврежденный ключ или повторяющийся вариант замороженного варианта отклоняются.
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go` и `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) проверяют без базы: отклоняется некорректное содержимое семейства (правила рецензии, неизвестный алгоритм, границы параметров, несоответствие формата ответа, форма рубрики, символы формата Unicode); шаблоны условий принимают только текст и подстановки `{{.name}}`, а бомба из вложенных `define`, бомба ширины `printf`, `range` по числу и рекурсивный `block` отклоняются быстрее секунды и не запускаются; шаблон без подстановок, от которых зависит ответ, отклоняется; размер готового условия ограничен; измененный сохраненный документ не проходит проверку хеша; каждый отказ в публикации называет причину; один seed дает один вариант, а рубрика одинакова для всех seed; golden-тесты фиксируют точное условие и эталонный ответ для заданного seed у каждого из четырех алгоритмов и хеш содержимого схемы 1 для заданного входа; строка проверяется схемой хеша, с которой она сохранена (тест регистрирует вторую схему, а хеш одной схемы под именем другой и неизвестная схема отклоняются); шаблон, чье условие достигает границы размера только для одного пробного seed, отклоняется при импорте, потому что наибольшие значения параметров подставляются для восьми seed; разделители строки и абзаца отклоняются как символы формата; четыре решателя совпадают с посчитанными вручную случаями; покрытие для открытия равно `max_scored_items` плюс `seed_items` политики; демонстрационный пакет читается как черновик ИИ с рецензией `pending` и без рецензента. `assessment_choice_test.go` проверяет формат с выбором без базы: один seed дает одинаковые варианты, ID и порядок, а по 400 seed правильный вариант встречается на каждой позиции; каждый отвлекающий вариант `lru_hits_choice.v1` пересчитывается по условию как результат именованной модели ошибки (а добор соседними значениями используется, только если модели дали меньше трех различных значений), варианты не повторяют текст, модели кэша совпадают с посчитанными вручную случаями, а модель LRU равна решателю `lru_hits.v1`, golden-тест фиксирует варианты, их ID и ключ одного seed; правильный вариант, неверный вариант, вариант чужого задания, два варианта, числовой ответ на задание с выбором и ответ с выбором на целочисленное задание оцениваются или отклоняются, как описано, проекция для кандидата содержит только непрозрачные ID и тексты, а поврежденный ключ или повторяющийся вариант замороженного варианта отклоняются. `assessment_table_test.go` проверяет табличные семейства: строки выбираются по seed, ответ - записанный, выбор для фиксированных seed зафиксирован, каждая из 39 ошибок формата (нет столбца, повтор строки, неверный ответ, повторяющийся отвлекающий вариант, слишком большое условие, вызов или конвейер в шаблоне, алгоритм рядом с таблицей и другие) отклоняется с индексом строки, хеш схемы 2 Line truncated
`TestAssessmentBank` в `backend/integration_test/assessment_bank_test.go` использует `bootstrap(t, postgresService)` и дает каждому случаю свою мигрированную базу:
@@ -510,7 +510,8 @@ Spec не проверяет запланированные переходы б
- Публикация более поздней версии семейства выводит из обращения опубликованную более старую и записывает обоих операторов; публикация более старой версии при опубликованной более новой отклоняется; таблица допускает одну опубликованную версию на семейство и отклоняет перезапись записанного публикатора.
- Транзакция, держащая блокировку категории, заставляет открытие ждать до срока, а после освобождения блокировки открытие проходит.
- Более старый одобренный черновик нельзя опубликовать, когда существует более новая версия, в том числе выведенная из обращения. Проверки действующей политики используют часы базы данных, без сдвига часов в тесте.
- `TestAssessmentChoiceFamiliesAreServedAndGradedOverHTTP` в `backend/integration_test/assessment_choice_http_test.go` проходит настоящую попытку по банку из алгоритма с выбором и целочисленного алгоритма: каждое задание, которое получает кандидат, содержит только разрешенные поля (для выбора - ID и тексты вариантов в сохраненном порядке, без поля ключа, seed или отвлекающего варианта), вариант чужого задания и два варианта отклоняются с 400, неверный выбор не дает баллов, а верный дает их по ключу, результат совпадает с ожидаемым числом баллов, и каждый ответ оставил наблюдение сигналов.
- Пакет с табличным семейством и семейством с выбором импортируется: таблицы со схемой хеша 2, алгоритм со схемой 1; повторный импорт сообщает их как неизмененные, а сохраненные строки дважды дают одинаковые варианты; прямая правка сохраненной таблицы отклоняется как правка сохраненной версии.
- `TestAssessmentChoiceAndTableFamiliesAreServedAndGradedOverHTTP` в `backend/integration_test/assessment_choice_http_test.go` проходит настоящую попытку по банку из алгоритма с выбором, целочисленной таблицы и таблицы с выбором: каждое задание, которое получает кандидат, содержит только разрешенные поля (для выбора - ID и тексты вариантов в сохраненном порядке, без поля ключа, seed или отвлекающего варианта), вариант чужого задания и два варианта отклоняются с 400, неверный выбор не дает баллов, а верный дает их по ключу, результат совпадает с ожидаемым числом баллов, и каждый ответ оставил наблюдение сигналов.
- Сырые строки политики, в документе которых нет границ оцениваемых заданий, они заданы текстом, слишком большим, дробным или отрицательным числом или нет seed-заданий, отклоняются триггером открытия отказом по порогам, а не ошибкой приведения типа; сохраненная схема хеша вне списка CHECK отклоняется, а саму схему изменить нельзя.
- В обход usecase таблица отклоняет открытие с заниженным требованием, открытие ниже покрытия, открытие под неизвестной версией политики и название с переопределением направления текста.
- Семейства выводятся страницами по две после курсора, каждое один раз и по порядку.