From e95c681165a9e93e025524f167196c5aeeb125c1 Mon Sep 17 00:00:00 2001 From: shira Date: Sun, 11 Oct 2026 08:23:50 +0300 Subject: [PATCH] docs(assessment): describe content hash scheme 2 of table families --- docs/en/ARCHITECTURE.md | 2 +- docs/ru/ARCHITECTURE.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 93a808d..cdf8776 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -668,7 +668,7 @@ These intervals are the accepted initial policy, stored as demo version 1 of the Implemented as storage and a loader, 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`). Bootstrap creates `assessment.NewBank` once (`bootstrap/catalog.go`, with its own small PostgreSQL pool) and hands it to `CatalogHandler`; HTTP uses only the read `Bank.SpecializationAvailability` for the public specialization catalog (`GET /api/v1/specializations`). HTTP does not call the loader operations (`ImportBundle`, `PublishFamily`, `RetireFamily`, `OpenCategory`): the demonstration seed command (`adapter/primary/cli/demoseed`, `usecase/demoseed`) and `cmd/questionnaire-fixture` call them, so no category is open in a build without the seed. Assessment attempts run through a separate `AttemptService` that reads the bank through the `UnitOfWork.AssessmentBank()` repository, not through `Bank`. - 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:` or `operator:`), reviewer (`operator:` 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. +- 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 an existing scheme) 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 and scheme 2 hashes of fixed inputs. Scheme 1 is the layout of an algorithmic generator and scheme 2 (migration `00047_allow_table_hash_scheme.sql` widens the CHECK to `1, 2`) is the layout of a table generator; a new version gets the scheme of its generator kind, so the content and the hash of every algorithmic version stay what they were, and each scheme refuses the other kind of generator, because a table hashed by scheme 1 would not be covered by the hash. 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 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. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 53e57d0..d4a5d20 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -668,7 +668,7 @@ contact_grant относится к паре кандидат-компания Реализованы хранилище и загрузчик, а не функция для кандидата: миграция `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 создает `assessment.NewBank` один раз (`bootstrap/catalog.go`, отдельный небольшой пул PostgreSQL) и передает его `CatalogHandler`; HTTP использует только чтение `Bank.SpecializationAvailability` для публичного каталога специализаций (`GET /api/v1/specializations`). Операции загрузчика (`ImportBundle`, `PublishFamily`, `RetireFamily`, `OpenCategory`) HTTP не вызывает: их вызывают команда демонстрационного seed (`adapter/primary/cli/demoseed`, `usecase/demoseed`) и `cmd/questionnaire-fixture`, поэтому в сборке без seed ни одна категория не открыта. Попытки оценки работают через отдельный `AttemptService`, который читает банк через репозиторий `UnitOfWork.AssessmentBank()`, а не через `Bank`. - Версия семейства. Одна строка `assessment_families` - одна версия одного семейства (`family_key`, `version`): категория, специализация (область внутри категории), название, автор (`ai:` или `operator:`), рецензент (`operator:` или 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_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 и 2 для заданных входов. Схема 1 - формат алгоритмического генератора, а схема 2 (миграция `00047_allow_table_hash_scheme.sql` расширяет CHECK до `1, 2`) - формат табличного генератора; новая версия получает схему по виду своего генератора, поэтому содержимое и хеш каждой алгоритмической версии остаются прежними, а каждая схема отклоняет генератор другого вида, потому что таблица, захешированная схемой 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-тесты с посчитанными вручную случаями. Реестр только растет: измененный алгоритм получает новое имя, потому что сохраненные версии ссылаются на старое. - Формат ответа с выбором. Формат ответа `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` в документе замороженного варианта; для других форматов поле опускается, поэтому сохраненные попытки продолжают читаться.