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

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

No files matched your search

+15
View File
@@ -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.
+4
View File
@@ -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.
+20
View File
@@ -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.
+15
View File
@@ -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 применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия.
+4
View File
@@ -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()` в своей бизнес-транзакции.
+20
View File
@@ -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, почта - тестовым адаптером.