feat(profile): add the manual candidate profile contract and storage

This commit is contained in:
shira committed 2026-10-06 21:10:04 +03:00
1 parent d21fd49a42
commit e52ffe7bcb
97 files changed
+20442 -63

No files matched your search

+19
View File
@@ -751,6 +751,25 @@ What the ports guarantee (`outbound.OrganizationRepositories`, available on `Uni
- `GetForMember` reads the organization, its representatives (aggregated as JSON in the same statement), and the caller's active membership from one snapshot, and returns them or `ErrOrganizationNotFound` for an unknown organization, an account without a membership, and a `suspended`, `removed`, or `left` member alike. `ListForUser` pages the active organizations of one account, newest membership first, with the organization identifier as the tie-breaker. `UpdateProfile` is described above.
- `Memberships().Insert` returns `ErrMembershipExists` for a repeated pair in any state, `ErrOrganizationNotFound` for an unknown organization, and `ErrUserNotFound` for an unknown account; `Get` returns the membership in any state or `ErrMembershipNotFound`, and the caller checks `GrantsAccess`. There is no method that changes a role or a state yet.
### Candidate profile
Implemented as storage, domain, and the source contract (TASK-066): the migration `backend/db/migrations/00013_create_candidate_profiles.sql`, the queries in `backend/db/queries/candidate.sql`, the domain types in `backend/internal/domain/candidate.go`, the schemas in `api/core/components/schemas/candidate_schemas.yml`, and the operations `GetMyProfile` and `SaveMyProfile` in `api/core/routes/candidate_profile.yml`. There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter will come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`StoredClaims`, `RestoreCandidateProfile`) are ready and covered by an integration test.
Tables:
- `candidate_profiles`: `user_id` (the primary key and a foreign key to `users` with `ON DELETE CASCADE`), `version` (positive; the first save creates version 1, and the contract's version 0 is the absence of a row), and times. The profile is personal data of the account and goes with it; retention rules are an open legal question.
- `candidate_profile_claims`: one row per stored claim - a single field (`full_name`, `contact_email`, `contact_phone`, `contact_telegram`, `terms_location`, `terms_relocation`, `terms_salary_minimum` at `ordinal` 0) or a list item (`stack` up to 30, `role` up to 9, `experience` up to 20, `soft_skill` up to 10, by position). Columns: `value` jsonb, `status` (`confirmed` or `extracted`), `origin` (`manual`, `extracted_from_resume`, `imported`), `trust_level`, `quote`, `extraction_version`, and `confirmed_at`. A field without a value has no row, so the contract's `unknown` is the absence of a row. The foreign key points at `candidate_profiles` with `ON DELETE CASCADE`.
Decisions:
- Claims, not columns. Every value has a status, a source, and a confirmation time, so one claims table replaces fifty columns; jsonb holds the shape of the value (a string, a boolean, or an object), and each kind has its own CHECK for the format and bounds of the contract (E.164 for the phone, the `@` of a Telegram name, a multiple of 1000 for the salary, `YYYY-MM` and the order of the period for experience, the known specialization and grade codes). The domain validates a value in full before it is written, and `RestoreCandidateProfileContent` applies the same rules on read, so a row changed outside the application is rejected.
- Trust level 0 in the schema. `trust_level` is stored in a column with `CHECK (trust_level = 0)`, and the insert statement supplies 0 itself and takes no level from the caller. A confirmed value requires `confirmed_at`, an unconfirmed suggestion does not and is always an import (`extraction_version` is not NULL); a manual value is always confirmed and carries no quote. Raising trust is a property of evidence, which is not stored here.
- No confirmed category. The tables have no column for a confirmed grade or a category, and the value of a role admits only the keys `specialization` and `self_assessed_grade`, so neither a form nor an import can write a confirmed category; it is derived from assessment results when read (`confirmed_categories`).
- No mandatory link to a file, ML, or FSP. The tables have no column or foreign key to a resume file, the object storage, ML, or an FSP account, and the only foreign keys point at `users` and `candidate_profiles`. A profile typed by hand is complete; a future import adds its own columns or tables additively (`TestCandidateProfileStorage` checks the set of columns and foreign keys).
- Version. `AdvanceCandidateProfileVersion` is one statement that advances the version only when the stored one equals the one the caller read; for a stale version no row returns, and the caller answers 412 `version_conflict`. The update time is `GREATEST(stored, application clock)`, so an instance clock that runs behind never violates the CHECK `candidate_profiles_updated_after_creation` (which would be a 500). Version monotonicity is enforced by these queries only: there is no trigger, so no other code may write `version`. `InsertCandidateProfile` with `ON CONFLICT DO NOTHING` tells a lost first save apart (concurrent first saves: one wins, the rest get a version conflict). Replacing the set of claims (delete all, insert the new ones) runs in one transaction with the version advance. `domain.CandidateProfile.Replace(input, expectedVersion, at)` fixes the order: a version above the current one is a conflict; body rules are 400; a decision `extracted` that depends on the stored claims, against a stale version, is `ErrCandidateProfileVersionConflict` rather than 400; a body that changes nothing does not advance the version; any other change over a stale version is a conflict.
- Consistent read. `ReadCandidateProfile` reads the profile row and every claim in one statement (a LEFT JOIN), that is, from one snapshot; two separate queries could return version N with the claims of N+1 when a save commits between them. The adapter must use only this query and never replace it with two; a write reads the profile in the same transaction as the replacement, and the version condition protects against a lost edit.
- Privacy. The values are personal data of the candidate: `ProfileClaim`, `ProfileExperience`, `ProfileSalaryMinimum`, `CandidateProfileContent`, and `CandidateProfile` hide themselves in `fmt` and `slog` output, `CandidateProfile` logs only the account identifier and the version, domain errors name the field and the rule but never the value, and metric labels are never taken from the profile. No query selects the profile of another account: every statement is scoped by `user_id`. The adapter must never log or wrap `pgconn.PgError.Detail` (it contains the failing row with names and phones) and reports only the SQLSTATE and the constraint name, as the organizations adapter does.
## Frontend
The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need.
+18
View File
@@ -352,6 +352,24 @@ 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.
## Candidate profile tests
Unit tests (`make -C backend test`) check the profile rules without a database:
- `internal/domain/candidate_test.go`: manual values get the source `manual`, trust level 0, and the save time; a field sent as null is removed and a list is replaced; an imported suggestion stays unconfirmed under `extracted` with the same value, is confirmed under `confirmed` while keeping its source and quote, becomes manual under another value, while `extracted` for a value that is not among the suggestions and moving a confirmed value back to a suggestion are rejected with the pointer `/stack/1/status`; a table of values names the field that broke the rule (a phone outside E.164, a Telegram name without `@`, a name with whitespace, a salary that is not a multiple of 1000, an unknown specialization or grade, a tag repeated without regard to case, a repeated role specialization, a month outside `YYYY-MM`, a period that ends before it starts or lies in the future, too many items); an error never contains the submitted value; a body that changes nothing leaves the profile and the confirmation time unchanged; the storage rows (`StoredClaims`) restore to the same content in any order, and a row with an unknown kind, a trust level above 0, a quote on a manual value, a value of another type, an extra `confirmed_grade` key, a gap in a list, or a repeat is rejected; the profile types have no field for a confirmed grade, a category, or a trust level; the values are hidden in `fmt` and `slog` output.
- `internal/adapter/primary/http/candidate_profile_contract_test.go`: by the contract bundle, the operations follow the conventions (session and CSRF for the save, the version in the body, no Idempotency-Key or If-Match, 412 rather than 409, `no-store`); a request carries no confirmed category, source, trust level, or confirmation time, and every profile schema closes its objects; each claim carries `status` and `source`, and `trust_level` is limited to zero; the full name uses `ContactFullName`; **no schema outside the profile family and no operation of an organization reaches a profile schema through references, and the profile refers to no organization, invitation, or need schema**; through the generated server the schema rejects a client-sent category, source, and unknown fields before the implementation, a valid profile answers 501, and a denied session answers 401.
- `frontend/src/shared/api/profile-contract.test.ts`: the generated Zod schemas accept a complete profile and a profile with no value at all (that is, without a file or FSP), require `expected_version`, reject each broken format and extra list items, let no confirmed grade, category, or source into the parsed body, require every claim to have a source with trust level 0, and the request types have none of these fields; the generated organization, invitation, and need files hold no profile keys, and vice versa.
`TestCandidateProfileStorage` in `backend/integration_test/candidate_profile_test.go` uses `bootstrap(t, postgresService)` with the migrated schema; `candidateProfileTables` belong to `usersDependentTables`, so the other tests truncate them together with `users`:
- Saving without a file, ML, or FSP: a profile with only a name, and a profile row with no claim at all, are saved and read back, and a complete profile returns the same content and sources through `StoredClaims` and `RestoreCandidateProfile`; a stored import suggestion reads back with its quote, extraction version, and level 0.
- Schema: the columns of the two tables equal the expected list (no file, FSP, confirmed grade, or category), and the only foreign keys lead to the account and to the profile row.
- Constraints through direct SQL: each rule refuses a row with its own constraint (a trust level above 0, an unknown kind, status, and origin, a single field with a position, a list past its limit, a confirmation without a time, a manual value with a quote, an import without an extraction version, wrong values of a tag, a phone, a Telegram name, relocation, a salary, a role with a `confirmed_grade` key, and experience); a repeated tag, skill, or role specialization, a profile without an account, version 0, and a claim without a profile are refused too, while the same valid row is accepted.
- Deleting the account deletes the profile and its claims; two accounts keep their profiles apart.
- Version: a lost second first save and a stale version return no row, eight advances from one version and eight concurrent first saves on their own connections give exactly one success, and an advance with an earlier application clock keeps the update time and violates no CHECK. Reading uses the single `ReadCandidateProfile` query.
`TestCandidateProfileMigrationRollsBack` rolls migration 00013 back on an isolated database and checks that both tables disappear while `users` stays.
## 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.
+19
View File
@@ -751,6 +751,25 @@ contact_grant относится к паре кандидат-компания
- `GetForMember` читает организацию, ее представителей (собранных в JSON тем же оператором) и активное членство вызывающего из одного снимка и возвращает их либо `ErrOrganizationNotFound` одинаково для неизвестной организации, аккаунта без членства и участника в состоянии `suspended`, `removed` или `left`. `ListForUser` постранично отдает активные организации одного аккаунта от нового членства к старому с идентификатором организации как разрешением ничьей. `UpdateProfile` описан выше.
- `Memberships().Insert` возвращает `ErrMembershipExists` для повторной пары в любом состоянии, `ErrOrganizationNotFound` для неизвестной организации и `ErrUserNotFound` для неизвестного аккаунта; `Get` возвращает членство в любом состоянии или `ErrMembershipNotFound`, а вызывающий проверяет `GrantsAccess`. Метода, который меняет роль или состояние, пока нет.
### Профиль кандидата
Реализовано как хранение, домен и исходный контракт (TASK-066): миграция `backend/db/migrations/00013_create_candidate_profiles.sql`, запросы в `backend/db/queries/candidate.sql`, доменные типы в `backend/internal/domain/candidate.go`, схемы в `api/core/components/schemas/candidate_schemas.yml` и операции `GetMyProfile` и `SaveMyProfile` в `api/core/routes/candidate_profile.yml`. Порта, адаптера и обработчиков пока нет: операции отвечают 401 `unauthenticated`, пока сессий нет, и 501 `not_implemented` после валидации. Порт и адаптер придут с обработчиками и должны войти в `UnitOfWork`; запросы и доменное преобразование строк (`StoredClaims`, `RestoreCandidateProfile`) уже готовы и проверены интеграционным тестом.
Таблицы:
- `candidate_profiles`: `user_id` (первичный ключ и внешний ключ `ON DELETE CASCADE` на `users`), `version` (больше нуля; первое сохранение создает версию 1, а версия 0 контракта - отсутствие строки) и времена. Профиль - ПДн аккаунта и уходит вместе с ним; правила хранения - открытый юридический вопрос.
- `candidate_profile_claims`: по строке на сохраненное заявление - одиночное поле (`full_name`, `contact_email`, `contact_phone`, `contact_telegram`, `terms_location`, `terms_relocation`, `terms_salary_minimum` при `ordinal` 0) или элемент списка (`stack` до 30, `role` до 9, `experience` до 20, `soft_skill` до 10 по позиции). Столбцы: `value` jsonb, `status` (`confirmed` или `extracted`), `origin` (`manual`, `extracted_from_resume`, `imported`), `trust_level`, `quote`, `extraction_version` и `confirmed_at`. Поле без значения строки не имеет, поэтому `unknown` контракта - это отсутствие строки. Внешний ключ ведет на `candidate_profiles` с `ON DELETE CASCADE`.
Решения:
- Заявления, а не столбцы. У каждого значения есть статус, источник и время подтверждения, поэтому одна таблица заявлений вместо пятидесяти столбцов; форму значения (строка, булево или объект) держит jsonb, а у каждого вида есть свой CHECK формата и границ контракта (E.164 для телефона, `@` у Telegram, кратность 1000 у зарплаты, `YYYY-MM` и порядок периода у опыта, известные коды специализации и грейда). Домен проверяет значение полностью до записи, а `RestoreCandidateProfileContent` повторяет те же правила при чтении, поэтому строка, измененная вне приложения, отклоняется.
- Доверие 0 в схеме. `trust_level` хранится в столбце с `CHECK (trust_level = 0)`, а оператор вставки подставляет 0 сам и не принимает уровень от вызывающего. Подтвержденное значение требует `confirmed_at`, неподтвержденное предложение - нет и обязательно является импортом (`extraction_version` не NULL); ручное значение всегда подтверждено и не несет цитаты. Повышение доверия - свойство доказательств, которые хранятся не здесь.
- Нет подтвержденной категории. В таблицах нет столбца подтвержденного грейда или категории, а значение роли допускает только ключи `specialization` и `self_assessed_grade`, поэтому ни форма, ни импорт не могут записать подтвержденную категорию; она выводится из результатов оценки при чтении (`confirmed_categories`).
- Нет обязательной связи с файлом, ML или ФСП. В таблицах нет столбцов и внешних ключей к файлу резюме, хранилищу объектов, ML или аккаунту ФСП, а единственные внешние ключи - на `users` и на `candidate_profiles`. Профиль, набранный вручную, полон; будущий импорт добавит свои столбцы или таблицы аддитивно (`TestCandidateProfileStorage` проверяет набор столбцов и внешних ключей).
- Версия. `AdvanceCandidateProfileVersion` - один оператор, который увеличивает версию только когда сохраненная равна прочитанной вызывающим; для устаревшей версии строка не возвращается, и вызывающий отвечает 412 `version_conflict`. Время обновления считается как `GREATEST(сохраненное, текущее время приложения)`, поэтому отставшие часы экземпляра не нарушают CHECK `candidate_profiles_updated_after_creation` (иначе был бы 500). Монотонность версии обеспечивают только эти запросы: триггера нет, поэтому никакой другой код не должен писать `version`. `InsertCandidateProfile` с `ON CONFLICT DO NOTHING` отличает проигранное первое сохранение (параллельные первые сохранения: одно выигрывает, остальные - конфликт версии). Замена набора заявлений (удалить все и вставить новые) идет в одной транзакции вместе с продвижением версии. `domain.CandidateProfile.Replace(input, expectedVersion, at)` задает порядок: версия выше текущей - конфликт; правила тела - 400; решение `extracted`, зависящее от сохраненных заявлений, при устаревшей версии - `ErrCandidateProfileVersionConflict`, а не 400; тело без изменений - без продвижения версии; иное изменение по устаревшей версии - конфликт.
- Согласованное чтение. `ReadCandidateProfile` читает строку профиля и все заявления одним оператором (LEFT JOIN), то есть из одного снимка; два отдельных запроса могли бы вернуть версию N с заявлениями N+1 при сохранении между ними. Адаптер обязан использовать только этот запрос и не заменять его двумя; запись читает профиль в той же транзакции, что и замена, а защиту от потерянной правки дает условие версии.
- Приватность. Значения - ПДн кандидата: `ProfileClaim`, `ProfileExperience`, `ProfileSalaryMinimum`, `CandidateProfileContent` и `CandidateProfile` скрывают себя в выводе `fmt` и `slog`, `CandidateProfile` логирует только идентификатор аккаунта и версию, ошибки домена называют поле и правило, но не значение, а метки метрик никогда не берутся из профиля. Ни один запрос не выбирает профиль чужого аккаунта: каждый оператор ограничен `user_id`. Адаптер никогда не логирует и не оборачивает `pgconn.PgError.Detail` (там строка с именами и телефонами) и сообщает только SQLSTATE и имя ограничения, как адаптер организаций.
## Frontend
Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности.
+18
View File
@@ -352,6 +352,24 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
`TestPostgresMigrations` откатывает миграцию 00010 вместе с остальными, проверяет, что три ее таблицы и функция исчезают, а таблицы identity остаются, и проверяет их снова после второго применения. Тесты, очищающие `users`, называют `usersDependentTables` (таблицы identity, доставок, согласий и организаций) - единственный список, который нужно расширять, когда миграция добавляет таблицу со ссылкой на users. Набор не покрывает usecase, обработчики, сопоставление сессии и CSRF и утверждение, что контракт соблюдается сквозным путем, потому что ничего из этого еще нет; атомарность чтения организации с представителями одним оператором тестом не доказана, потому что окно между двумя операторами нельзя воспроизвести детерминированно.
## Тесты профиля кандидата
Модульные тесты (`make -C backend test`) проверяют правила профиля без базы данных:
- `internal/domain/candidate_test.go`: ручные значения получают источник `manual`, уровень доверия 0 и время сохранения; поле, посланное как null, удаляется, а список заменяется; предложение импорта остается неподтвержденным при `extracted` с тем же значением, подтверждается при `confirmed` с сохранением источника и цитаты, становится ручным при другом значении, а `extracted` для значения, которого нет среди предложений, и возврат подтвержденного значения в предложение отклоняются с указателем `/stack/1/status`; таблица значений называет поле, которое нарушило правило (телефон вне E.164, Telegram без `@`, имя с пробелами, зарплата не кратна 1000, неизвестные специализация и грейд, повтор тега без учета регистра, повтор специализации роли, месяц не в формате `YYYY-MM`, период, который кончается раньше начала или лежит в будущем, слишком много элементов); ошибка не содержит присланного значения; тело без изменений не меняет профиль и время подтверждения; строки хранилища (`StoredClaims`) восстанавливаются в то же содержимое в любом порядке, а строка с неизвестным видом, уровнем доверия выше 0, цитатой у ручного значения, значением чужого типа, лишним ключом `confirmed_grade`, пропуском в списке или повтором отклоняется; типы профиля не имеют полей подтвержденного грейда, категории или уровня доверия; значения скрыты в выводе `fmt` и `slog`.
- `internal/adapter/primary/http/candidate_profile_contract_test.go`: по бандлу контракта операции следуют соглашениям (сессия и CSRF для сохранения, версия в теле, нет Idempotency-Key и If-Match, 412 вместо 409, `no-store`); запрос не несет подтвержденную категорию, источник, уровень доверия и время подтверждения, а все схемы профиля закрывают объекты; каждое заявление несет `status` и `source`, а `trust_level` ограничен нулем; имя использует `ContactFullName`; **ни одна схема вне семейства профиля, ни одна операция организации не достигает схемы профиля по ссылкам, и профиль не ссылается на схемы организации, приглашения или потребности**; через сгенерированный сервер схема отклоняет присланную клиентом категорию, источник и неизвестные поля до реализации, а допустимый профиль отвечает 501, при отклоненной сессии - 401.
- `frontend/src/shared/api/profile-contract.test.ts`: сгенерированные схемы Zod принимают полный профиль и профиль без единого значения (то есть без файла и ФСП), требуют `expected_version`, отклоняют каждый нарушенный формат и лишние элементы списков, не пропускают в разобранное тело подтвержденный грейд, категорию и источник, требуют у каждого заявления источник с уровнем доверия 0, а типы запросов не имеют этих полей; сгенерированные файлы организации, приглашения и потребности не содержат ключей профиля, и наоборот.
`TestCandidateProfileStorage` в `backend/integration_test/candidate_profile_test.go` использует `bootstrap(t, postgresService)` с мигрированной схемой; `candidateProfileTables` входят в `usersDependentTables`, поэтому остальные тесты очищают их вместе с `users`:
- Сохранение без файла, ML и ФСП: профиль только с именем, а также строка профиля без единого заявления сохраняются и читаются, а полный профиль возвращается с тем же содержимым и источником через `StoredClaims` и `RestoreCandidateProfile`; сохраненное предложение импорта читается с цитатой, версией извлечения и уровнем 0.
- Схема: столбцы двух таблиц равны ожидаемому списку (без файла, ФСП, подтвержденного грейда и категории), а единственные внешние ключи ведут на аккаунт и на строку профиля.
- Ограничения через прямой SQL: каждое правило отказывает строке с собственным ограничением (уровень доверия выше 0, неизвестные вид, статус и источник, одиночное поле с позицией, список за пределом, подтверждение без времени, ручное значение с цитатой, импорт без версии извлечения, неверные значения тега, телефона, Telegram, переезда, зарплаты, роли с ключом `confirmed_grade` и опыта); повтор тега, навыка и специализации роли, профиль без аккаунта, версия 0 и заявление без профиля тоже отклоняются, а такая же корректная строка принимается.
- Удаление аккаунта удаляет профиль и заявления; два аккаунта хранят профили независимо.
- Версия: проигравшее второе первое сохранение и устаревшая версия не возвращают строку, восемь продвижений от одной версии и восемь параллельных первых сохранений на своих соединениях дают ровно один успех, а продвижение с более ранним временем приложения сохраняет время обновления и не нарушает CHECK. Чтение идет одним запросом `ReadCandidateProfile`.
`TestCandidateProfileMigrationRollsBack` откатывает миграцию 00013 на изолированной базе, проверяет, что обе таблицы исчезают, а `users` остается.
## Тесты банка заданий
`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-ошибки без строки с нарушением, что страница списка вне предела падает до любого запроса и что блокировка категории отклоняется вне транзакции.