feat(evidence): project skill evidence from confirmed assessments
This commit is contained in:
1 parent
4761508f13
commit
c2a8d17195
94 files changed
+10077
-151
No files matched your search
@@ -623,6 +623,24 @@ Code: migration `backend/db/migrations/00033_create_assessment_signal_review.sql
|
||||
- When and how. The review never runs in a candidate's transaction. The first accepted answer schedules the job `assessment.signal_review` with the key `<attempt>:deadline`, due one minute after the deadline of the attempt (so an answer committed right at the deadline is in its facts), and finalization schedules `<attempt>:ended`, due at once; both are inserts into `scheduled_jobs` in the transaction of the answer or the finalization, and repeats do nothing. The deadline job also covers an attempt that expires or is abandoned, however and whenever its state changes. A review is a point-in-time evaluation: it describes the facts committed when its job ran, and the job at the deadline runs it again for a finalized attempt, which picks up later matches. The job computes the review of its attempt and refreshes the review of every other attempt that has ended (terminal state or past its deadline) and shares answers with it at the attention level or above, at most 50 per job; a ring of more than 50 attempts that share answers is covered because each member runs its own deadline job and sees the others. An attempt that is still running is flagged by its own job when it ends and sees the other facts then. Writers are ordered by a transaction-scoped advisory lock per review: the job locks the review of every attempt it will write, in ascending attempt order, before it reads any fact, so the later of two jobs over one attempt waits and then reads what the earlier committed (no lost update, and no lock cycle). The times of a review come from the database clock inside the upsert and the update time never falls behind the stored times. Nothing else is locked: the facts are append-only and a job is scheduled after its facts are committed. A failure is retried by the runner with backoff and can never block or change a result; without the worker (`JOBS_ENABLED=false`) reviews wait with their jobs. The only review statement in a candidate's transaction is the insert of the job (and the two counter updates of the answer). The job logs one line with the number of reviews it wrote and its duration, and no answer, address, or candidate. Applicability bound: the share is read from the counters in constant time, but the comparison joins the answers of the attempt with the answers that hold the same values, so its cost grows with the number of holders of popular values, at most 23 items times the holders of each; it is fine for background jobs on populations of up to about 100,000 answers per family and needs sampling or a cap above that.
|
||||
- Limits. Browser signals can be forged or suppressed, so they are a hint only. A helper such as an LLM on another device is not visible. False positives are possible: a shared or changing network (mobile data, NAT), a reload, two tabs, copying the task text, and coinciding answers of a small answer space. The retention period of these facts, whether collecting them needs a separate consent beyond the notice, and who calibrates the thresholds are not decided.
|
||||
|
||||
### Skill evidence
|
||||
|
||||
Implemented as a stored projection of the immutable assessment results, with two reads: the candidate's own list and the permitted projection of a currently visible card. It feeds nothing yet: no ranking, matching, or percentile reads it.
|
||||
|
||||
Code: migration `backend/db/migrations/00035_create_skill_evidence.sql`, queries `backend/db/queries/evidence.sql`, the model in `backend/internal/domain/evidence.go`, the port `port/outbound/evidence.go` (`UnitOfWork.Evidence()`), the adapter `adapter/secondary/postgres/evidence.go`, the usecase `backend/internal/usecase/evidence/read.go`, the handler `adapter/primary/http/v1/evidence.go`, and the operations `ListMyEvidence` and `GetOrganizationCandidateEvidence` ([api/README.en.md](../../api/README.en.md#skill-evidence)).
|
||||
|
||||
- One event is one fact. `skill_evidence_facts` has one row per source event (`UNIQUE (source_type, event_id)`); `skill_evidence_skills` holds the skills of that event as tags (primary key `(fact_id, skill_code)`, a closed set of the nine specialization codes and the four technology codes of the card). A second tag adds a tag, never a fact, so repeated tags cannot multiply a contribution. A fact without a skill cannot be committed (a deferred constraint trigger), tags, once stored, are never rewritten or removed, and a tag joins a fact only in the transaction that created it (`created_txid` and the trigger `skill_evidence_skills_require_new_fact`), so a stored fact is never widened afterwards.
|
||||
- A fact keeps its source, event, result, attribution, date, visibility, and trust, and tells a claim from a measurement. `kind` is `claim` (trust 0, a statement that nothing confirmed separately) or `measurement` (trust 1 to 3, an observed result); a CHECK ties each kind to its levels. Only measurements are written today, so no claim is stored and the profile claims (trust 0) are not listed. `source_type` is `assessment_result` and the event and the result are the attempt, because a result is keyed by its attempt (`result_id` is a foreign key to `assessment_attempt_results` with the owner, and a cascade removes the fact with its result or account). `attribution` is `personal` (the team values of the PRD are reserved by the CHECK). The result part is the grade that was passed, the basis (`synthetic_demo`), and the calibration (`uncalibrated`), copied from the category decision of the result: a demonstration category is shown as one.
|
||||
- Trust 1. An online assessment is unproctored and nothing confirms who answered, so the projection writes trust 1 (the PRD level without a reliable confirmation of the identity or authorship). A CHECK allows only 1 or 2 for this source, never the in-person level 3; 2 is reserved for a result tied to a confirmed identity, which no flow produces yet. `domain.EvidenceTrustOnlineUnconfirmed` and the SQL value are kept equal by the integration test.
|
||||
- Which results qualify. One SQL predicate (`skill_evidence_result_qualifies`) says that a result is evidence: a real result (`root` or `corrective`) of the basic mode, version 2, with the outcome `confirmed`, and a category decision with the status `assigned` or `unchanged`, that is, a reviewed synthetic source. A result that passed but had no reviewed source (`not_eligible`, for example with the demonstration gate off) is not evidence, a failed attempt is not evidence and is never shown as a failure, and an express training run (`demo_express`, a version 1 result of the mode `demo_express`) is never evidence. A lower passing result under a higher category (`unchanged`) is a fact of its own: the grade was passed, and the category stays.
|
||||
- Why a stored projection written by the database, not a derivation on read. Decision: a trigger on `assessment_attempt_results` calls `skill_evidence_project_assessment_result` after the insert of a result, in the transaction that finalizes the attempt, and the migration projects the results that already exist with the same function. Reasons: the atomicity with the result and the category holds without a change to the finalization code; no write path (a command, a repair, a future import) can store a qualifying result and forget its evidence, or the reverse; a fact needs state that a derivation cannot carry (the candidate's visibility, tags from other events); and every read touches only the projection, so no query of the evidence names a result, an answer, an attempt, or a review (a test reads the query files and fails on it). The cost: the rule lives in SQL as the category guards do, the projection must be rebuilt by the function if the rule changes (the function is idempotent, and an integration test truncates the projection and rebuilds it), and the facts duplicate three values of the result. A guard trigger refuses a fact whose result does not qualify or does not match the fact, even through a direct write, and the table refuses every change but `visibility`. Rolling the migration back drops the projection, which is derived, and applying the migration again rebuilds it; but the rollback refuses (`skill_evidence_retained`) while any fact is hidden, because hiding is the candidate's decision and no result can bring it back. Known risks: a trigger failure rolls the finalization back with it, which is the intended atomicity (a result without its fact is never stored); and a real version 2 result whose specialization is outside the closed skill list would fail the backfill of the migration and the trigger, so a new specialization needs a change of the list in the same migration that admits it.
|
||||
- The candidate reads `GET /api/v1/me/evidence`: own facts only, newest first, the hidden ones with `visibility` `hidden`, a cursor bound to the candidate (the cursor of the privacy lists), `Cache-Control: no-store`. The fact names the result that the candidate can open at `GetMyAssessmentResult`.
|
||||
- The organization reads `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`. The evidence is a section of the card, so the read runs the checks of the card read in one transaction: verified employer, active membership, effective C2 publication, the hiding of this organization, the minimum cohort, and the card must show at least one category after the cohort rules (`candidateview.Service.AuthorizeCategoriesSection`, which returns the categories of the card, each with its grade). Then the statement `ListOrganizationVisibleEvidence` repeats the barrier: it selects from `candidate_effective_publications`, excludes the candidates that hide the organization with `NOT EXISTS`, requires the `categories` field in the published fields, and returns only visible measurements. It returns one fact for each category of the card: the earliest fact that passed exactly the confirmed grade of that category, so a lower grade or a retake adds nothing, and only the skill of the category, never the other tags. A closed or revoked publication, a hidden organization, an unknown handle, a suppressed card, and a card without categories answer one 404; a hidden fact gives an empty list, not an error. The answer is an allowlist: the skill, the passed grade, the trust level, the year of the event (`observed_year`), and the basis and calibration of the method (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and tell the organization that the fact is a demonstration, not a validated measurement (they add no fingerprint). It has no identifier of the fact, the event, the result, or the candidate, no month or exact time, no source, and never an answer, score, item, failure, signal, or review band. What can and cannot be linked: no key joins the answer to a person, but it is not unlinkable. The skill, grade, trust, and year, together with the other values of the card, can narrow a small pool of candidates, and the minimum cohort of the card does not cover the year. The read consumes the card-view quota under the distinct-card rule and is recorded in the access history with the field `categories`, so the candidate sees it.
|
||||
- Scope of the consent C2. Publishing the `categories` field now sends an organization the confirmed category and one supporting assessment fact for it (skill, grade, trust level, year, and the demonstration labels). The candidate sees the same section in `GetMyCardPreview` (`evidence`), which applies no organization or cohort, so an organization can receive less. The C2 consent text was written before this section existed, and whether it needs a new version for it is a decision for the owner and the lawyer; this change does not touch the consent texts.
|
||||
- Express and failure. Reading the evidence before and after an express run shows the same list, the database refuses a fact whose result is an express run or a failed attempt, and an express run is not in the category, hence not in the card cohort. There is no percentile or ranking cohort in this release; when they appear they must read the same predicate.
|
||||
- Contract checks. `TestEvidenceOperationsFollowTheConventions`, `TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements`, `TestNoOrganizationOperationReachesRawAssessmentData`, and `TestEvidenceWalkReachesTheEvidenceFamily` (Go) and `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) walk every organization operation and the candidate list through all references and fail on an assessment, signal, or review schema, or on a raw answer, score, or failure property.
|
||||
- Not implemented: an operation to hide or show a fact (the column and the guard exist; no HTTP operation changes it), claims from the profile as facts, facts from FSP or other sources, revocation of a source, a trust level above 1, the use of evidence in ranking or in the Passport PDF, and retention. Whether the evidence should need its own card field instead of `categories` is open.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -623,6 +623,24 @@ contact_grant относится к паре кандидат-компания
|
||||
- Когда и как. Проверка никогда не считается в транзакции кандидата. Первый принятый ответ планирует задание `assessment.signal_review` с ключом `<попытка>:deadline`, срок - через минуту после дедлайна попытки (чтобы ответ, зафиксированный прямо на дедлайне, попал в факты), а завершение планирует `<попытка>:ended`, срок - сразу; оба - вставки в `scheduled_jobs` в транзакции ответа или завершения, повтор ничего не делает. Задание дедлайна покрывает и попытку, которая истекает или брошена, как и когда бы ни менялось ее состояние. Проверка - оценка на момент: она описывает факты, зафиксированные к запуску ее задания, а задание на дедлайне для завершенной попытки запускает ее снова и подхватывает поздние совпадения. Задание считает проверку своей попытки и обновляет проверку каждой другой завершившейся (терминальное состояние или срок прошел) попытки с общими ответами на уровне «внимание» и выше, не более 50 за задание; кольцо больше 50 попыток с общими ответами покрыто тем, что каждый участник запускает свое задание дедлайна и видит остальных. Еще идущую попытку помечает ее собственное задание, когда она закончится и увидит остальные факты. Писатели упорядочены транзакционной advisory-блокировкой на каждую проверку: задание берет блокировки проверок всех попыток, которые будет писать, по возрастанию идентификатора, до чтения любого факта, поэтому более позднее из двух заданий по одной попытке ждет и затем читает то, что зафиксировало раннее (нет потерянного обновления и нет цикла блокировок). Время проверки берется из часов базы внутри upsert, а время обновления не отстает от сохраненного. Больше ничего не блокируется: факты только добавляются, а задание планируется после фиксации его фактов. Сбой повторяется исполнителем с задержкой и никогда не блокирует и не меняет результат; без worker (`JOBS_ENABLED=false`) проверки ждут вместе со своими заданиями. В транзакции кандидата из запросов проверки только вставка задания (и два обновления счетчиков ответа). Задание пишет в журнал одну строку с числом записанных проверок и длительностью, без ответов, адресов и кандидатов. Граница применимости: доля читается из счетчиков за постоянное время, но сравнение соединяет ответы попытки с ответами, у которых те же значения, поэтому цена растет с числом держателей популярных значений, не более 23 заданий на число держателей каждого; для фоновых заданий это нормально на совокупностях до порядка 100 000 ответов на семейство, выше нужна выборка или предел.
|
||||
- Ограничения. Браузерные сигналы можно подделать или подавить, поэтому это только подсказка. Помощь, например LLM на другом устройстве, не видна. Возможны ложные срабатывания: общая или меняющаяся сеть (мобильный интернет, NAT), перезагрузка страницы, две вкладки, копирование условия и случайные совпадения ответов из малого пространства. Срок хранения этих фактов, нужно ли для их сбора отдельное согласие сверх уведомления и кто калибрует пороги, не решено.
|
||||
|
||||
### Доказательства навыков
|
||||
|
||||
Реализовано как сохраняемая проекция неизменяемых результатов оценки с двумя чтениями: собственный список кандидата и разрешенная проекция сейчас видимой карточки. Проекцию пока никто не использует: ни ранжирование, ни подбор, ни перцентиль ее не читают.
|
||||
|
||||
Код: миграция `backend/db/migrations/00035_create_skill_evidence.sql`, запросы `backend/db/queries/evidence.sql`, модель `backend/internal/domain/evidence.go`, порт `port/outbound/evidence.go` (`UnitOfWork.Evidence()`), адаптер `adapter/secondary/postgres/evidence.go`, usecase `backend/internal/usecase/evidence/read.go`, обработчик `adapter/primary/http/v1/evidence.go` и операции `ListMyEvidence` и `GetOrganizationCandidateEvidence` ([api/README.md](../../api/README.md#доказательства-навыков)).
|
||||
|
||||
- Одно событие - один факт. В `skill_evidence_facts` одна строка на событие-источник (`UNIQUE (source_type, event_id)`); в `skill_evidence_skills` навыки этого события лежат как теги (первичный ключ `(fact_id, skill_code)`, закрытый набор из девяти кодов специализаций и четырех кодов технологий карточки). Второй тег добавляет тег, а не факт, поэтому повторные теги не умножают вклад. Факт без навыка нельзя зафиксировать (отложенный constraint-триггер), сохраненные теги не меняются и не удаляются, а тег присоединяется к факту только в транзакции, создавшей факт (`created_txid` и триггер `skill_evidence_skills_require_new_fact`), поэтому сохраненный факт потом не расширяется.
|
||||
- Факт хранит источник, событие, результат, атрибуцию, дату, видимость и доверие и отличает заявление от измерения. `kind` равен `claim` (доверие 0, утверждение без отдельного подтверждения) или `measurement` (доверие 1-3, наблюдаемый результат); CHECK связывает вид с допустимыми уровнями. Сейчас записываются только измерения, поэтому заявлений в таблице нет, а заявления профиля (доверие 0) в списке не показываются. `source_type` равен `assessment_result`, событие и результат - это попытка, так как результат ключуется попыткой (`result_id` - внешний ключ на `assessment_attempt_results` вместе с владельцем, каскад удаляет факт вместе с результатом или аккаунтом). `attribution` равна `personal` (командные значения PRD зарезервированы CHECK). Часть "результат" - пройденный грейд, основание (`synthetic_demo`) и калибровка (`uncalibrated`), скопированные из решения о категории: демонстрационная категория показывается как демонстрационная.
|
||||
- Доверие 1. Онлайн-оценка проходит без прокторинга, и ничто не подтверждает, кто отвечал, поэтому проекция пишет доверие 1 (уровень PRD без надежного подтверждения личности или авторства). CHECK допускает для этого источника только 1 или 2 и никогда не очный уровень 3; уровень 2 зарезервирован за результатом, связанным с подтвержденной личностью, - такого потока пока нет. `domain.EvidenceTrustOnlineUnconfirmed` и значение в SQL сверяет интеграционный тест.
|
||||
- Какие результаты считаются доказательством. Один SQL-предикат (`skill_evidence_result_qualifies`): настоящий результат (`root` или `corrective`) базового режима, версия 2, исход `confirmed` и решение о категории со статусом `assigned` или `unchanged`, то есть с проверенным синтетическим источником. Пройденный результат без проверенного источника (`not_eligible`, например при выключенном демонстрационном режиме) доказательством не является, проваленная попытка тоже не является и нигде не показывается как провал, а экспресс-прогон (`demo_express`, результат версии 1 режима `demo_express`) не бывает доказательством никогда. Более низкий пройденный результат при более высокой категории (`unchanged`) - отдельный факт: грейд пройден, категория остается.
|
||||
- Почему сохраняемая проекция, которую пишет база, а не вычисление при чтении. Решение: триггер на `assessment_attempt_results` после вставки результата вызывает `skill_evidence_project_assessment_result` в той же транзакции, что завершает попытку, а миграция проецирует уже существующие результаты той же функцией. Причины: атомарность с результатом и категорией без изменений в коде завершения; ни один путь записи (команда, исправление, будущий импорт) не сохранит подходящий результат без доказательства и наоборот; факту нужно состояние, которое вычисление не несет (видимость кандидата, теги от других событий); все чтения трогают только проекцию, поэтому ни один запрос доказательств не называет результат, ответ, попытку или проверку (тест читает файлы запросов и падает на этом). Цена: правило живет в SQL, как и охранники категории; при смене правила проекцию нужно перестроить функцией (она идемпотентна, интеграционный тест очищает проекцию и перестраивает ее); факт дублирует три значения результата. Охранный триггер отказывает факту, чей результат не подходит или не совпадает с фактом, даже при прямой записи, а таблица отказывает в любых изменениях, кроме `visibility`. Откат миграции удаляет проекцию, она производная, и повторное применение миграции строит ее заново; но откат отказывает (`skill_evidence_retained`), пока хоть один факт скрыт, потому что скрытие - решение кандидата, и никакой результат его не вернет. Известные риски: сбой триггера откатывает и завершение попытки, это задуманная атомарность (результат без своего факта не сохраняется); а настоящий результат версии 2 со специализацией вне закрытого списка навыков сломал бы заполнение миграции и триггер, поэтому новая специализация требует изменить список в той же миграции, которая ее допускает.
|
||||
- Кандидат читает `GET /api/v1/me/evidence`: только свои факты, новые первыми, скрытые - с `visibility` `hidden`, курсор привязан к кандидату (курсор списков приватности), `Cache-Control: no-store`. Факт называет результат, который кандидат открывает через `GetMyAssessmentResult`.
|
||||
- Организация читает `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`. Доказательства - раздел карточки, поэтому чтение выполняет проверки чтения карточки в одной транзакции: подтвержденный работодатель, активное членство, действующая публикация с C2, скрытие этой организации, минимальная когорта, и после правил когорты карточка должна показывать хотя бы одну категорию (`candidateview.Service.AuthorizeCategoriesSection`, он возвращает категории карточки с грейдами). Затем запрос `ListOrganizationVisibleEvidence` повторяет барьер: выбирает из `candidate_effective_publications`, исключает кандидатов, скрывших организацию, через `NOT EXISTS`, требует поле `categories` в опубликованных полях и возвращает только видимые измерения. Он возвращает по одному факту на каждую категорию карточки: самый ранний факт, который прошел ровно подтвержденный грейд этой категории, поэтому более низкий грейд и пересдача ничего не добавляют, и только навык категории, а не остальные теги. Закрытая или отозванная публикация, скрытая организация, неизвестный handle, подавленная карточка и карточка без категорий дают один и тот же 404; скрытый факт дает пустой список, а не ошибку. Ответ - белый список: навык, пройденный грейд, уровень доверия, год события (`observed_year`), а также основание и калибровка метода (`synthetic_demo`, `uncalibrated`), одинаковые для всех кандидатов: они сообщают организации, что факт - демонстрация, а не проверенное измерение (отпечатка они не добавляют). В нем нет идентификатора факта, события, результата или кандидата, нет месяца и точного времени, нет источника и никогда нет ответа, балла, задания, провала, сигнала или полосы проверки. Что можно и что нельзя связать: ключа, который привязывает ответ к человеку, нет, но ответ не является несвязываемым. Навык, грейд, доверие и год вместе с другими значениями карточки могут сузить малый пул кандидатов, а минимальная когорта карточки год не покрывает. Чтение расходует квоту просмотров карточек по правилу разных карточек и записывается в историю доступа с полем `categories`, так что кандидат его видит.
|
||||
- Область согласия C2. Публикация поля `categories` теперь отправляет организации подтвержденную категорию и один подтверждающий ее факт оценки (навык, грейд, уровень доверия, год и метки демонстрации). Кандидат видит тот же раздел в `GetMyCardPreview` (`evidence`); предпросмотр не применяет организацию и когорту, поэтому организация может получить меньше. Текст согласия C2 написан до появления этого раздела, и нужна ли для него новая версия, решают владелец продукта и юрист; это изменение тексты согласий не трогает.
|
||||
- Экспресс и провал. Чтение доказательств до и после экспресс-прогона дает один и тот же список, база отказывает факту, чей результат - экспресс-прогон или проваленная попытка, а экспресс не входит в категорию и потому в когорту карточки. Перцентиля и ранжирования в этом выпуске нет; когда они появятся, они обязаны читать тот же предикат.
|
||||
- Проверки контракта. `TestEvidenceOperationsFollowTheConventions`, `TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements`, `TestNoOrganizationOperationReachesRawAssessmentData` и `TestEvidenceWalkReachesTheEvidenceFamily` (Go) и `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) обходят все организационные операции и список кандидата по всем ссылкам и падают на схеме оценки, сигнала или проверки, а также на свойстве с сырым ответом, баллом или провалом.
|
||||
- Не реализовано: операция скрыть или показать факт (колонка и охранник есть, HTTP-операции для изменения нет), заявления профиля как факты, факты из ФСП и других источников, отзыв источника, уровень доверия выше 1, использование доказательств в ранжировании и в PDF "Паспорт навыков", срок хранения. Нужно ли доказательствам отдельное поле карточки вместо `categories`, остается открытым вопросом.
|
||||
|
||||
## Подбор и объяснение
|
||||
|
||||
До ранжирования Go применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия.
|
||||
|
||||
Reference in new issue
Block a user