feat(assessment): keep real attempts in fullscreen and protect the task text

This commit is contained in:
shira committed 2026-10-11 03:03:55 +03:00
1 parent 56dcf32f8c
commit efa41d5967
46 files changed
+1940 -72

No files matched your search

+1 -1
View File
@@ -688,7 +688,7 @@ Code: migration `backend/db/migrations/00033_create_assessment_signal_review.sql
- Why the demo thresholds are 48 and 64 bits, and what the figure means. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` samples 4000 seeds of each of the four demo families (the three integer families have 36 to 47 distinct answers, the dependency order about 2250), builds the distribution of shared values and their bits, and computes the probability that one pair of honest candidates who answer a 23-item attempt correctly reaches each threshold. Multiplied by 10,000 rivals (union bound), the per-attempt false flag rate is about 4e-5 for attention and 3e-9 for review, against test targets of 1e-3 and 1e-8. The model uses the distribution of reference answers: it does not model the distribution of wrong answers or correlated mistakes (candidates who make the same common error, or a shared tutorial), which can make honest coincidences more likely than computed. These are demo values pending calibration on a real bank, with four AI-drafted families. In the other direction, `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` calculates how many answers per family a copied pair needs before the demo thresholds flag it, when the pair copies every answer and nobody else holds those values: for an attempt of 13 items, attention from 26 answers per family and review from 61; for 23 items, from 9 and from 14. A stand with fewer attempts flags nothing by design. To try the feature on a small stand, publish a policy version with lower thresholds in `assessment.signals` (the integration tests do this with 4 and 6 bits); the demo policy is not changed for that.
- Policy. The optional section `assessment.signals` of a schema 2 policy document holds every threshold (`domain.AssessmentSignalPolicy`); a version without it computes no band. `DemoProductPolicyV3` is `DemoProductPolicyV2` plus `DemoAssessmentSignalPolicy`; `DemoProductPolicyV1` and `DemoProductPolicyV2` and the startup seed are unchanged, and a stored version is never rewritten. The band uses the thresholds of the product policy version in `assessment_attempts.product_policy_version_id`, so a policy published later does not change an attempt in progress or a stored review; `assessment_attempt_reviews.policy_version_id` records the version, and a trigger refuses to change it. A matched attempt is re-evaluated under its own pinned version; pairs are selected with the attention level of the evaluating attempt, so across versions with different levels a pair can be missed on the side with the lower level.
- 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.
- Limits. Browser signals can be forged or suppressed, so they are a hint only. The client measures of the attempt page (fullscreen, covering the task, blocking copy, selection, print, and paste) stop only the casual route: the task text is in the candidate's browser, so a screenshot, a second device, or an extension takes it out, and they change no score by themselves. 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
+8
View File
@@ -536,6 +536,14 @@ Unit tests (`make -C backend test`) check the visibility rules without a databas
The tests prove the stored facts, the policy pinning, the job-based computation, and the absence of the band from the contract and from candidate reads. They do not prove detection quality: the thresholds are uncalibrated, the false-positive measurement covers four drafted families, and no study of real candidates exists. The employer reads are covered by the contract walk, not by an HTTP call per operation.
## Assessment lockdown tests
Vitest runs in Node without a DOM, so the lockdown is checked in parts. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` covers support detection (including a browser without element fullscreen, such as iPhone Safari), that the request is issued synchronously inside the call so it stays in the click, and that a refusal is a result and not an exception. `model/cover.test.ts` is the table of when the task is covered: fullscreen exit, a hidden tab, a window without focus, a request in flight, and the mode without fullscreen. `ui/protected-region.test.tsx` renders the region with a fake lockdown and checks that a covered task leaves no text of the prompt or the options in the markup, that a cover for a left tab has no fullscreen button, and the explanation shown for an unsupported browser; `features/answer-assessment/ui/answer-form.test.tsx` checks that a concealed form renders nothing. The notice text version 2 and its list of measures are checked in `features/assessment-signals/ui/signal-notice.test.tsx`. In the backend, `usecase/assessment/signal_notice_test.go` checks that every version except the current one is refused, and `TestAssessmentSignalNoticeOverHTTP` checks over HTTP with PostgreSQL that a stored acknowledgement of version 1 does not count for version 2.
Unit tests of the task protection: `model/task-guard.test.ts` runs the rules with small fake elements and events: selection, the context menu, and drag are cancelled on the task text and left alone in a field, a drop never fills a field, paste is refused in answer fields (and reported, so the screen can say so) and allowed in the code editor, the `beforeinput` routes of paste and drop are closed while typing and composing are never touched, and a copy or cut is refused when the target or the selection reaches into the task but not when it is inside a field. `features/answer-assessment/ui/answer-form.test.tsx` checks that only the code editor carries the paste exception.
Two browser specs run against a mocked API, so they need no backend data and also run against the Vite server (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`) as well as in `make -C deploy test-e2e`; the mock is in `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: leaving fullscreen covers the task (its text is not in the page), sends a `fullscreen_exit` signal, and the continue button restores the task with the typed draft; leaving the tab covers the task and returning in fullscreen shows it; a browser without the fullscreen API shows the explanation and still takes the test from the keyboard; a refused fullscreen request continues without it; closing the notice without confirming leaves fullscreen and stores nothing. `assessment-task-protection.spec.ts`: the task text is not selectable, a select-all or scripted copy leaves no task text in the clipboard, the context menu and drag are cancelled on the task but not in a field, a field copies its own text, the text stays in the accessibility tree, and printing hides the task; an answer field refuses a paste, shows the notice, and the refused paste is sent as a `paste` signal with its size and without its text; the practice code editor accepts a paste and sends its size; an item is answered with the keyboard alone. The notice acknowledgement over the real backend is covered by the existing notice test in `assessment.spec.ts`, which now expects version 2. These specs show the page behavior in Chromium with a mocked server; they do not show behavior in other browsers, on a phone, with a real screen reader, or against a window manager that changes fullscreen on its own. The paste rule cannot see text that an on-screen keyboard inserts as typing.
## Internal notification tests
Unit tests (`make -C backend test`, `make -C frontend test`):
+1 -1
View File
@@ -688,7 +688,7 @@ contact_grant относится к паре кандидат-компания
- Почему демо-пороги равны 48 и 64 битам и что означает эта цифра. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` берет по 4000 seed каждого из четырех демо-семейств (у трех целочисленных 36-47 различных ответов, у порядка зависимостей около 2250), строит распределение общих значений и их битов и считает вероятность того, что одна пара честных кандидатов, верно ответивших на попытку из 23 заданий, достигнет каждого порога. Умноженная на 10 000 соперников (граница объединения), доля ложных пометок на попытку - около 4e-5 для «внимание» и 3e-9 для «проверить» при целях теста 1e-3 и 1e-8. Модель использует распределение эталонных ответов: она не моделирует распределение неверных ответов и коррелированные ошибки (одинаковая типичная ошибка многих кандидатов, общий учебник), из-за которых честные совпадения могут быть вероятнее расчетных. Это демо-значения до калибровки на настоящем банке, измеренные на четырех семействах, написанных ИИ. В обратную сторону `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` считает, сколько ответов на семейство нужно скопированной паре, чтобы демо-пороги ее пометили, когда пара копирует все ответы и больше никто эти значения не держит: для попытки из 13 заданий «внимание» от 26 ответов на семейство и «проверить» от 61; для 23 заданий от 9 и от 14. Стенд с меньшим числом попыток по замыслу ничего не помечает. Чтобы попробовать функцию на малом стенде, опубликуйте версию политики с меньшими порогами в `assessment.signals` (интеграционные тесты делают так с 4 и 6 битами); демо-политика для этого не меняется.
- Политика. Необязательный раздел `assessment.signals` документа схемы 2 хранит все пороги (`domain.AssessmentSignalPolicy`); версия без него не считает полосу. `DemoProductPolicyV3` - это `DemoProductPolicyV2` плюс `DemoAssessmentSignalPolicy`; `DemoProductPolicyV1`, `DemoProductPolicyV2` и стартовый seed не изменились, сохраненная версия не переписывается. Полоса использует пороги версии продуктовой политики из `assessment_attempts.product_policy_version_id`, поэтому политика, опубликованная позже, не меняет попытку в процессе и сохраненную проверку; `assessment_attempt_reviews.policy_version_id` фиксирует версию, а триггер запрещает ее менять. Попытка из пары пересчитывается под своей закрепленной версией; пары выбираются по уровню «внимание» считающей попытки, поэтому между версиями с разными уровнями пара может быть пропущена на стороне с меньшим уровнем.
- Когда и как. Проверка никогда не считается в транзакции кандидата. Первый принятый ответ планирует задание `assessment.signal_review` с ключом `<попытка>:deadline`, срок - через минуту после дедлайна попытки (чтобы ответ, зафиксированный прямо на дедлайне, попал в факты), а завершение планирует `<попытка>:ended`, срок - сразу; оба - вставки в `scheduled_jobs` в транзакции ответа или завершения, повтор ничего не делает. Задание дедлайна покрывает и попытку, которая истекает или брошена, как и когда бы ни менялось ее состояние. Проверка - оценка на момент: она описывает факты, зафиксированные к запуску ее задания, а задание на дедлайне для завершенной попытки запускает ее снова и подхватывает поздние совпадения. Задание считает проверку своей попытки и обновляет проверку каждой другой завершившейся (терминальное состояние или срок прошел) попытки с общими ответами на уровне «внимание» и выше, не более 50 за задание; кольцо больше 50 попыток с общими ответами покрыто тем, что каждый участник запускает свое задание дедлайна и видит остальных. Еще идущую попытку помечает ее собственное задание, когда она закончится и увидит остальные факты. Писатели упорядочены транзакционной advisory-блокировкой на каждую проверку: задание берет блокировки проверок всех попыток, которые будет писать, по возрастанию идентификатора, до чтения любого факта, поэтому более позднее из двух заданий по одной попытке ждет и затем читает то, что зафиксировало раннее (нет потерянного обновления и нет цикла блокировок). Время проверки берется из часов базы внутри upsert, а время обновления не отстает от сохраненного. Больше ничего не блокируется: факты только добавляются, а задание планируется после фиксации его фактов. Сбой повторяется исполнителем с задержкой и никогда не блокирует и не меняет результат; без worker (`JOBS_ENABLED=false`) проверки ждут вместе со своими заданиями. В транзакции кандидата из запросов проверки только вставка задания (и два обновления счетчиков ответа). Задание пишет в журнал одну строку с числом записанных проверок и длительностью, без ответов, адресов и кандидатов. Граница применимости: доля читается из счетчиков за постоянное время, но сравнение соединяет ответы попытки с ответами, у которых те же значения, поэтому цена растет с числом держателей популярных значений, не более 23 заданий на число держателей каждого; для фоновых заданий это нормально на совокупностях до порядка 100 000 ответов на семейство, выше нужна выборка или предел.
- Ограничения. Браузерные сигналы можно подделать или подавить, поэтому это только подсказка. Помощь, например LLM на другом устройстве, не видна. Возможны ложные срабатывания: общая или меняющаяся сеть (мобильный интернет, NAT), перезагрузка страницы, две вкладки, копирование условия и случайные совпадения ответов из малого пространства. Срок хранения этих фактов, нужно ли для их сбора отдельное согласие сверх уведомления и кто калибрует пороги, не решено.
- Ограничения. Браузерные сигналы можно подделать или подавить, поэтому это только подсказка. Клиентские меры страницы попытки (полноэкранный режим, скрытие задания, запрет копирования, выделения, печати и вставки) останавливают только простой путь: текст задания находится в браузере кандидата, поэтому снимок экрана, второе устройство или расширение его выносят, а сами по себе эти меры оценку не меняют. Помощь, например LLM на другом устройстве, не видна. Возможны ложные срабатывания: общая или меняющаяся сеть (мобильный интернет, NAT), перезагрузка страницы, две вкладки, копирование условия и случайные совпадения ответов из малого пространства. Срок хранения этих фактов, нужно ли для их сбора отдельное согласие сверх уведомления и кто калибрует пороги, не решено.
### Доказательства навыков
+8
View File
@@ -536,6 +536,14 @@ Spec не проверяет запланированные переходы б
Тесты доказывают сохраненные факты, закрепление политики, вычисление заданием и отсутствие полосы в контракте и в чтениях кандидата. Они не доказывают качество обнаружения: пороги не откалиброваны, измерение ложных срабатываний покрывает четыре написанных семейства, исследования на реальных кандидатах нет. Чтения работодателя покрыты обходом контракта, а не HTTP-вызовом каждой операции.
## Тесты ограничений во время попытки
Vitest работает в Node без DOM, поэтому ограничения проверяются по частям. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` покрывает определение поддержки (в том числе браузер без полноэкранного режима элемента, например iPhone Safari), то, что запрос делается синхронно внутри вызова и остается внутри клика, и то, что отказ - это результат, а не исключение. `model/cover.test.ts` - таблица случаев, когда задание закрыто: выход из полноэкранного режима, скрытая вкладка, окно без фокуса, запрос в процессе и режим без полноэкранного режима. `ui/protected-region.test.tsx` рисует область с поддельным состоянием и проверяет, что закрытое задание не оставляет в разметке текста условия и вариантов, что у закрытия из-за ухода с вкладки нет кнопки полноэкранного режима, и объяснение для неподдерживаемого браузера; `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что скрытая форма ничего не рисует. Версия 2 текста уведомления и перечень мер проверяются в `features/assessment-signals/ui/signal-notice.test.tsx`. В бэкенде `usecase/assessment/signal_notice_test.go` проверяет, что любая версия, кроме текущей, отклоняется, а `TestAssessmentSignalNoticeOverHTTP` по HTTP с PostgreSQL проверяет, что сохраненное подтверждение версии 1 не засчитывается для версии 2.
Модульные тесты защиты задания: `model/task-guard.test.ts` проверяет правила на небольших поддельных элементах и событиях: выделение, контекстное меню и перетаскивание отменяются на тексте задания и не трогаются в поле, сброс текста мышью никогда не заполняет поле, вставка отклоняется в полях ответа (и об этом сообщается, чтобы экран мог сказать) и разрешена в редакторе кода, пути `beforeinput` для вставки и сброса закрыты, а набор и композиция никогда не затрагиваются, копирование и вырезание отклоняются, когда цель или выделение доходят до задания, и не отклоняются внутри поля. `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что исключение для вставки есть только у редактора кода.
Две браузерные спецификации работают с подставным API, поэтому им не нужны данные бэкенда, и их можно запускать и на сервере Vite (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`), и в `make -C deploy test-e2e`; подставной API лежит в `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: выход из полноэкранного режима закрывает задание (его текста нет в странице), отправляет сигнал `fullscreen_exit`, а кнопка продолжения возвращает задание вместе с набранным черновиком; уход с вкладки закрывает задание, а возврат в полноэкранном режиме показывает его; браузер без полноэкранного API показывает объяснение и проходит тест с клавиатуры; отказ в полноэкранном режиме не мешает продолжить; закрытие уведомления без подтверждения выходит из полноэкранного режима и ничего не сохраняет. `assessment-task-protection.spec.ts`: текст задания нельзя выделить, копирование после выделения всего или из скрипта не оставляет текста задания в буфере, контекстное меню и перетаскивание отменяются на задании, но не в поле, поле копирует собственный текст, текст остается в дереве доступности, печать скрывает задание; поле ответа отклоняет вставку и показывает сообщение, а отклоненная вставка уходит сигналом `paste` с размером и без текста; редактор кода принимает вставку и отправляет ее размер; задание отвечается только с клавиатуры. Подтверждение уведомления с настоящим бэкендом покрывает существующий тест уведомления в `assessment.spec.ts`, который теперь ожидает версию 2. Эти спецификации показывают поведение страницы в Chromium с подставным сервером; они не показывают поведение в других браузерах, на телефоне, с настоящим экранным диктором и в оконном менеджере, который сам меняет полноэкранный режим. Правило вставки не видит текст, который экранная клавиатура вставляет как набор.
## Тесты внутренних уведомлений
Модульные тесты (`make -C backend test`, `make -C frontend test`):