Files
lincodex/docs/en/TESTING.md
T

706 lines
181 KiB
Markdown

# Checks and quality evaluation
Routine checks prove individual code properties. They do not establish ranking accuracy, grade validity, production latency, or complete product readiness.
## Commands
Use the root Make targets:
make test
make check
make verify
make docs-check
make test runs backend, frontend, and ML tests. make check also runs API contract, formatting, lint, type, build, Compose, observability, and documentation checks. make verify sequentially generates contracts, checks generated drift, runs root check, API toolchain/backend race and integration checks, and then starts an isolated deployment smoke. It uses Docker.
Useful focused commands:
| Command | Coverage |
| --- | --- |
| make -C api check | Schema merge, bundles, OpenAPI lint, merge-script tests |
| make -C backend test | Go unit suite with race detector |
| make -C backend test-fast | Faster Go tests without race instrumentation |
| make -C backend test-int | Go integration tests with Testcontainers/PostgreSQL/Redis/SeaweedFS/Kafka |
| make -C frontend check | Prettier, ESLint, Stylelint, TypeScript, Vitest, FSD boundaries, build |
| make -C ml check | Ruff, mypy, pytest, and wheel build |
| make -C ml check-generated | Pydantic models match the ML bundle without rewriting files |
| make -C deploy config | Render Compose configurations without starting them |
| make -C deploy check | Render Compose configurations and run `check-workflows`, which fails when a workflow `aggregate` job does not need every other job or lacks `if: always()`, and `check-release`; see [Release manifest tests](#release-manifest-tests) |
| make -C deploy smoke | Isolated technical smoke of service health routes |
| make -C deploy test-e2e | Playwright browser suite against an isolated throwaway stack |
| make -C deploy release-smoke, release-e2e | The same smoke and browser suite against the release images; a passing run records evidence for the release manifest |
| make -C observability check | Validate Prometheus config and alert rules with their unit tests, Loki, Alloy, and dashboard JSON |
| make -C observability verify-product-metrics | Isolated core and monitoring stacks: product metrics in Prometheus and Grafana, no fixture address in metrics or Loki logs; see [Product metrics tests](#product-metrics-tests) |
make -C deploy test-e2e currently runs a technical browser suite, not a business-flow suite; see [Browser E2E suite](#browser-e2e-suite).
make -C ml check-generated uses datamodel-code-generator --check: a mismatch fails the check and leaves the models file unchanged. Prepare the bundle with make -C api bundle before checking; use make -C ml generate to update Python models. Generated models do not establish inference functionality or support for every OpenAPI 3.2 feature.
Security checks run separately: `make -C security check` scans source/dependencies/secrets, `make -C security test` validates local Semgrep fixtures, installer integrity, and govulncheck failure handling, and `make -C security images` builds and scans all three service images. Install tools with `make -C security install` first. Scanner failure is a failed check, not a clean result. See [SECURITY.md](SECURITY.md) for Git/Docker requirements, blocking findings, and CI reports.
## Current scaffold coverage
Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, the private file layer and SeaweedFS access controls (see [Private file storage tests](#private-file-storage-tests)), the Kafka test harness (keyed records with headers and per-partition order, refusal to create a missing topic on demand, and topic cleanup), the outbox relay (see [Outbox relay tests](#outbox-relay-tests)), the event consumer runtime (see [Event consumer tests](#event-consumer-tests)), mail deliveries (see [Mail delivery tests](#mail-delivery-tests)), metrics, the API client, ML schemas, and current endpoint availability. Registration and email confirmation have API integration coverage; login, assessment, search, invitation, and file workflows are not implemented. Confirmation writes an event to the transactional outbox, with no registered product consumer for that event; mail delivery is tested separately. There is no real model inference to validate as product behavior.
TestEmailVerificationOverHTTP obtains a token from the Resend fixture after registration. It checks candidate and employer confirmation, no session or cookie, and unchanged state after an unknown, expired, replaced, or consumed token, a wrong password, or missing pending credentials. It also checks C1 version binding, missing, null, and foreign Origin values, plus rate limits, expiry after a lock wait, rollback after an outbox failure, and one event from concurrent confirmations. It covers the API only and does not send through an external mail provider. The separate local registration browser flow covers the frontend.
TestEmailVerificationCodeOverHTTP (`backend/integration_test/email_code_test.go`) takes the code and the link from the same fixture message. It checks that the code confirms like the link; that five wrong codes burn the token, after which the right code and the link both fail; that eight concurrent wrong codes count exactly five attempts; that a wrong password counts; that an expired code leaves the link valid; that the link and the code consume one token in either order; that a resend replaces the code; that a registration replaced by another registration cannot be confirmed with its code; that an unknown address and a wrong code give the same refusal; and that the address limit answers 429 after ten requests. Its origin case refuses a foreign Origin before the usecase runs.
API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub.
Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, rejection of anonymous SeaweedFS bucket access, isolation of SeaweedFS from the frontend (by name and by its storage network address), rejection of filer, master, and volume HTTP requests that do not come from inside the SeaweedFS container, and the backend startup log for `EMAIL_PROVIDER=disabled`. The backend relay connects to Kafka in the smoke stack, but the smoke does not check that it publishes. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It sends no mail and does not check mail delivery, contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application.
## Browser E2E suite
`make -C deploy test-e2e` runs the Playwright suite from `frontend/e2e/` in Chromium against the real frontend and backend images. It needs Docker and frontend dependencies installed with `make -C frontend install`; no browser is installed on the host. `deploy/scripts/e2e.sh` does the following:
- Reads the exact `@playwright/test` version from `frontend/package.json`, checks that the installed package matches it, and runs the suite in the official `mcr.microsoft.com/playwright:v<version>-noble` image with `frontend/` mounted read-only.
- Starts the core stack under a unique project `lincodex-e2e-<random>` with fresh volumes and a generated throwaway env file: random passwords, `EMAIL_PROVIDER=disabled`, no mail transport settings. Shell variables other than Docker client settings do not reach Compose. The run refuses to reuse an existing project, network, or volume.
- Publishes no host port. The browser container shares the frontend container's network namespace, so it opens `http://localhost:8080`, the same loopback origin as `APP_PUBLIC_URL`. The Playwright config refuses a base URL outside a loopback host.
- Runs Playwright with the host UID/GID on rootful Docker; on rootless Docker it uses container UID 0, which maps to the owner of the host artifact directory. The runner drops all capabilities and mounts the source read-only.
- Waits for backend readiness, runs the suite with retries disabled, and returns its exit code; make reports any failure as exit status 2.
- Removes the containers, volumes, network, locally built images, and env file on every exit, including failures and interrupts. Only the cached Playwright image and the build cache remain.
Every browser of a run reaches the stand from the same client address: the browser container shares the frontend container's network namespace, so the app Nginx sees all requests from loopback. The per-address limit on `/api/v1/` (20 requests per second with a burst of 60, `deploy/nginx/nginx.conf` and `deploy/nginx/conf.d/app.conf`) is therefore one budget for the whole suite. A 429 from that limit is a failed stand, not a result of the flow under test, and the production limits stay unchanged; `deploy/scripts/test_perimeter.py` keeps checking them. The suite stays inside the budget by design. `frontend/playwright.config.ts` runs one worker. `frontend/e2e/assessment.spec.ts` pauses 250 ms after each saved answer of a full attempt, because a candidate reads each item. The real-bank search in `frontend/e2e/match-search.spec.ts` runs first, in its own project: an unfiltered bank search keeps ten entries per group, so candidates published by earlier specs would decide which entries the test sees. On the stand, a replay of this limit over the access log peaked at about two thirds of the burst with one worker and within about ten requests of it with two workers.
Artifacts of the last run are in `frontend/test-results/e2e/`, which Git ignores; the runner prints the path. `report/` holds the HTML report (`pnpm exec playwright show-report test-results/e2e/report` from `frontend/`). For each failed test, `results/` keeps `trace.zip` and a screenshot (`pnpm exec playwright show-trace <trace.zip>` needs a local browser; trace.playwright.dev opens the file without one). After a failed run, `stand.log` holds the stack logs. `E2E_SPEC_DIR=<dir>` runs specs from another directory, such as a scratch copy, against the same isolated stack.
## Local registration browser tests with a mail fixture
`make -C deploy test-e2e-registration` runs the same disposable browser stack with the additional `docker-compose.e2e-mail.yml` overlay. Only this mode builds the backend with the Go `e2e` build tag: its Resend constructor uses the fixed `http://mail-fixture:8025/emails` endpoint, and Compose supplies a synthetic key. Before Playwright starts, the runner sends one synthetic message through the Compose network, replays the same idempotency key, and verifies the message in the authenticated inbox. The `mail-fixture` service accepts Resend-compatible requests, deduplicates by key, and keeps at most 64 messages and 256 requests of up to 32 KiB each in memory. Its inbox requires bearer authentication, returns only messages for the requested `to`, and is reachable inside the stack. The registration network is marked internal, the fixture is not connected to the storage network, and no host port is published; requests cannot reach an external mail provider. Cleanup removes the containers and inbox.
Playwright receives `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-fixture:8025/__e2e/inbox`, and the synthetic `E2E_MAILBOX_TOKEN=local-e2e-mailbox-token`. A test requests `GET $E2E_MAILBOX_URL?to=<urlencoded email>` with `Authorization: Bearer $E2E_MAILBOX_TOKEN`; the response contains `messages` with `id`, `to`, `subject`, `text`, and `html` fields. Registration-only tests should skip unless `E2E_MAIL_FIXTURE=1`, because neither ordinary `test-e2e` nor `release-e2e` sets it. Tests must not print message content or a link containing a one-time token. The runner disables Playwright tracing in this mode. The ordinary `test-e2e` still sets `EMAIL_PROVIDER=disabled`, and `release-e2e` uses release images without the fixture and records no evidence for a mail-fixture image. The registration mode refuses to run with `LINCODEX_RELEASE_TAG`.
The current suite (`frontend/e2e/smoke.spec.ts`) checks that the SPA serves `/` with `lang="ru"` and its heading, that `/status` shows the technical page with a live API, that `/api/v1/healthz` returns 200 `{"status":"ok"}` through the frontend proxy, that an unknown SPA route shows the not-found page, and that `/api/v1/missing` returns 404 `application/problem+json` with code `not_found`. It needs no data. Business tests use synthetic data in each fresh stack: registration through the public API and the separately documented test fixture for consent scopes. No real data are used.
`frontend/e2e/mail-unavailable.spec.ts` runs only in the ordinary `test-e2e`, whose stand sets `EMAIL_PROVIDER=disabled`, and skips when `E2E_MAIL_FIXTURE=1`. On the real backend it registers a candidate (202 `accepted`) and checks that the step waits for the message ("Запрос принят", "Письмо может прийти не сразу") and never says that a message was sent or delivered. A guessed code and a forged link answer 400 `verification_token_invalid`; the correct password answers 403 `email_not_verified` with the message in the form; afterwards `GET /api/v1/identity/sessions/current` and `GET /api/v1/me/profile` answer 401 and `/candidate` shows the sign-in page. The browser cannot see the delivery row: that it stays `pending` without an attempt while the transport is disabled is checked by the `EMAIL_PROVIDER=disabled` subtest of `TestServiceMailSending`.
The ordinary technical suite does not cover candidate or employer workflows beyond the unconfirmed registration of `mail-unavailable.spec.ts`, a successful sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, or screen readers. Its stubbed checks of the minimal path states, focus, and overflow are described in [Minimal path states and accessibility](#minimal-path-states-and-accessibility). CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-<n>` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate.
The registration-mode suite additionally runs `frontend/e2e/auth-registration.spec.ts`: candidate and employer registration with visible C1, real local resend and a distinct received message, same-tab replacement of the verification link, wrong-password retry, confirmation without automatic login, sign-in, and restoring the server step after reload. It checks keyboard focus and overflow at 360, 768, and 1280 pixels. Expired-link rendering uses a controlled problem response; actual token expiry is covered by backend integration tests. Only this isolated overlay sets `VERIFICATION_MAIL_MIN_INTERVAL=1s`; normal and release environments retain their configured interval. Auth traces, failure screenshots, and video are disabled; explicit review screenshots show only token-free states and synthetic addresses. No external mail or production edge flow is verified.
Since the code step, the same suite confirms each candidate and employer registration with the six-digit code from the message: a wrong code first, a reload that asks for the password again, and a check that no browser storage holds the password. A separate test keeps the link as the fallback: an expired link leads to the code step, which sends a new message, and the link from that message then confirms the registration.
In the same mode, the runner invokes `/consent-fixture` from the test backend image before starting the browser. The command exists only with the Go `e2e` build tag, requires `E2E_CONSENT_FIXTURE=1`, and uses domain objects and transactional ports to create a synthetic verified candidate, C1/C2, and two C4 scopes for different companies. A collision with an existing test address stops the run. Ordinary and release images contain neither the command nor its enabled flag. `frontend/e2e/consent-management.spec.ts` uses normal sign-in and real consent APIs to grant C3 independently, revoke C2 and one C4, retain the other scope, reload, and submit a C1 request whose returned status is shown. A controlled 403 exercises the failure UI; successful mutations reach PostgreSQL. Synthetic invitation IDs in the fixture do not prove the invitation acceptance flow. Traces and automatic screenshots are disabled; the explicit review screenshot contains only synthetic data.
The same command also seeds a second synthetic candidate for `frontend/e2e/privacy-visibility.spec.ts`: an active C1 and C2, one C4 for the first of two new companies, and three recorded card reads (a card view and a contact read by the first company, a card view by the second). The reads are inserted through the privacy port because the organization read path needs search results that do not exist yet; they do not prove that path. With the real backend, the suite confirms the search status without publishing, publishes after the explicit C2 step, compares the owner preview with the API response, hides one company and brings it back, revokes C2 and checks the closure explanation, grants C2 again without reopening the card, and republishes with the keyboard alone; in the mail-fixture mode a freshly registered candidate with two declared specializations and no test publishes and sees the not-confirmed grade status for each. A stubbed group renders a confirmed Backend next to unconfirmed specializations, the evidence basis and calibration labels, empty histories, a failed save that keeps the draft, and a revoked C2. No test reads the card as an employer, so the immediate loss of access of a hidden employer is not checked in a browser.
`frontend/e2e/profile-edit.spec.ts` walks the steps of the manual profile at 360px after real registration ("Далее" with the focus on the heading, a step blocked until overlapping periods are confirmed, "Назад" without losing data), acknowledges overlapping employment periods, saves, and reloads the data. A second context changes the version through the API; the first window keeps its draft on 412 and replaces it only through an explicit action. The test checks frozen fields during PUT, focus, no overflow at 360/768/1280px, and rejection of a late response after an account switch. Saving a profile does not count as completion of the consent step.
`frontend/e2e/candidate-home.spec.ts` has two parts. In the mail-fixture mode a candidate goes through registration, a profile with only a name (no FSP ID linking), the questionnaire, and signing in again: the home leads to the profile, then the questionnaire, then the test, shows the declared level apart from the empty confirmed category, and matches the `GET /me/assessment-availability` answer after a page refresh. The saved step stays "Consents" throughout, because the server advances it only from the matching step. The second part also runs in the ordinary `test-e2e`: it replaces API answers (`page.route`) and checks only how the home renders each state - a category with the result and privacy links, an open card and search status, no category with an empty history, a failed attempt, a failed read with retry, a denied read, a failed privacy read, and an expired session. It does not prove backend behavior and does not replace a check of category assignment on a real stack, which this spec does not perform. Review screenshots (360 and 1280 px) contain only synthetic data.
`frontend/e2e/company-management.spec.ts` creates a company, retries a lost response with the same key and body, edits the profile, and compares its preview with the API. Controlled responses check CSRF recovery, version conflict, and a delayed response. A separate `company-fixture` performs real revocation: Go build tag `e2e`, an explicit enable flag, a random bearer token per run, no published port, and only the internal network. It validates two synthetic verified employer accounts, adds a successor owner, and revokes the original owner in one transaction while preserving the mandatory-owner constraint. The browser with its original cookie checks real API denial and removal from its directory. The control endpoint is absent from the ordinary backend and release image; its URL and token reach only the test process through `E2E_COMPANY_FIXTURE_URL` and `E2E_COMPANY_FIXTURE_TOKEN`.
## Minimal path states and accessibility
`frontend/e2e/minimal-path-a11y.spec.ts` checks the states, the keyboard path, and the error binding of the sign-in, the candidate test start and profile, the candidate inbox, and the candidate invitation screen. Failures come from route interception, so no data is needed on the stand: HTTP 500 and 403 answers, a dropped connection, and the empty and forbidden answers. Each stubbed screen is checked at 360, 768, and 1280 px for horizontal overflow; the real-backend assessment check covers 360 and 768 px. Each control reached with Tab must match `:focus-visible` and draw a focus outline. The stubbed part runs in both `make -C deploy test-e2e` and `make -C deploy test-e2e-registration`. The one real-backend test runs only in the registration mode, because it needs the mail and questionnaire fixtures.
The other screens of the minimal path are covered by their existing specs: the employer candidate search and match list (`match-search.spec.ts`: a failed search with a retry, a refused search, an empty result, confirmed and declared grades as text, keyboard reach at every width), the invitation compose (`invitation-compose.spec.ts`: errors bound to fields, a lost send response retried with the same key, overflow at 360, 768, and 1280 px), registration and confirmation (`auth-registration.spec.ts`), and the profile and questionnaire (`profile-edit.spec.ts`, `questionnaire.spec.ts`).
Checklist for the minimal path. Each item is checked by the spec named in brackets; the result is the outcome of the last run of that spec.
- Sign-in [`minimal-path-a11y.spec.ts`]: Tab reaches both fields and the submit control with a visible outline at 360, 768, and 1280 px. An empty submit marks both fields `aria-invalid` and gives each one its message through `aria-describedby`. A failed answer keeps the typed email and keeps the focus in the form. While the answer is pending, the password field stays focused and read-only; it is not disabled, because a disabled field drops the focus.
- Candidate profile [`minimal-path-a11y.spec.ts`]: a loading text while the profile loads, an alert with a retry after a failed load, and no retry after an access refusal.
- Candidate test start [`minimal-path-a11y.spec.ts`]: an alert with a retry after a failed availability read; a candidate without a specialization sees the empty state with a link to the questionnaire.
- Candidate inbox [`minimal-path-a11y.spec.ts`]: a loading text; a server error or a dropped connection gives an alert with a retry that works from the keyboard; the empty state; no retry after an access refusal; each card names the company, the role, and the state as text.
- Candidate invitation [`minimal-path-a11y.spec.ts`]: an alert with a retry after a failed load; a failed decline keeps the chosen reason and the comment and moves the focus to the alert; the declined state is shown as text.
- Assessment on a phone with the real backend [`minimal-path-a11y.spec.ts`, registration mode]: an unsent numeric answer survives a reload at 360 px, and the stored copy is removed when the answer is accepted.
- Employer match list and invitation compose: see the specs named above; the compose page is also checked at 768 px.
- Not covered by these checks: screen reader output, the contrast of the focus outline, and zoom above 200 percent. They were not checked by hand in this pass.
An unsent answer is kept in `sessionStorage` of the same browser tab, under a key that names the attempt and the item. It is never sent to the server. A reload restores it only when it fits the item; a stored value larger than 64 KiB is not kept; a blocked or full store leaves the answer in the form only. An accepted answer removes the stored copy. Answers accepted by the server come from the server after a reload.
## Release manifest tests
`make -C deploy check-release` runs `deploy/scripts/test_release_manifest.py` with the Python standard library and without Docker. It fails when go.mod, the `GO_IMAGE` default, and `GOTOOLCHAIN=local` in backend/Dockerfile or backend/Dockerfile.demo-seed stop pinning Go 1.26.9, or when a service Dockerfile uses a base image that is not a pinnable `*_IMAGE` build argument, including an external image in `COPY --from` or `RUN --mount=from`. On fake image, Compose, and container data it checks that:
- the manifest copies no environment values, labels, or local paths, and two generations differ only in `generated_at`;
- evidence counts only for the same tag, commit, and working tree fingerprint, and malformed evidence or build records are not used;
- a component is `verified` only with evidence for its exact image ID, ML, monitoring, and missing components are never verified, and the release stays unverified without both smoke and E2E on the current images, on a dirty tree, with a core pulled image without a registry digest, a missing lockfile or Dockerfile, another Go version in the binary, or another Node version in the build image;
- `release-build` refuses to write the build record when the commit or the working tree changes during the build;
- the working tree fingerprint of a temporary Git repository ignores diff and line ending settings, covers untracked files, skips ignored ones, and leaves the real index unchanged;
- the secret scan finds key blocks, tokens, credentials in URLs, local paths, user and host names, and values of secret-like variables, also as substrings and in base64, without echoing them;
- the running-container comparison reports a different digest, a missing service, and an unknown service;
- the demo seed image is built with pinned base images under its profile, recorded but never verified, and retained by its image ID; its absence blocks only the demo stand restore, a Go drift in its binary keeps the release unverified, and the demo override pins the core services and the seed to exact image IDs and digests and refuses a missing image, a changed demo overlay, or a manifest without a demo restore entry;
- the `seed` entry hashes the non-test demo seed sources, and its version changes with them but not with a test file.
The test does not build images or start containers. The end-to-end path is `release-build`, `release-smoke` and `release-e2e`, `release-manifest`, `release-up`, `release-manifest-verify`, and `release-manifest-check`; see [DEPLOY.md](DEPLOY.md#release-manifest).
## Integration test bootstrap
The shared helper lives in `backend/integration_test/bootstrap_test.go`. Calling `env := bootstrap(t)` starts PostgreSQL, Redis, and SeaweedFS, waits for adapter readiness, and returns an environment with configuration and clients. To test one adapter, use `bootstrap(t, postgresService)`, `bootstrap(t, redisService)`, or `bootstrap(t, seaweedfsService)`. Multiple services can be selected.
Call bootstrap once in the parent test and share its environment with its subtests. Each call creates separate containers with dynamic ports and a separate SeaweedFS volume when needed. Cleanup is registered through `t.Cleanup`, including partial startup. Redis outage and SeaweedFS recreation scenarios manage resources through environment helpers without affecting other tests. Tests fail when Docker is unavailable. Testcontainers also tries the Docker context and default sockets when `DOCKER_HOST` is unreachable, so an invalid `DOCKER_HOST` alone does not simulate a missing Docker.
Container startup makes at most three attempts, and only when rootless Docker returns the exact host-port networking error ending in `bind: address already in use` (`EADDRINUSE`). Before retrying, bootstrap terminates any partial container returned by the failed attempt; a cleanup error stops retries. Other startup and readiness errors, and test assertion failures, are not retried. This changes test setup behavior only and does not modify Docker or host networking configuration.
Bootstrap starts infrastructure and clients. When PostgreSQL is selected, it applies every embedded migration with the startup runner. `postgres_helpers_test.go` adds `env.newPool` for a pool to that database, `env.createIsolatedDatabase` for a separate database in the same container when a test changes the whole schema (for example up, down, and up again), `env.newPoolWithMaxConns` for concurrency tests that need one connection per transaction, and `truncateTables` for resetting shared tables between sequential subtests. Tests reach the transaction behind a unit of work only through `postgres.TransactionForIntegrationTest`, which is compiled only with the `integration` build tag. Test-only aggregates live in their own schema created by the test, not in production migrations. The application HTTP server, ML, and product fixtures are not included yet. The full-environment test exercises combined PostgreSQL, Redis, and SeaweedFS readiness.
Kafka is not part of `bootstrap(t)` and starts only for tests that select `bootstrap(t, kafkaService)`. It runs the same `apache/kafka:latest` image as Compose with the same KRaft settings, including `KAFKA_AUTO_CREATE_TOPICS_ENABLE=false`. The client listener is advertised on the dynamic host port, inter-broker and controller traffic stay on container loopback, and the data and declared image volumes use tmpfs, so a test broker leaves no volumes. Bootstrap sets `env.Config.KafkaBrokers` and creates `env.KafkaAdmin` from franz-go `kadm`.
`kafka_helpers_test.go` contains the helpers. `env.createKafkaTopic(ctx, t, partitions)` creates a topic with a unique random name and registers its deletion in `t.Cleanup` before creation, so the topic is removed even when the test fails. The broker never creates topics on demand: a test creates every topic it uses. `env.newKafkaClient(t, options...)` returns a `kgo` client that closes when `t` finishes. `produceKafkaRecords` and `env.consumeKafkaRecords` have bounded timeouts; the consumer reads partitions from the start without a consumer group, so no group offsets remain. The container is terminated in the cleanup of the test that called bootstrap, including after a failure. `env.pauseKafka(ctx, t)` freezes the broker with `docker pause` and returns a function that resumes it; cleanup also resumes it. A paused broker keeps its port and accepts connections but never answers, which models a hung broker. A stopped and restarted container would get a new host port that neither the advertised listener nor the clients follow, and its tmpfs topics would be gone.
## Private file storage tests
Unit tests in `backend/internal/usecase/files/` use an in-memory storage fake that, like an HTTP object store, commits an object as soon as it receives the declared number of bytes. They cover policy validation, key format and rejection of keys from other namespaces or shaped by clients, name sanitizing, the declared size limit, a source that is longer or shorter than declared (storage never receives a complete body and the key is deleted), cleanup after caller cancellation and after a lost response, a reported cleanup failure, the SHA-256 digest, a stored body that differs from its size, idempotent deletion, closing of the response on every `Open` rejection, and unique, valid declared namespaces. Adapter tests in `backend/internal/adapter/secondary/seaweedfs/` check that an upload and a download that last longer than `SEAWEEDFS_TIMEOUT` complete, while stalled response headers and an unreachable endpoint still fail within that bound.
The SeaweedFS bootstrap uses the same entrypoint and flags as Compose and also publishes the filer, master, and volume ports so tests can probe them. It does not model the Compose storage network; smoke checks that boundary. `TestPrivateFileStoreAgainstSeaweedFS` in `backend/integration_test/files_store_test.go` uses `bootstrap(t, seaweedfsService)` and the real adapter:
- writes and reads a synthetic object and an empty one, checking content, size, type, and digest;
- sends unsigned requests and expects 403 from S3 for object reads (also with a presign-like query), bucket listing, upload, and deletion, and 401 from the filer for object reads, listing, and upload and from the master for volume assignment and collection deletion; the object stays readable afterwards;
- assigns a file ID inside the container and expects 401 from the volume for a read without a token and for a write with the signed token that the master returned;
- checks that a wrong secret cannot open, upload, or delete files and is not reported as absence;
- opens, partly reads, and closes the object more times than the adapter's connection limit with a long storage timeout, so a leaked response body would block the loop;
- rejects uploads over the limit or past or short of the declared size and lists the namespace through a separate signed client to show that no partial object remains;
- deletes the object twice and then gets `files.ErrNotFound`.
The probes run from the host through published ports, so requests do not come from inside the SeaweedFS container, as for another member of the storage network. The gRPC and admin ports are not probed; their remaining exposure is described in [ARCHITECTURE.md](ARCHITECTURE.md#private-file-storage).
## Outbox relay tests
Unit tests (`make -C backend test`) cover the record envelope, key, and headers and an invalid payload that is not quoted in the error (`internal/adapter/secondary/kafka/`), a publish and a topic creation that fail within the produce timeout plus a 2-second scheduling margin when the broker is unreachable (the tests assert the elapsed time), the mapping of an unknown topic to `ErrEventDestinationMissing`, the comparison of an existing topic with the configured layout, the shared backoff schedule with and without jitter (`internal/worker/retry/`), relay passes that mark only acknowledged events, retries after failed `Prepare` calls and passes, no backoff after a pass that published part of its batch while a poison event leads every batch, a new `Prepare` after a missing destination, at most one backlog read per interval, a pass in progress that finishes after cancellation, a pass canceled by the shutdown timeout, a stop during backoff (`internal/worker/outboxrelay/`), the relay and topic settings, including the broker-default replication factor and `min.insync.replicas` (`config/`), SQLSTATE-only database errors and timeouts that would round to no limit (`internal/adapter/secondary/postgres/`), the relay counter and backlog gauges, and an application that runs the relay while serving and stops it with the servers (`internal/bootstrap/`).
`TestOutboxRelay` in `backend/integration_test/outbox_relay_test.go` uses `bootstrap(t, postgresService, kafkaService)`, writes events through the transactor with a test aggregate, and runs these sequential cases, each with its own topic:
- A committed event is published as the documented envelope with its key and headers, and `published_at` is set.
- Kafka outage: with the broker paused, a business transaction still commits, the relay pass fails within the produce timeout, both events stay pending, and the business rows are intact. After the broker resumes, the relay publishes both and a consumer receives them with their `event_id`.
- Failure between publish and mark: a publisher wrapper produces for real and then cancels the pass, as a killed process would; the row stays pending, and a new relay publishes it again, so the topic holds two records with the same `event_id`.
- Competing claims: while one claim holds the earliest events of two aggregates, a second claim on a pool with a 500 ms `lock_timeout` gets only the third aggregate, without waiting and without the first aggregate's version 2; the next pass gets version 2.
- Two relays run while 12 concurrent writers each commit 8 versions of their own aggregate. Every event is published, each aggregate stays in one partition, and the first delivery of each version follows `aggregate_version` order. A publisher wrapper adds 10 ms to every publish so the relays' passes overlap; the test logs how many events each relay published.
- Shutdown with the broker paused and a 30-second produce timeout: the relay stops no sooner than the 1-second shutdown timeout and within 5 seconds after it, so only the shutdown timeout could have ended the pass; its event stays pending, and no connection stays busy.
- Idle timeout: a claim whose publish callback ignores its context for 2 seconds, with a 300 ms `idle_in_transaction_session_timeout`, fails with SQLSTATE 25P03; the event stays pending, and no connection stays busy.
- `Backlog` reports zero for an empty outbox and two pending events with a positive age after two writes.
- `Prepare` creates a topic with the configured partitions, the broker default replication factor, and a topic-level `min.insync.replicas`, and accepts the topic again.
The suite runs against one broker and one PostgreSQL. It does not measure throughput or latency, and does not cover broker failover or replication. Consumers are covered in [Event consumer tests](#event-consumer-tests).
## Event consumer tests
Unit tests (`make -C backend test`) cover the consumer runtime with a fake source, store, and handler (`internal/worker/eventconsumer/`): applied, duplicate, and ignored records committed in poll order; store failures retried beyond the attempt limit without a dead letter, with the offset committed only after the store succeeded; a handler that keeps failing, retried exactly `MaxAttempts` times with at least the minimum backoff between attempts, then dead-lettered with its event ID, type, value size, and SHA-256 while the next record is applied; `ErrEventRejected` and a panic dead-lettered after one attempt without quoting the panic value; an invalid record dead-lettered without calling the handler, with the commit waiting until two failed dead letter writes succeed; a shutdown that abandons a stuck handler after the grace without committing it or anything after it; a record that finishes within the grace and is committed while the next one is not started; no retry and no dead letter during shutdown; backoff after failed polls; commits that PostgreSQL refuses after the handler swallowed an error, counted as attempts and ending in `retries_exhausted`; a serialization conflict at commit retried as an attempt; a panic in `Handles` dead-lettered without quoting its value; the prefix commit right after a dead letter, before the next record starts; `poll` and `commit` failure counts; and the reason sanitizer. The PostgreSQL adapter tests classify refused, conflicting, and transport commit failures and check that handler errors keep their identity without the PostgreSQL message. They also cover envelope decoding and its round trip with the producer, every rejected envelope rule without quoting the value, and commit bookkeeping of the group member, including the refusal of finished records that are not a gap-free prefix of the last poll per partition (`internal/adapter/secondary/kafka/`), the consumer settings and the rebalance budget, including the documented 42.5-second default (`config/`), the consumer counters (`internal/adapter/secondary/prometheus/`), and in `internal/bootstrap/` the skip cases, one consumer per handler, rejected duplicate and invalid names, the registered delivery handler, label values that match the prepared metrics, and an application that runs a consumer while serving and returns only after it stopped polling.
`TestEventConsumer` in `backend/integration_test/event_consumer_test.go` uses `bootstrap(t, postgresService, kafkaService)`. Its handler exists only in the test: it writes one row per applied event into `consumer_test.effects`, a table without a unique key that the test creates, so a second effect would stay visible. The sequential cases, each with its own topic and group, are:
- One event ID delivered three times, twice on partition 0 and once on partition 1, next to another event: the group commits both partitions, each event has exactly one effect row and one marker, and the counters show 2 `applied` and 2 `duplicate`.
- Two consumers race on one event without Kafka: each reads the same record from an in-memory source. The first holds its uncommitted marker inside the handler until the test sees, in `pg_stat_activity`, the second consumer's marker insert waiting for a lock; then the first commits. The result is one effect, `applied` for the first and `duplicate` for the second, without the second calling its handler.
- The same race where the first handler fails after the second started waiting: the first rolls back, the second applies the event, and the first's retry finds the marker. One effect row.
- Restart before commit: a handler writes its effect and then blocks past a 300 ms shutdown grace, as a process killed before the commit. After the stop there is no effect row, no marker, and no committed offset for the group. A new consumer in the same group receives the record, applies it once, and commits offset 1.
- Crash after the database commit but before the offset commit: the effect and marker are committed directly, then the record is consumed. It is a `duplicate`, the handler is not called, and the offset is committed.
- Invalid record followed by a valid one on one partition: one dead letter row with offset 0, the header event ID, class `invalid_record`, zero attempts, the value size and SHA-256, and a reason that does not quote the value; the valid event is applied; offset 2 is committed; the `dead_lettered` counter is 1; and no further dead letter appears within 500 ms.
- A handler that always fails for one event, with 3 attempts and a 200 ms backoff: exactly 3 attempts at least 100 ms apart and within 5 seconds, a `retries_exhausted` dead letter with the event ID, type, and handler error, no effect row of that event because every attempt rolled back, the next event applied, offset 2 committed, a handler failure count of 3, and no further attempt within 500 ms.
- Hard crash before commit: the handler writes its effect, reads its own backend PID, and ends that backend with `pg_terminate_backend`, as a crashed process or a dropped connection would. The backend disappears from `pg_stat_activity`, no effect row, marker, or committed offset remains, and a new member of the group applies the event once.
- A handler that runs `SELECT 1 / 0`, ignores the error, and returns nil: PostgreSQL refuses each commit, the consumer counts 3 handler attempts and no store failure, writes a `retries_exhausted` dead letter, commits offset 1, and leaves no effect or marker.
- Dead letter upsert: the same record written twice keeps one row with the second outcome; another value at the same position gets its own row.
- Rebalance handover with two members of one group: the first member's commits always fail, and it holds a record while a second member joins; the test waits until the group is in `PreparingRebalance`, releases the record, and waits until the group is stable with one partition per member. Each of four events has exactly one effect, the first member handled both first-round events before the rebalance, the joiner received nothing of the moved partition's first round (its position was committed in the revocation, the only commit path left) and counted no duplicate, the first member never tried to commit or handle a record of the moved partition after losing it, and after the first member leaves, the group's offsets are 2 on both partitions, so the moved partition was not rewound.
- An event appended to the outbox through the transactor, published by the relay, and consumed: the decoded event matches the outbox row, so the producer and consumer agree on the envelope.
`TestPostgresMigrations` also checks that migration 00005 creates and drops both consumer tables. The suite uses one broker, one PostgreSQL, and test-only handlers. It does not measure throughput, does not cover a rebalance under load or with more than two members, broker failover, a member removed after the rebalance timeout, and does not check alert delivery; the product handler has its own [Mail delivery tests](#mail-delivery-tests).
## Mail delivery tests
Unit tests (`make -C backend test`) cover the delivery model and its creation path:
- `internal/domain/`: the content hash covers the version, subject, both parts, and part borders; content that no transport could send or that belongs to another kind is refused; a changed stored body fails the integrity check; a new delivery starts `pending`, due at creation, with version 1, the key `delivery/<id>`, and an optional source event; every attempt outcome applied to `pending`, `waiting_quota`, and `unknown` gives the documented status, attempt number, version, times, and provider ID, including `waiting_quota` without a known reset, and `accepted` and `rejected` refuse every further attempt; inconsistent attempt results are refused; `WaitForQuota` parks `pending` and `waiting_quota` with a known or unknown reset without an attempt, refuses `unknown` and terminal deliveries and times before the last change, and a later attempt must not precede it; `Rebind` changes only the provider account and version before the first attempt and is refused after it; stored rows that break an invariant are refused; a mail request accepts only the notification kind and storable text; and `fmt` and `slog` output of a delivery, its content, and a mail request never shows the address, subject, body, request text, or token.
- `internal/usecase/notification/`: a request stores its text under the event's aggregate ID and the event payload carries only `mail_request_id` and `kind`; invalid requests write nothing; the handler stores one delivery under the request ID with the source event, the account address, the rendered content, the configured provider account, and the clock time, and deletes the request; the same event again finds no request; an existing delivery under the request ID is accepted for the same recipient and kind and rejected otherwise; broken events (another schema version or aggregate, a malformed payload, trailing data, a request ID that is not the aggregate ID, a token mail kind) and text the template refuses are rejected without quoting the payload; a request that is gone, an account that is gone, and an unverified address are skipped with a log line that names only the delivery and event IDs; storage failures, including an account deleted between its read and the insert, stay retryable and keep the request; and no error or log line holds the address, subject, or body.
- `internal/adapter/secondary/postgres/`: delivery and mail request constraint errors map to their sentinels (`deliveries_content_immutable` and `delivery_attempts_immutable` to `ErrDeliveryContentImmutable`, `deliveries_provider_pinned` to `ErrDeliveryProviderPinned`, the user foreign keys to `ErrUserNotFound`), and any other PostgreSQL error, such as a check violation, keeps only its SQLSTATE and constraint without the message or detail.
- `internal/usecase/notification/mailtemplate/`: a rendering converts to the stored content with the same kind, version, parts, and hash.
- `config/` and `internal/bootstrap/`: `EMAIL_ACCOUNT` defaults to `default`, accepts labels up to 64 characters, and refuses empty, mixed-case, key-like, and oversized values without echoing them; bootstrap registers exactly the `notification_delivery` and `notification_inbox` handlers and refuses an invalid account label.
`TestMailDelivery` in `backend/integration_test/delivery_test.go` uses `bootstrap(t, postgresService, kafkaService)` and the real request usecase, handler, relay, consumer runtime, and stores. Its sequential cases are:
- One event processed twice through the consumer: a request for a verified account is recorded in a business transaction, the relay publishes its event, the row is marked unpublished again as after a crash before the `published_at` commit, and the relay publishes it a second time with the same event ID. The consumer commits offset 2 and counts one `applied` and one `duplicate` record; the database holds exactly one delivery, addressed to the account, rendered with `notification.v1`, pinned to the configured provider account, naming the event as its source, and `pending` with no attempt, and no mail request remains.
- A template change after creation: a first request is stored with `notification.v2`. A handler with a test renderer that stands for the later version `notification.v3` stores a second request with the new version, and a replay of the first request under another consumer name finds its request consumed and stores nothing. The first delivery, read through a new pool, still has the `notification.v2` subject, parts, and hash, and a direct `UPDATE` of its body fails with `deliveries_content_immutable`.
- Restart persistence: one pool records an `unknown` attempt with a provider code and a wait hint with sub-millisecond parts, loses a second write of the same attempt with `ErrDeliveryVersionConflict`, records an `accepted` attempt with a provider message ID, and closes. A new pool and store read the delivery as `accepted` with that ID, two attempts, and version 3, and both attempt rows exactly as written, the wait hint to the nanosecond; a further attempt is refused, and an `UPDATE` of an attempt fails with `delivery_attempts_immutable`.
- Rebind and quota wait: a delivery without attempts is moved to another provider account and parked in `waiting_quota` with an unknown reset, a stale second write fails with a version conflict, and no attempt row exists; after an attempt, `Rebind` is refused by the domain and a direct `UPDATE` of the provider account fails with `deliveries_provider_pinned`.
- A notification to an unverified address stores no delivery, deletes its request, and logs the delivery ID.
- A request whose account is deleted loses its request row with the account; the handler then stores no delivery and logs the delivery ID.
- The unverified account cleanup skips an account whose delivery row another transaction holds, deletes it once the lock is gone, and its pending request and its delivery, created directly through the repository as token mail will be, go with it.
Every case checks that the captured handler and consumer logs hold neither the address nor the subject or body, and the request events are checked to carry no address and no request text. `TestPostgresMigrations` also checks that migration 00006 creates and drops its three tables and both trigger functions, and `TestIdentityRepositories` runs the cleanup query with the mail request and delivery locks. `TestMailDelivery` does not send mail; it covers the product notification consumer. `TestEmailVerificationOverHTTP` exercises verification mail and confirmation through the Resend fixture but does not call an external provider. The password reset flow has no delivery test because it is not implemented.
## Mail quota tests
Unit tests (`make -C backend test`) cover the quota rules without a database:
- `internal/domain/`: the day and month windows of an instant are UTC calendar periods whatever its location: midnight UTC belongs to the new day and one nanosecond before it to the old one, a local time after local midnight can still be the previous UTC day, the day reset of February 28 in a common year and of February 29 in a leap year is March 1, and December resets into January of the next year; limits refuse zero, negative, and a daily limit above the monthly one.
- `config/` and `internal/bootstrap/`: `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` default to 100 and 3000 for `resend` and `disabled`; `smtp` refuses to start without either and takes stated values; a lowered value is taken as configured for every provider; an empty value counts as unset; zero, negative, non-integer, out-of-range values and a daily limit above the monthly one are refused without echoing secrets; bootstrap refuses to start with a quota of zero.
- `internal/adapter/secondary/mail/resend/`: 429 `daily_quota_exceeded` gives `QuotaPeriod` `day` with the wait until midnight, and `monthly_quota_exceeded` gives `month` without a wait.
- `internal/usecase/notification/`, with an in-memory counter and journal and a fake clock:
- `QuotaGate.PrepareSend` admits sends up to the daily limit and parks the next one in `waiting_quota` until 00:00 UTC without counting it, then admits it after midnight. It waits for the month start when the month is full (December 31 to January 1) and also when both windows are full.
- It parks a delivery last changed by an instance whose clock is 5 ms ahead, past midnight, at that change time without an error.
- It applies a lowered limit to `smtp` like any other transport, and refuses a delivery pinned to an account without a quota, reserving nothing for it.
- It returns an `unknown` delivery unchanged with the reset time and refuses a terminal one.
- A retry within 24 hours reuses the open reservation even with the day otherwise full; a rejection of that retry keeps it; after the window the retry counts again. An `smtp` gate, without provider deduplication, counts every retry.
- `SettleSend` keeps the reservation for `accepted` and `unknown`, and releases it for a `Send` error and every `rejected` outcome. A repeated settlement releases once.
- A daily quota answer marks the day and returns midnight, a monthly one marks the month and returns its end, an answer without a window parks only the delivery for its hint or without a time, and a window the provider reported full is not reopened by a release.
- The window marked is the one current at settlement: a daily refusal on October 31 marks only the day and leaves November open, a reservation at 23:59:59 settled 5 ms after midnight marks the new day, and a hint computed by a provider clock 5 ms ahead still gives exactly midnight.
- `ReportQuotaUsage` logs the usage and limits and warns with the other account labels.
- `DeliveryStatusReader.LatestForUser` returns the kind, status, and change time, and `WaitingUntil` only for `waiting_quota`. It asks only for the given account, returns nothing without a delivery, and refuses a nil account and an unknown kind.
- Logs hold no address, subject, or body.
`TestMailQuota` in `backend/integration_test/mail_quota_test.go` uses `bootstrap(t, postgresService)`, the real transactor, delivery store, and quota repository, and a fake clock. Each case starts from empty tables:
- Concurrency: 12 senders, each with its own connection and transaction, call `PrepareSend` at once. On windows without rows (the row creation races too) and a daily limit of 10 exactly 10 get a permit; after 7 sequential sends exactly 3 of the next 12 get one. Every other delivery is stored as `waiting_quota` with `next_attempt_at` at the next 00:00 UTC, and both counters end at 10. Without the row lock the case fails with all 12 admitted.
- Midnight and month boundary: with limits of 2 per day and 3 per month starting October 30 at 22:00 UTC, the third send waits until October 31 00:00 UTC, still waits one second before it, and goes at midnight; the fourth waits for November 1 because the month is full, and goes then. The day and month rows hold 2, 1, 1 and 3, 1.
- Lowered limit and SMTP: gates are built from `config.LoadFromEnv`. After 4 Resend sends with the default limit, a limit lowered to 3 parks the next send until midnight. `smtp` without quota settings fails to load; with 2 and 2 it admits two relay sends and parks the third until the month start, and a Resend delivery under the `smtp` gate fails with `ErrQuotaNotConfigured` and changes no counter.
- Provider refinement: a `temporary` rejection gives its reservation back. A `daily_quota_exceeded` refusal while the local count is 1 of 100 stores the delivery as `waiting_quota` until midnight with one attempt, raises the day row to 100 with `provider_exhausted_at`, and the gate then parks the next delivery itself. After midnight a `monthly_quota_exceeded` refusal raises the month row to 3000 and parks the deliveries until November 1.
- Account deletion: three accepted sends count 3 of 3; deleting the account deletes its deliveries and attempts by cascade, the counters keep 3, and a delivery for another account the same day waits until midnight.
- Lock order, deterministic: the month row lies before the day row in the heap, and the writers run on sessions with `enable_indexscan=off`, so scans follow heap order as in the reproduced deadlock. A third transaction holds the day row; a reservation and a release queue on it in both orders, and the blocker is released. Neither gets a deadlock error, and the usage ends consistent. With the ordered lock removed from `Settle`, the case fails with SQLSTATE 40P01.
- Lock order, bounded stress: 60 rounds, each starting at once a release of day two, a release of day one that marks day two across midnight, and two reservations of day two, on heap-order sessions. No round returns an error.
- Journal: a transport error settled twice releases once. An unknown attempt's reservation is reused by a retry an hour later and not after the 24-hour window. The journal ends with 2 open rows, 1 released, and 2 with an outcome.
- User status: an account without mail gets nothing; after one admitted and one parked notification it sees `waiting_quota` until midnight; another account and another kind get nothing.
- Startup report: with usage under the label `old-label` and under the configured label, the report through `postgres.MailQuotaStore` logs the configured account's usage and warns with `old-label`.
- The database refuses an unknown period kind, a month that does not start on day one, negative usage, a malformed account label, a reservation whose day is outside its month, and an unknown outcome.
`TestPostgresMigrations` also checks that migration 00007 creates and drops `mail_quota_usage` and `mail_quota_reservations` and leaves the delivery tables. The quota suite does not call a transport; the worker that runs `PrepareSend`, `Send`, and `SettleSend` in sequence is covered by the service mail sending tests below.
## Service mail sending tests
Unit tests (`make -C backend test`) cover:
- `domain`: `Delivery.CheckServiceMail` names the first failed rule (missing token, purpose, owner, consumed, revoked, expired exactly at its deadline, registration moved, verified address, changed address) and leaves a current verification or reset mail sendable; `Delivery.Cancel` works from `pending` and `waiting_quota`, refuses `unknown` and the terminal statuses, leaves no attempt, and survives a restore; a notification cannot carry a token ID; the status names contain no claim of delivery to a person.
- `usecase/notification`: `ServiceMailSender` against in-memory stores with the version rule and the lease of the PostgreSQL store, the in-memory quota of the gate, and a scripted transport. Every transport result becomes the right delivery state, due time, and quota effect (accepted, permanent and invalid-request refusal, temporary refusal after the first backoff, a provider wait hint longer than the backoff, the provider's daily quota answer until midnight UTC, a quota answer without a reset, unknown, a transport that answers without an outcome, no transport, an interrupted call, an invalid message); every cancel reason is reached without a transport call or a reservation; a full local quota parks the delivery without a call and sends it at the reset; a result that cannot be stored keeps the lease, is repeated three times, and is then covered by a replacement under the same key without counting twice; an attempt lost beyond the idempotency window, or with a transport without deduplication, is recorded as unknown and not repeated; a delivery whose content hash does not match is cancelled as `content_invalid` and reported without calling the transport; a row that fails by its own fault (unreadable for a reason other than a hash mismatch, a domain rule broken while reading its state) is counted, moved back by the retry schedule so the delivery behind it is sent, and cancelled as `processing_failed` after three failures; transient errors (deadline, cancellation, deadlock, network, EOF, missing quota configuration) are reported to the worker and never counted or cancelled however often they repeat; a `Send` error without an answer moves the row back without counting it; paused counting moves rows back without counting; a successful pass clears the count; a failure is not recorded for a row another worker holds; the idempotency window is counted from the first request across repeated lost workers and with the one-hour margin; a revocation between the claim and the call is honored; a result is dropped when the lease was lost during the call; the call is bounded by the lease minus the settle budget; jitter is bounded and injectable; mail stored while no transport ran is rebound to the configured account and a delivery of another account is left alone; logs never hold the address, the token, or the link. `ServiceMailer` stores a token-bound delivery under the token ID with the token in the fragment of the link and no `?token=`, repeats harmlessly, and refuses a token of the wrong purpose before rendering. `RetryPolicy` doubles to its maximum and honors a longer hint.
- `worker/mailsender`: cancelled deliveries are counted by reason; the breaker pauses failure counting after three different rows fail in a row and resumes after a success, and one row failing again does not trip it; a failing row makes the loop wait by the backoff; the gauge is true only while the loop runs, an idle pass waits for the poll interval, a handled delivery is followed at once by the next pass, and a missing transport, an interrupted call, or a database failure back off instead of spinning.
- `adapter/secondary/postgres`: only SQLSTATE classes 22 and 23 match `ErrRowFault`; deadlock, serialization, connection, resource, shutdown, and internal errors do not.
- `adapter/secondary/prometheus`: `lincodex_mail_sender_cancelled_total` has every reason at zero and refuses an arbitrary label; `lincodex_mail_sender_running` exists at 0 and follows `SetMailSenderRunning`; every delivery status including `cancelled` exists at zero.
- `adapter/secondary/mail/resend`: the loopback constructor accepts only an http URL on a loopback host, so the key and the messages of a deployment cannot be pointed at another host through it; `resendfixture` answers like Resend (accepts, replays a repeated key and body with the original message, refuses another body under the key, plays scripted errors).
- `bootstrap`: no worker without a transport or a database; the loop starts and stops with the application and the gauge follows.
- `observability/prometheus/tests`: `LincodexMailDeliveriesOverdue` stays silent without the gauge, while it is 0, and for a notification-only backlog (age 0), and fires while some instance reports 1; `LincodexMailCancelledBroken` fires on `content_invalid` and `processing_failed` and stays silent on user-caused reasons (`make -C observability check`).
`TestServiceMailSending` in `backend/integration_test/mail_sender_test.go` uses `bootstrap(t, postgresService)`, the real transactor, stores, quota gate, and sending usecase, the real Resend transport pointed at the local fixture, and a fake clock. Subtests share the database and start from empty tables:
- A service email for a synthetic account with no consent record of any purpose is enqueued with its token in one transaction and accepted by the fixture: one provider call with the key `delivery/<id>`, the address, and the link with the token in the fragment; the delivery is `accepted` with the provider message ID, one accepted attempt, one counted recipient, no lease left, the account's status is `accepted`, and a second pass does nothing. Logs hold neither the address nor the token.
- A password reset email for a synthetic account without C2 is accepted by the fixture: one call with the key `delivery/<id>`, the address, and the `/reset-password` link with the token in the fragment; the log holds no address and no token.
- A verification email goes out even if C2 is granted and revoked while the email waits for the worker: the check reads only the token and the account, and the fixture gets exactly one call.
- A worker that holds a delivery keeps another off it: the fixture answers slowly, the second worker's pass is idle while the first one's request is in flight, and the fixture gets exactly one call and the database one attempt.
- Four workers drain a queue of eight deliveries at once: eight provider calls under eight distinct keys, none replayed, eight accepted deliveries with one attempt each, eight counted recipients.
- A worker that stopped after sending (the database fails when it stores the answer) is replaced after its lease expires: two calls under the same key, the second a replay, one message at the provider, one attempt, and the open reservation reused, so the recipient counts once. Beyond the 24-hour window the replacement records an unknown attempt and does not call the provider.
- A delivery whose content hash was broken by a manual edit is cancelled as `content_invalid` at version 2 without a provider call, and the delivery behind it is sent in the next pass.
- A row that fails for a reason of its own (a subject that breaks the domain rules, so the row cannot be restored although its hash is intact) is counted and moved back by a minute while the delivery behind it is sent, fails again at each due time, and is cancelled as `processing_failed` on the third failure with its bodies cleared; a transport error without an answer moves the row back by a minute without counting it, with the reservation given back and the delivery pending.
- A failure recorded by a worker whose claim rolled back leaves a row alone that another worker holds, and an uncounted failure leaves `failure_count` at 0.
- Three workers lost in turn do not hide the age of the first request: the delivery becomes `unknown` once `first_send_started_at` is 24 hours old, and the provider is not called a fourth time.
- The lease is a few seconds by the database clock; a stranger cannot record an attempt or lock the row; `RecordClaimedAttempt` succeeds for the holder.
- Over 5000 due notification rows the claim plan uses `deliveries_due_idx` and no sequential scan (`EXPLAIN`).
- A notification-only backlog does not make the earliest pending age appear; a service mail does.
- A token mail's bodies are cleared when it is accepted or cancelled and the token no longer appears in any row; a waiting mail cannot be cleared by hand; a cleared row cannot get a body back or lose its mark; the account still sees its status.
- A token revoked by a resend, a token already used, an expired token, an account registered again, an address already verified, a changed address, and a token of another purpose each end the delivery as `cancelled` with the matching reason, no attempt, no lease, no next attempt, no reservation, and no provider call; the account sees `cancelled`; a further pass is idle. A deleted account takes its delivery with it.
- A verification email revoked before its send is cancelled as `token_revoked` with no provider call and no attempt; the delivery keeps its provider account, its body is cleared, and the log holds no address, token, link, or account ID.
- Provider answers: a 503 `service_unavailable` leaves the delivery `pending` due one minute later, a pass before that is idle, the retry at the due time repeats the key and is accepted; a 500 is `unknown` with no next attempt and no retry a day later; a 403 `validation_error` is `rejected`.
- Quota: a local limit of one per day parks the second delivery in `waiting_quota` until midnight UTC without a provider call, the account sees the wait and its end, and the delivery is sent at the reset; the provider's `daily_quota_exceeded` answer parks the delivery until the next midnight.
- A product notification is never claimed by the service worker; the notification lane sends it instead (`TestProductNoticeIsSentOnceByItsOwnWorker`).
- `EMAIL_PROVIDER=disabled`: with the disabled transport the pass reports the channel unavailable, the delivery stays untouched at version 1, the lease and the reservation are released, nothing reaches the fixture, a loop run against it makes at most four passes in under a second, and the gauge is 1 while it runs and 0 after; with a transport the same mail is rebound to the configured account and accepted.
- The schema refuses a cancelled delivery without a reason, a reason on another status, a half lease, a lease on a terminal delivery, a notification bound to a token, a change of the token binding, and the deletion of a token that a delivery references; deleting the account removes both.
`TestDeliverySendingMigration` rolls back and applies migration 00012 over a cancelled and redacted reset delivery: the earlier schema keeps it as `rejected` with a placeholder body, drops reset tokens and the new columns, and the migration applies again. `TestPostgresMigrations` covers the generic up, down, and up path.
`make -C backend lint` also forbids importing `resendfixture` and calling `resend.NewLoopbackSender` outside `_test.go` files (depguard and forbidigo in `backend/.golangci.yml`).
No check calls the real Resend API: the fixture is the only provider, so these tests prove the protocol the transport speaks and the delivery rules, not Resend's behavior, deliverability, or the account's real quota.
## Product notification tests
Unit tests (`make -C backend test`) cover:
- `domain`: `Delivery.CheckInvitationNotice` decides in its documented order (a missing or unverified recipient, a changed address, a missing or foreign invitation, an invitation that was answered, expired, or past its deadline, a hidden organization, a withdrawn publication, and a notice without a subject), and the first failed rule decides, so an unverified address outranks a hidden organization; `MailSubject` accepts only known kinds with complete IDs and prints no identifier; only a notification names a subject; `MailQuotaLimits.WithReserve` keeps each window's share and refuses a reserve that leaves no room; the three rights reasons parse and exist at zero in the metrics set.
- `config`: the service reserve defaults to a fifth of each quota limit (20 and 600 on the Resend Free plan), a stated zero is kept, and a reserve that is negative or reaches its limit is refused with a message that names the setting.
- `adapter/secondary/prometheus`: `lincodex_notification_sender_running` exists at 0 and follows `SetNotificationSenderRunning` without moving the service gauge; the rights reasons exist at zero in `lincodex_mail_sender_cancelled_total`.
- `bootstrap`: no notification worker without a transport or a database, and the notification loop starts and stops with the application while its gauge follows.
- `observability/prometheus/tests`: `LincodexMailCancelledBroken` stays silent on `rights_revoked`, `recipient_ineligible`, and `source_closed` (`make -C observability check`).
`TestProductNotice*` in `backend/integration_test/product_notification_test.go` use `bootstrap(t, postgresService)`, an isolated database with the real invitation send and the real notifier, the consumer `DeliveryHandler` run on the stored request, the real notification sender with the Resend fixture as its transport, and a fake clock. Each top-level test uses its own isolated database, so quota counts never mix between them; the subtests of the rights test share one database:
- `TestProductNoticeIsSentOnceByItsOwnWorker`: the notice of a delivered invitation is sent once by the notification lane, with the neutral body, which names neither the organization nor the candidate and links to the inbox; the service worker takes nothing (idle, no provider call); a second pass is idle; the logs hold neither the address, the candidate ID, nor the card handle.
- `TestProductNoticeRightsAreCheckedBeforeEverySend`: a candidate who hides the organization between the send and the worker gets no mail, and the notice is cancelled as `rights_revoked` with no provider call, its bodies cleared, a further pass idle, and no address in the logs; an address that is no longer verified is cancelled as `recipient_ineligible`; a notice that names no subject is cancelled as `source_closed` with its body cleared; an invitation past its response deadline is cancelled as `rights_revoked`. The deadline subtest moves the clock, so it runs last.
- `TestProductNoticeReserveLeavesServiceQuotaToServiceMail`: with a daily limit of 10 and a reserve of 8, the notification lane sends two notices and parks the third in `waiting_quota` until the next UTC midnight, without a provider call and without a spin; a verification mail then goes out under the full limit, and the day counts three recipients.
- `TestProductNoticeQueueIsDrainedOnceByConcurrentWorkers`: four senders drain six notices at once; the provider sees six calls, and each notice is accepted after one attempt.
- `TestProductNoticeClaimReadsItsOwnDueIndex`: over 5000 service-mail rows the product claim plan uses `deliveries_product_due_idx` and no sequential scan (`EXPLAIN`).
These tests prove the rights rules and the lane mechanics against the local fixture. They do not decide the product questions listed under [Sending product notifications](ARCHITECTURE.md#sending-product-notifications), such as whether a withdrawn publication should cancel a pending notice.
`TestInvitationNoticesSurviveRelayAndConsumerRestarts` in `backend/integration_test/notification_restart_test.go` uses `bootstrap(t, postgresService, kafkaService)` with the same fixture and follows two real invitation sends through the outbox, the relay, a one-partition Kafka topic, and the `notification_inbox` and `notification_delivery` consumers built as bootstrap builds them. The relay produces all four events and is killed before its mark commits; the consumers apply them. A restarted relay then publishes the same event IDs again, and restarted consumers in the same groups count each repeated record as a duplicate; consumers in new groups, as after lost offsets, replay the whole topic as duplicates too. After each stage every recipient has exactly one row in `notification_inbox_events` and one notification delivery, and no dead letter exists; the notification lane then sends one message to each recipient.
## Scheduled job tests
Unit tests (`make -C backend test`) cover the job runtime with an in-memory store that applies the claim, lease guard, and release rules of the PostgreSQL store and a fake clock from `backend/pkg/testutil/` (`internal/worker/jobrunner/`): only due jobs of registered kinds run, in due order, and a job due in two days runs exactly when the clock reaches it; a failing job is retried after the backoff by the clock, is not claimed again before it, and is dead after the last attempt with an error log and metrics; `ErrJobRejected` and a panic end a job after one attempt without logging the panic value; a handler that outlives its lease fails as `timeout`; a job reclaimed by another worker before it starts is skipped without calling the handler; a job whose last started lease expired becomes dead without running; a slow first job of a batch neither spends the next job's single attempt nor lets it die, and another worker runs a job that a busy worker claimed but did not start, on the same attempt; a database failure outside the handler releases the job and the rest of the batch without counting attempts; failed claims back off instead of looping; at shutdown the job in progress finishes within the grace, a job that outlasts it is canceled and released without an effect or a counted attempt, and claimed jobs that did not start are released; a panic during shutdown still makes the job dead; and the backlog of all kinds is reported. Further unit tests cover the job rules (`internal/domain/`: kind, key, flat payload, size limit, UTC microsecond due time), the settings (`config/`), the counters and gauges (`internal/adapter/secondary/prometheus/`), `FakeClock` (`pkg/testutil/`), and in `internal/bootstrap/` the skip cases with their log lines, the empty kind registry, a duplicate kind, and an application that runs the worker against an unreachable database and still stops.
`TestScheduledJobs` in `backend/integration_test/scheduled_jobs_test.go` uses `bootstrap(t, postgresService)`. Its handler exists only in the test: it writes one row into `job_test.effects`, a table without a unique key, in the transaction that completes the job, so a second effect would stay visible. Each simulated process gets its own pool, store, and worker; building a new one is a restart. All due and lease decisions use one `FakeClock`. The sequential cases are:
- Jobs on different dates: two jobs scheduled through `UnitOfWork.ScheduledJobs()` for tomorrow and in three days, and a repeated schedule that is ignored and does not move the due time. Nothing runs at the start; after a restart and one day the first job runs; after another restart the second job does not run a microsecond early and runs at its due time; a month later nothing runs again. The effects are one per job, in due order.
- Two workers with their own pools run their loops against 40 due jobs at once: every job is done, and there are exactly 40 effects for 40 distinct jobs.
- A handler that outlives its lease by the clock still holds the job row lock, so another worker's claim skips the job; the first worker then completes it, with one effect.
- An expired lease: worker A claims and starts the job and stops inside it. Worker B cannot claim it a microsecond before the lease expires and runs it at expiry, with two counted attempts and `lease_expired` recorded. A's late start is refused, its late `Run` returns `ErrJobLeaseLost` without calling its handler, and its late failure record and release are refused; one effect remains.
- A started attempt with a limit of one attempt whose lease expired: the next claim makes the job dead with one attempt and `lease_expired`, without calling the handler.
- A claim that never started, with a limit of one attempt: after its lease expires another worker runs the job on the same attempt, with no error class.
- A slow first job of a batch runs past the claim lease: the next job, limited to one attempt, is released with its attempt intact and runs in the next pass. With two workers, while the slow job holds its row, the other worker claims only the waiting job and runs it on its single attempt; the busy worker then counts it as `lease_lost`.
- A handler that cancels its own job through the unit: its effect commits, the job stays `cancelled`, and the next job of the pass runs. A handler that changes its own job otherwise makes it dead with `completion_conflict` and leaves no effect.
- Graceful shutdown: a handler writes its effect and then outlasts a 200 ms grace. After the stop the effect is rolled back and the job is `pending` with no attempt and no lease, and a new process runs it at once without waiting for a lease.
- A failing job with its own limit of two attempts: the first attempt moves only `available_at` by the backoff and keeps `due_at`, the job is not claimed before the backoff, the second attempt makes it dead, the handler saw the original due time both times, no effect remains, the backlog reports one dead job, and the counters show one `retry` and one `dead`.
- Cancel: a canceled job is never claimed, a second cancel and a new schedule of the same key do nothing, and nothing is due.
- Cancel during a run: while a handler holds the job, a cancel in another transaction is observed waiting for the row lock in `pg_stat_activity`; after the handler commits, the job is done and the cancel reports false.
`TestPostgresMigrations` also checks that migration 00008 creates and drops `scheduled_jobs`. The suite uses one PostgreSQL and a test-only kind. It does not measure throughput, does not cover clock skew between instances, a database failover, or a product handler, and does not check alert delivery.
## Product metrics tests
Unit tests (`make -C backend test`) cover the product metrics. In `internal/adapter/primary/http/`, requests through the real router and the real collector are labeled with the route template of their operation (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) and never with a path parameter, an address in the path, or a query string; unknown paths and methods keep `/api/v1/*`, `/api/*`, or `unmatched`; problem responses are counted by code (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), a plain 404 outside `/api` is not; and the exposition holds no email-like or UUID-like value; every contract problem code keeps its own label. The request log test sends an address and a UUID in paths and queries through the same router and checks that the JSON log names only route templates, statuses, problem codes, and query parameter counts, skips `/healthz` and `/readyz`, and holds neither value. `internal/adapter/primary/http/middleware/` tests the log and metrics middleware on a plain chi router: the shared route and problem code, no problem for a response that finally succeeded, the error level for 5xx, an unknown method logged as `OTHER`, and a collector without problem counting. In `internal/adapter/secondary/prometheus/`: latency by status class, every delivery kind and status pair exposed at zero and reset when a status empties, quota gauges without an account label, the answer save hook mapping unknown values to `other` and exposing no series before its first call, and a scan of the whole exposition after every hook was called with email and UUID fixtures. `internal/worker/deliverymetrics/` covers the due age of the earliest pending delivery (zero when it is not due yet), the current quota windows, a failed read that does not skip the other, and the loop lifecycle; `internal/bootstrap/` covers the skip without a database, the quota only for an active transport, and an application that runs the sampler against an unreachable database and still stops. `pkg/testutil/` tests the identifier scan itself.
`TestDeliveryStatistics` in `backend/integration_test/delivery_statistics_test.go` checks the sqlc query `GetDeliveryStatistics` on PostgreSQL: an empty table, then deliveries of three kinds in all five statuses, set within the table constraints, give exact counts per kind and status, and the earliest due time comes only from deliveries that are still pending.
`make -C observability check` validates the alert rules with `promtool check config` and runs `promtool test rules` on `observability/prometheus/tests/lincodex_rules_test.yml`: every alert fires in a positive case (backend down, 5xx share, outbox lag, dead letter, stalled consumer, dead and lagging jobs, unknown delivery outcome counted once across two instances, overdue deliveries, stale mail gauges, the used-up quota by count and by provider refusal), and the guards stay silent: quiet traffic with only failing requests, overdue deliveries without `lincodex_mail_sender_running`, a sampler that keeps succeeding, and a month window with room.
`make -C observability verify-product-metrics` is the end-to-end check described in [DEPLOY.md](DEPLOY.md#separate-monitoring-compose-project). It needs Docker and free host ports 18085 and 13085, builds the core images, and takes several minutes. It sends the fixture address in a query through Nginx and in a path straight to the backend and provokes a unique violation on it in PostgreSQL. It proves that the metrics reach Prometheus and the product dashboard queries run in Grafana, that PostgreSQL logs errors tersely, and that the fixture address is absent from the metric exposition, every series and label value, the federated samples, and the Loki logs of the core services in that run. It does not test alert delivery, production retention, load, or latency targets, and it does not send mail.
## Integration test sharding
`make -C backend test-int` runs the full suite through `backend/scripts/run-integration-suite.py`. The runner discovers every top-level `Test*` in `./integration_test/...`, sorts by package and name, and distributes tests round-robin. Each test belongs to exactly one shard with all its subtests. Changing the test set may change the assignment; duration-based balancing is not implemented.
```sh
make -C backend test-int-list
TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 make -C backend test-int
TEST_SHARD_INDEX=2 TEST_SHARD_TOTAL=2 make -C backend test-int
```
Indexes start at 1. Set both variables together; invalid settings, an empty suite, excess shards, and discovery failures fail the command. `test-int-list` compiles test packages and lists selected tests without starting containers. `make -C backend test-scripts` verifies for every shard count that each test runs in exactly one shard, that a shard listing matches the tests the shard runs, parent-test selection, and runner failure propagation. It is included in `make -C backend check`.
CI uses a separate matrix of two integration jobs with `GOFLAGS=-race` and `fail-fast: false`. Every shard must pass before aggregate and deployment smoke succeed. Run `GOFLAGS='-race -shuffle=on' make -C backend test-int` locally to check races and order independence. Shards use their own containers; runners do not share a database or a broker, so a Kafka test passes in whichever shard it lands. CI takes `TEST_SHARD_TOTAL` from the matrix size (`strategy.job-total`), so adding a shard index to the matrix is enough when suite duration warrants more runners; an index above the total fails the job. The `go test` timeout shares a 20-minute budget of the whole suite between shards with a floor of 10 minutes: an unsharded local run gets 20 minutes, each of the two CI shards gets 10.
## Consent ledger tests
Unit tests (`make -C backend test`) cover the ledger rules without a database:
- `internal/domain/` (`consent_test.go`): only `c1` to `c5` are purposes and only C4 is organization scoped; a text version follows the contract pattern of 1 to 64 characters; a text hash must be 32 bytes and not all zero; a stored text whose body no longer matches its hash, a C4 text without the `{organization}` placeholder, and another text with it are refused; the rendered C4 text hashes differently per organization and from its template, and an empty, padded, or multi-line organization name is refused. `NewConsentGrant` refuses C4, an empty or malformed version, a missing hash, subject, or time, and a source that the purpose does not allow; `NewContactConsentGrant` requires the C4 text, the organization with a valid name, a field set, the invitation, and a positive terms version, and hashes the text as shown for that name. Grants and revocations print and log no subject, organization, name, or field. A field set is canonical in any input order and refuses empty, repeated, unknown, and more than four fields. `RestoreConsentRecord` refuses what the database refuses, and a record prints and logs only its ID, purpose, and state.
- `internal/adapter/secondary/postgres/` (`consents_test.go`): ledger constraint errors map to their sentinels by SQLSTATE and constraint name without the row detail, the restricting consent key in the cleanup maps to `ErrTransactionConflict`, invalid input fails before any statement, every generated row type converts to one record row, and the stored field set keeps the order the database accepts.
- `internal/usecase/consent/` (`service_test.go`, with an in-memory text repository, ledger, transactor, and a controllable clock): a grant of C1, C2, C3, and C5 records the current text version and hash, the source of its entry point (`GrantAtRegistration` fixes C1 and `registration`, `GrantInSettings` fixes `consent_settings`), and the time of the injected clock, never another time; a grant with an older, unknown, or scheduled version fails with `ErrStaleConsentText`, names the current version, and never reaches the ledger; granting version one, publishing version two, and repeating version one is stale and leaves one record; `CheckTextVersion` returns the current text, fails stale for an older, unknown, and scheduled version, refuses an unknown purpose and a malformed version, and never touches the ledger; C4 on the generic path fails with `ErrScopedConsentRequired` before any repository is read; a malformed or empty version, an unknown purpose, and a nil subject are refused; a repeat returns the existing record with `Created` false and its first time, and the ledger keeps one record; failures of the repositories (no published text, unknown subject) keep their sentinel and a missing text is not reported as stale; a subject who withheld C3 has the other purposes with their own records and no C3 record; `GrantContact` records the scope, the source `invitation_acceptance`, and the hash of the text as shown, returns the existing record for a repeat, reports an invitation of another subject as taken, and refuses a stale C4 version, a padded name, and missing fields, organization, invitation, subject, or terms version; `GrantInSettingsInNewTransaction` retries a transaction conflict after a wait, stops after three attempts, does not retry another error or a canceled context, and rolls back a stale grant; `NewService` panics on a nil transactor or clock.
- `internal/adapter/primary/http/` (`router_test.go`): `ListMyConsents` answers 501 after validation for a session and 400 with the query pointer for an unknown state, a limit over 100, and a malformed cursor; under `DenyAllSecurity` it answers 401 with or without a cookie and with a `subject_id` parameter; the DTOs carry no hash, subject, or contact field, the parameters are only the state and the page, and the contract example decodes and validates.
- `frontend/src/shared/api/consent-contract.test.ts`: the generated Zod schemas accept a C4 record with its scope and a revoked unscoped record, refuse an unknown purpose, state, or source, an empty or malformed version, an empty or oversized field set, an unknown contact kind, and a terms version below 1, require every nullable field, and drop a hash or subject; the operation takes only the state and page parameters.
`TestConsentLedger` in `backend/integration_test/consent_ledger_test.go` uses `bootstrap(t, postgresService)` with the migrated schema, publishes a second C1 text the way a migration would, and truncates the ledger between cases:
- The migration publishes one demo text per purpose with a matching hash; the current C1 text depends on the time; an unknown version and a version of another purpose are not found.
- Versions and purposes: C1 at registration, C2, and a newer C1 version give three rows; the older C1 row stays byte-for-byte the same and is listed as `superseded`, the current C1 is the newer one, a repeated grant of the older version returns the existing row without a new one, and revoking C2 leaves C1 unchanged.
- Revocation stamps once: a second revocation finds nothing and keeps the first time, the current C3 is gone, and a new grant is a new row next to the revoked one. Revoking C1 also closes its superseded row.
- C4: the generic grant and a scoped grant without organization and fields are refused by the domain; a grant stores the organization, the canonical fields, the invitation, and the terms version, with the hash of the shown text rather than the template; a repeat returns the same row; an invitation consent of another subject fails with `ErrConsentInvitationTaken`; revoking C4 for organization A leaves organization B, and a revoked invitation consent never comes back.
- Repository validation: an unknown subject, an empty or malformed version, an empty hash, an invented version, a version of another purpose, a hash of another text, and a grant before publication are refused and store nothing. Another subject neither sees nor revokes the owner's consent.
- Database constraints through raw SQL: an empty version, an empty or short hash, C4 without a scope or with an empty, repeated, or unknown field, C2 with a scope or from the registration, a revocation without a source, and a hash of another text are refused by name; an update of a granted row, a revocation that also moves the grant, a second revocation, an update or delete of a published text, and a delete of an account with consent history are refused.
- Read model: pages of three return exactly the owner's four records newest first and never the other subject's; the state filter returns the active and the revoked records.
- Business transaction: a C4 grant rolls back with a failing acceptance, a failing statement after the grant rolls back the whole transaction, and a committed acceptance is visible after the commit and to its own transaction before it.
- The unverified account cleanup deletes the stale account with its C1 row and keeps the verified account and its record.
- C4 snapshot: raw rows whose hash belongs to another organization name, to another name than the stored one, or to the template are refused (`consent_records_c4_text_hash`), C4 without a name and C1 with one are refused (`consent_records_c4_scope`); after a rename, two acceptances keep their own names, and each hash still proves the text shown with its snapshot.
- A revocation dated an hour before the grant is stamped at the grant time.
- Deleting a consent row of a confirmed account is refused (`consent_records_retained`); a row of an unconfirmed account can be deleted.
- Re-registration: `UpdateRegistration` and a new C1 grant in one transaction leave only the new C1; a stale re-registration and an attempt on a verified account change and delete nothing.
- Eight concurrent grants of one version on their own connections store one record, and all of them return it with exactly one `created`.
- Twenty rounds of a grant racing a revocation return no error other than `ErrTransactionConflict` and never leave more than one unrevoked record of the version.
- With only the consent row of a stale account locked, the cleanup on a session with a 200 ms lock timeout skips the account without waiting, and deletes it after the lock is gone.
`TestConsentGrants` in `backend/integration_test/consent_usecase_test.go` runs the usecase on the bootstrap database with a fixed application clock, a second C1 text, and a C5 text scheduled after the clock:
- Registration: `UserRepository.Create` and `GrantAtRegistration` of C1 run in one `Transactor` transaction with no session (the sessions table stays empty) and commit one account and one C1 at the application time with the current text version. C2 and C5 follow as separate operations, each with its own active record; C3 is withheld and has no record while the others stand; a C3 granted later and revoked leaves C1, C2, and C5 active.
- Atomicity: a transaction that fails after the account and C1 were written leaves neither, and a grant for a subject without an account fails with `ErrUserNotFound` and stores nothing.
- Idempotency and versions: a repeat in its own transaction and in a business transaction returns the first record and its time and stores no row, and a repeat does not abort the transaction. An outdated C1 version, a scheduled C5 version, and an unknown C3 version fail with a stale error that names the current version and store nothing; the current C1 version goes through and the outdated one stays refused. A grant after a revocation is a new row. Eight concurrent repeats create exactly one row.
- Republication: after C3 version one is granted and version two is published, a repeat of version one is stale, names version two, and leaves one row and the first record as the current C3.
- Re-registration: `UpdateRegistration` followed by `GrantAtRegistration` in one transaction returns `created` true with a new record and leaves exactly one C1. The opposite order is shown as a hazard: the grant finds the earlier registrant's C1 and returns it with `created` false, the update then deletes it, and the account ends with no C1.
- C4: the generic path refuses it and stores nothing; `GrantContact` in a transaction stores the organization, the name, the fields, the invitation, and the source `invitation_acceptance`; a repeat returns the same record, an outdated C4 version is stale, and the C4 does not create a C2.
- Restart: after the pool is closed, a new pool, store, and usecase list the same four records in order with their states, the revocation stamp and source, and the original grant times, and a repeat grant through the new instance stores nothing.
`TestRegistrationConsentMigration` applies migration 00016 in an isolated database and checks legacy C1 binding, no binding for settings grants, inserts through the old row shape, rejection of a supplied mismatched version, protection against changing the version during revocation, and down/up. A separate case confirms that stale registration C1 stops the migration without partial changes. `TestPostgresMigrations` continues to cover migration 00009. Registration and email confirmation integration tests exercise the consent service through the API flow; `TestConsentGrants` covers the usecase separately from HTTP. Revocation and C4 invitation acceptance are not covered as business flows. The cleanup race with SQLSTATE 23001 is covered only by its mapping unit test because its window cannot be reproduced deterministically.
## Organization tests
Unit tests (`make -C backend test`) cover the organization rules without a database:
- `internal/domain/` (`organization_test.go`, `membership_test.go`): a profile accepts a name only and a complete card; every rule names the field that breaks it by a JSON Pointer (`/name`, `/contacts/website`, `/representatives/1/name`) without quoting the value: an empty, padded, multi-line, over-long, or non-UTF-8 name, a description or sphere with a line break or control character, a website that is not `https` or has credentials, a port, an IP address, a numeric or hexadecimal host, or no dot, an email without a domain dot, a phone outside E.164, a Telegram username without `@`, and eleven representatives. CRLF in a description is stored as LF. `NewOrganization` starts at version 1 with a UUIDv7 and the level `e0` on `confirmed_email`, whatever the profile looks like; `ApplyProfile` keeps the identifier, the version, and the verification and never moves the update time backwards; a level pairs only with its own bases; `e0` to `e2` map to the quota tiers of the policy and `e3` has none; a stored row that was changed outside the application fails to restore. The card holds the profile and the level only. A representative is redacted in `fmt` and `slog` output, also inside an enclosing struct, and an organization logs only its identifier, version, and level. Only the owner manages the company, only an `active` membership gives access, the four roles and four states are the contract values, and `NewMembership` refuses a nil identifier, an unknown role, and a zero time.
- `internal/adapter/secondary/postgres/` (`organizations_test.go`): organization constraint errors map to their sentinels by SQLSTATE and constraint name without the failing row, which holds representative names; other errors keep only the SQLSTATE and the constraint; a deadlock maps to `ErrTransactionConflict`; invalid input fails before any statement; the manager roles passed to SQL come from the domain rule.
- `internal/adapter/primary/http/` (`organization_test.go`): under a session the operations answer 501 after validation and 400 with the pointer for each rule of the schema (a name over 200 characters or with a line break, a missing `expected_version`, contacts that omit a field, an http website or one with credentials, a phone outside E.164, a Telegram username without `@`, eleven representatives, a representative with a contact, null `name`, `contacts`, or `representatives`, a limit over 100, an identifier that is not a UUID); the representatives of the candidate card may be absent, null, or empty, and a card without contacts is refused. Each of eleven fields that would carry a right or a trust level (`role`, `owner_id`, `verification_level`, `verification`, `verification_basis`, `members`, `membership`, `candidate_card`, `id`, `version`, `created_at`) is refused alone on create and on update with the whole-body pointer. Under `DenyAllSecurity` all four operations answer 401, with or without a cookie and with a `user_id` parameter. The request DTOs have exactly the profile fields and no role, owner, member, or verification field, the card has no membership, role, basis, or time, the list takes only the page, an absent list differs from an empty one in `OrganizationUpdate`, every documented example decodes and validates, and the bundle has closed request objects, the CSRF scheme on both writes, the Idempotency-Key on create, 412 on update, and no operation that sets a level or a role.
- `frontend/src/shared/api/organization-contract.test.ts`: the generated Zod schemas accept a name only and a complete card for create and update, require `expected_version`, accept null only for `description` and `sphere`, refuse the same limits as the contract, drop a role or a verification level that a client adds, list the four levels, roles, and states, and, at the type level, give the requests no role, owner, member, verification, or identity field, the card no membership or basis, and the membership no account.
`TestOrganizationsAndMemberships` in `backend/integration_test/organizations_test.go` uses `bootstrap(t, postgresService)` with the migrated schema and truncates the organization tables with `users` between cases:
- Storage: an organization is stored with its owner and read back with its profile, representatives in order, version 1, the level `e0`, and the active owner membership; fields that are not set are NULL.
- Membership uniqueness: a repeated membership of the same account and organization, in each of the four roles and after the member left, fails with `ErrMembershipExists` naming `memberships_user_id_organization_id_key`, a raw insert fails with SQLSTATE 23505, and only one row remains; another account or organization is another pair.
- Atomic creation: an unknown owner account rolls back the organization, its representatives, and the membership; a later failure of the same transaction does too; an owner membership that is a recruiter, belongs to another organization, or is zero is refused before any write.
- Owner at commit: a transaction that inserts an organization alone, with a recruiter only, with a suspended owner only, or with an owner that it moves to `removed` before it commits fails at commit with SQLSTATE 23514 on `organizations_owner_required` and leaves nothing; an organization and an active owner inserted in one transaction commit.
- Scoped list: the organizations of one account include the ones where it is a recruiter and exclude those where its membership is suspended, left, or removed and every organization of another account; pages of two follow the same order with no gap or repeat; memberships created at the same instant order by the organization identifier; invalid queries, including a position without an organization identifier, are refused; an organization without representatives reads back with an empty list.
- Access: an account that is no member, an unknown account, an unknown organization, and a `suspended`, `removed`, or `left` member all get `ErrOrganizationNotFound`, a restored member reads again, and `Memberships().Get` returns the stored state in any state.
- Update: the owner replaces the profile, the representative list, and the contacts, the version advances to 2 and the update time changes, cleared fields become NULL, and a verification level that a process set to `e1` is still `e1` after the next profile update. A recruiter gets `ErrOrganizationManagerRequired`, a suspended owner, an outsider, and an unknown account get `ErrOrganizationNotFound` even with a stale version, a stale version gets `ErrOrganizationVersionConflict`, and none of them changes the stored organization.
- Revocation during an update: a transaction that revokes the second owner stays open, an update by that owner queues behind its membership lock (seen in `pg_stat_activity`), and when the revocation commits the update returns `ErrOrganizationNotFound` and writes nothing. Without `FOR SHARE` on the actor's membership the test fails.
- Concurrency: eight updates from the same version on their own connections give exactly one success and seven conflicts, and the stored name and representative belong to the same winner.
- Constraints through raw SQL: an empty, padded, multi-line, or over-long name, an unknown level, a basis of another level, version zero, a description with a padded end or a control character, a sphere with a line break, an http website or one with credentials, an email with a space, a phone without `+`, a Telegram username without `@`, an update before the creation time, the level and basis pairs of `e1`, `e2`, and `e3` (the right ones accepted, the wrong ones refused), a composite foreign key onto `(organization_id, id)` of the memberships (accepted for the member's own organization, refused for another), an unknown role (including `manager`), an unknown state (including `invited`), an eleventh representative, and a padded job title are refused by constraint name; the organizations table has no column for a role, an owner, a member, or a user.
- Deletion: an account with a membership and an organization with a member cannot be deleted (SQLSTATE 23001); once the memberships are gone, the organization takes its representatives with it.
`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. This storage suite does not cover the usecases or HTTP; the separate tests below use real sessions and CSRF. 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.
`TestOrganizationCreationAndOwnerEditingOverHTTP` and `TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` exercise organization creation and editing, idempotent replay, the caller's paginated directory, owner-only actions, foreign organizations, and revoked membership over real HTTP and PostgreSQL. Revoking a second owner closes the profile and tenant operations for the same cookie while preserving another owner's access. Middleware tests enumerate every tenant operation in the contract.
`TestCompanyIsolationAndRevocationOverHTTP` (`backend/integration_test/company_isolation_http_test.go`) checks company isolation and revocation across the minimal path over real HTTP and PostgreSQL. Company A runs a need, a search, a card with its evidence, an invitation accepted with C4, the contact read, and an inbox item. Company B, and a second company of A's own owner in the same holding, then call every organization-scoped operation with a valid session, on A's path and on their own path with the identifiers from A's responses. Each call must answer the documented refusal, identical to the answer for a random identifier, and A's objects must stay unchanged. A candidate gets the same check against another candidate's invitation and notification. The test also checks that hiding the organization, revoking C4, and withdrawing C2 close the very next read through the handles of an earlier search, the invitation page, and the contact read. A new C2 or a new publication must not revive a grant that C4 revocation closed. The MVP must serve no PDF, selection snapshot, or stored search result, and the server log, outbox payloads, inbox rows, and stored email requests must carry no contact, name, or profile value. It does not cover Kafka, the browser, or roles other than the owner.
## 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.
`TestCandidateProfileOverHTTP` checks the caller's profile through a session and CSRF: an empty GET, complete save and API restart, specific date and overlap errors, parallel-work confirmation, 412, no history write on a no-op, foreign-profile isolation, and employer denial. History, data, and the conditional onboarding transition share one transaction; injected history and step-transition failures roll back the save. Changing self-assessment does not create a confirmed category.
## Candidate questionnaire tests
`TestCandidateQuestionnaireOverHTTP` uses real sessions, CSRF, and PostgreSQL. It checks an empty version-zero questionnaire, save and handler restart, account isolation, employer denial, rejection of unknown confirmed-grade fields, different concurrent writes returning 200/412, identical concurrent writes returning 200 with one version increment, conditional onboarding, rollback, paired experience constraints, and catalog invalidation after a policy change or family retirement. Self-assessment never creates a confirmed category. The canonical API uses 412 for version conflicts; older task wording mentions 409.
The isolated mail overlay sets `IDENTITY_CLIENT_HOURLY_LIMIT=200` because all browser scenarios share one proxy address. Ordinary and release configuration retain 30, and per-email limits remain unchanged.
`questionnaire.spec.ts` uses the local mail fixture and an explicitly published synthetic bank for Backend/Junior with Go and Python. The test-only `questionnaire-fixture` command accepts only the unchanged initial demo policy, explicitly publishes `DemoProductPolicyV2`, then publishes the required number of reviewed families before binding the catalog. This also enables the support and assessment policy sections for browser tests. It refuses existing backend bank ownership or another current or scheduled policy and is absent from ordinary and release images. Normal startup still seeds V1 only. The browser scenario walks the questionnaire steps (step validation, the focus on the heading, "Назад" and "Изменить" without losing answers) and covers persistence, a DS/ML specialization marked in development, keyboard access and layout at 360/768/1280 px, and conflict handling between two real sessions. It is skipped when these isolated fixtures are not enabled.
`assessment.spec.ts` uses the same isolated fixture. It saves both languages and explicitly selects Python, then completes the full attempt with keyboard navigation at 360px and waits for finalization and the server result. It separately exercises express training with the resumption of an unfinished run after a reload (409 to a new start, then 201 for the stored key), offline answer submission, replay after a malformed success response, reload, and resuming saved progress. Explicit screenshots cover 360px and 1280px. These synthetic checks validate the application flow, not assessment calibration.
## Minimal path from registration to disclosed contacts
In the registration mode the overlay `docker-compose.e2e-mail.yml` sets `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` on the test backend and gives Playwright `E2E_DEMO_CATEGORIES=1`. After `questionnaire-fixture`, the runner attests the opened Backend Junior category with the operator command `/assessment-category-attest` from the test backend image, so a passed full test of this stand receives the uncalibrated `synthetic_demo` category, as on the demo stand. The ordinary and release suites keep the default `false`, and `make -C deploy check-e2e-mail` checks both settings.
`frontend/e2e/acceptance-path.spec.ts` walks the minimal path on the real backend without an FSP ID. Five candidates register with the link from the received message, fill the profile and the questionnaire, grant C3, solve every item of the full test from its statement, and publish an identical card after an explicit C2, because a card is shown only in a group of five. The spec then checks:
- the result `confirmed` with the category decision `assigned`, `demo_basic_pass_mark`, `synthetic_demo`; a reload in the middle of the attempt returns the same attempt without a second answer, and the result history keeps one entry after a reload and a step back and forward in the browser history;
- a need, the search by its requirements version with the five confirmed entries and the explanation from the server, a filter by the declared grade senior that removes all five cards and keeps only cards of other specs with that grade, and the unchanged result of the first requirements version after the need is edited;
- three invitations bound to the first requirements version, delivered once each; no search result, invitation list, or organization notification holds an email, a phone, or a name;
- an acceptance in the browser with the email only, after which a reload and a history step add no record, there is one C4 record for the organization, and the organization reads only the email;
- two concurrent acceptances of one invitation with different keys: both answer 200 with the same body, one C4 record and one grant;
- a decline without access and the refusal 409 `state_conflict` of a new invitation for the same pair;
- a second company that gets 404 or a field error, never data, for the need, the search by that need, the cards, the invitations, and the contacts of the first one;
- C2 revocation that closes the contact read and the cards of the earlier result at once (the four remaining cards fall below the group of five and are suppressed too), and a new C2 and publication that reopen the cards but not the grant of the accepted invitation.
The spec does not check the planned transitions without an operation (withdrawal, cancellation by the candidate, the counter offer, the interview, the closed final), the 20-invitation limit per need and the expiry (backend integration tests cover them), category recommendations for a need, which stay `pending`, or a PDF. Traces and screenshots are off; the data are synthetic.
## Candidate visibility tests
Unit tests (`make -C backend test`) check the visibility rules without a database:
- `internal/domain/visibility_test.go`: the card field set is canonical, closed, and refuses the full name, any contact, and the salary; a publication request needs a field to publish and none to close; a new profile is closed and never published; publishing needs an active C2 and names no consent; the order of checks (a future version, an unchanged state over a stale version, a stale change, a missing consent); a revoked C2 closes the card and a new C2 does not reopen it; the search status lapses after the interval of the policy to the non-public status without a write, is confirmed again explicitly, and takes the interval from the policy version; stored rows that break an invariant are rejected; the types log only identifiers.
- `internal/adapter/primary/http/candidate_privacy_contract_test.go`: by the contract bundle, the operations follow the conventions (the CSRF scheme exactly for changes, the version in the body, no Idempotency-Key or If-Match, the same 404 for hiding, 204 without a 404 for lifting); the publication and the search status carry no consent and reach no schema of each other; **the anonymous card and the preview reach no profile, contact, consent, invitation, or organization schema and have no property that names or identifies a person**, and no organization path reaches a setting; through the generated server the schema rejects a contact as a card field, a consent identifier, and a client-sent time before the implementation, a valid request answers 501, and a denied session answers 401.
- `frontend/src/shared/api/privacy-contract.test.ts`: the generated Zod schemas read a new candidate as closed and not looking at version 0, reject a card field that is a name, a contact, or the salary, strip a consent, a time, and an interval from the parsed requests, keep the card closed to contacts, and the generated organization, invitation, need, profile, and consent files hold no setting keys.
`TestCandidatePrivacyStorage` in `backend/integration_test/candidate_privacy_test.go` uses `bootstrap(t, postgresService)`; `candidatePrivacyTables` belong to `usersDependentTables`:
- A new profile has no published state: after saving a profile all four tables are empty and the reads return no row. A hidden organization is unique per candidate and belongs to the candidate; an unknown organization is refused by the reference; lifting deletes once; the 1001st record is refused by the trigger.
- Publication: the foreign key accepts only a C2 record of the same account; a revocation in the ledger closes the card without a write; a new C2 grant publishes nothing; a stale update returns no row; the constraints refuse a contact as a field, a wrong order, and a wrong state shape.
- Search status: in a fixture the status is set, confirmed, and cleared, and the raw rows of the consent ledger, the publication, and the hidden organizations stay equal; looking stores the confirmation under the policy version with the interval of the policy; a lapse changes no row; the constraints refuse looking without its confirmation; the table has no consent column and references only users.
- Closing over a revoked C2 normalizes the stored row and records the closing; an organization reads a publication only through the effective view and not when it hides the reading organization (the same no-row answer as for an unpublished profile); a revocation racing with a publication, held under `LockCurrentC2Record`, waits for it and closes the card after it, or finds nothing to lock; eight concurrent hidings at 999 records let exactly one through; the unverified account cleanup removes the hiding records and history of an unverified account and spares a confirmed one. `backend/db/privacy_queries_test.go` fails when a query other than the three settings queries names `candidate_publications`, and `TestCardTextLooksLikeContact` pins the drop of free text that looks like a contact.
- History: append-only (UPDATE refused, DELETE refused while the account is confirmed), identifiers only, the shape of each kind is checked, pages continue by position, and the published fields and the C2 record are kept with their time. No privacy table has a column for a profile value, a name, a contact, or a file.
## 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. `assessment_choice_test.go` covers the choice format without a database: the same seed gives identical options, IDs, and order, and across 400 seeds the correct option appears at every position; every distractor of `lru_hits_choice.v1` is recomputed from the statement as the result of a named error model (and the nearby fill-in is used only when the models give fewer than three distinct values), the options never repeat a text, the cache models match hand-computed cases and the LRU model equals the solver of `lru_hits.v1`, and a golden test pins the options, their IDs, and the key of one seed; the correct option, a wrong option, an option of no item, two options, a number answer for a choice item, and a choice answer for an integer item are graded or refused as stated, the candidate projection holds only the opaque IDs and texts, and a broken key or repeated option of a frozen variant is refused. `assessment_table_test.go` covers table families: rows are selected by seed, the answer is the written one, the selection of fixed seeds is pinned, each of 39 format errors (missing column, repeated row, bad answer, duplicate distractor, oversized statement, a call or pipeline in the template, an algorithm beside a table, and so on) is refused with the index of the row, the scheme 2 hash of a fixed table is pinned against its canonical document, any change of the table changes the hash, scheme 1 and scheme 2 each refuse the other kind of generator, and an edited stored table fails the integrity check. `bundle_test.go` reads a table bundle and refuses a row with an unknown field. With in-memory fakes of the repository and the unit of work, the usecase tests prove that a concurrent identical import reports the version as unchanged and a concurrent import with other content is refused, that the sentinels of database races become refusals with the matching reason, that publishing retires the older published version after taking the category lock and is refused when a newer one is published, that opening requires the policy version in force, that availability is refused when the published count falls below the opening's requirement or when the opening's policy version is no longer in force, and that an older approved draft is refused while a newer version exists as a draft, a published, or a retired one. `internal/adapter/secondary/postgres/assessment_bank_test.go` checks that the bank constraints map to their sentinels without the failing row, that a list page outside its limit fails before any statement, and that the category lock is refused outside a transaction.
`TestAssessmentBank` in `backend/integration_test/assessment_bank_test.go` uses `bootstrap(t, postgresService)` and gives every case its own migrated database:
- Two versions of one family are imported and version 1 is read back with its original key, while version 2 has a different key; a repeated import changes nothing, the same version with other content and a skipped version number are refused with reasons, and raw SQL cannot edit the key, the version, or the review, delete, or truncate (SQLSTATE 23000 on `assessment_families_immutable`).
- One seed gives the same statement and reference answer from the stored version, and a different seed keeps the rubric of every demo family.
- The demo bundle imports as drafts; publishing each family is refused with `reviewer_missing`, the table refuses publication without an approved review, and opening `backend` is refused with `coverage_insufficient` and stores no opening.
- An opening without a policy reference, with an unknown one, or with a policy version that is not the one in force is refused with the matching reason.
- A test bundle that carries an approved review by a reviewer who is not its author (a fixture of the loader rules, not demo content) is published one family at a time; the category opens only when the published families reach the policy's `max_scored_items` plus `seed_items`; the opening records the policy version, the operator, and the counts, the required number the database derived equals the one the domain computes, and the opening cannot be edited. Retiring one family afterwards makes the availability read refuse with `coverage_insufficient`. A published version cannot be published again, can be retired once, and cannot move backward.
- Publishing a later version of a family retires the published older version and records both operators; publishing an older version while a newer one is published is refused; the table allows one published version per family and refuses a rewrite of the recorded publisher.
- A transaction that holds the category lock makes an opening wait until the deadline, and the opening succeeds after the lock is released.
- An older approved draft cannot be published once a newer version exists, also when that version is retired. Policy-in-force checks use the database clock, with no clock offset in the test.
- A bundle with a table family and a choice family is imported with hash scheme 2 for the tables and scheme 1 for the algorithm, imported again as unchanged, and the stored rows generate the same variants twice; a raw edit of a stored table is refused as an edit of a stored version.
- `TestAssessmentChoiceAndTableFamiliesAreServedAndGradedOverHTTP` in `backend/integration_test/assessment_choice_http_test.go` runs a real attempt over a bank of a choice algorithm, an integer table, and a choice table: every item the candidate receives has only the allowlisted fields (for a choice the option IDs and texts in the stored order, and no key, seed, or distractor field), an option of no item and two options are refused with 400, a wrong choice scores nothing and a right one scores through the key, the result matches the expected points, and every answer left a signal observation.
- Raw policy rows whose document lacks the scored item bounds or holds them as text, as an oversized, fractional, or negative number, or without the seed items are refused by the opening trigger with the thresholds refusal, not with a cast error; a stored hash scheme outside the CHECK list is refused, and the scheme cannot be edited.
- Written around the usecase, an opening that claims a lower requirement, an opening below the coverage, an opening under an unknown policy version, and a title with a bidirectional override are refused by the table.
- Families are listed in pages of two after a cursor, each once and in order.
`TestPostgresMigrations` rolls migration 00011 back with the others and checks that its two tables and five functions disappear while the policy table stays. The suite proves the storage and loader rules only: it does not validate the content of the demo bundle, task difficulty, or any grade, it does not prove the serialization of concurrent publications beyond the held-lock case, and it does not cover a candidate-facing flow, because none exists yet. Integration tests need Docker.
## Assessment signal and review band tests
`backend/internal/domain/assessment_signal_policy_test.go` and `assessment_signal_review_test.go` check without a database: the demo signal section is valid and round-trips through the schema 2 document, a signal section alone is a valid extension and never acquires defaults, schema 1 rejects the key, out-of-range and inconsistent thresholds are refused, response times follow the per-format floors and the median ratio only on the fast side within one format and leave out the first item of a session, origin marks count alternations and distinct networks in time order (a return to an earlier network is not a new one), the band follows the policy, weak signals (parallel sessions and extra networks, one correlated group) stop at attention unless a strong signal is raised, an answer counts once as fast or as a deviation, client signals only raise a band to attention, and the operator handle must be `operator:<handle>`. `backend/internal/usecase/identity/keyring_test.go` checks the new keyring methods: the answer fingerprint is deterministic, keyed, and scoped to the family version; session and network digests differ across attempts (no linking), across sessions, and across client keys, and use separate purpose keys.
`backend/internal/usecase/assessment/signal_review_test.go` checks the observer and the review job with fake ports: an accepted answer stores the server time, whether it is measured from the previous answer, the key version, and the keyed fingerprint only, with no answer text, address, or session ID in the stored values or in the error text; origin marks are written only when the session or network changes; the first answer schedules the deadline job (one minute after the deadline) and finalization the ended job; training attempts and requests without a session store nothing; a policy version without a signal section makes no review; the job rejects a broken payload, ignores a missing attempt, locks the reviews of a pair in ascending attempt order before it reads any fact and writes them under their own pinned policies, and refreshes only ended attempts at the attention level, bounded. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` samples 4000 seeds of each demo family, builds the distribution of shared values with their bits, and computes the probability that one honest pair reaches each demo threshold on a 23-item attempt; times 10,000 rivals it gives about 4e-5 (attention) and 3e-9 (review), against the targets 1e-3 and 1e-8. `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` calculates how many answers per family a copied pair needs for the demo thresholds to flag it (26 for attention and 61 for review at 13 items, 9 and 14 at 23 items). The FP model uses the distribution of reference answers only, not wrong answers or correlated mistakes. The targets are test constants chosen here, not a product decision, and the measurement covers four AI-drafted families.
`backend/internal/adapter/primary/http/assessment_signal_review_contract_test.go` walks every path of the public contract through its references and refuses any property, schema name, or enum that would carry the band, its reasons, fingerprints, or origin digests, and checks that the signal receipt still has exactly `status`, `accepted_events`, and `received_at`. `backend/internal/adapter/primary/cli/assessmentreview/command_test.go` checks argument validation before any environment read, the printed fields, and sanitized errors. The bootstrap test checks that the review job kind is registered.
`TestAssessmentSignalReviewOverHTTP` in `backend/integration_test/assessment_signal_review_http_test.go` runs the real router, PostgreSQL, and the scheduled job worker:
- A candidate answers every item within milliseconds from two login sessions and three network addresses and sends paste events from the second session. Before the worker runs no review exists and the review jobs are pending, so nothing was computed in a candidate's transaction. Then the attempt has the band `attention` with the reasons fast answers, parallel sessions, extra networks, and client signals, and its result is `confirmed`, equal in outcome, score, limitations, and mode to the result of an equally correct attempt with band `normal`; no assessment table other than the review table has a band column.
- A policy version with other thresholds is published while attempts are in progress and the category is opened under it. The attempts started earlier keep the first version, the attempt created later is pinned to the new version and stays `normal` for the same behavior, and its facts are still stored.
- Two candidates with different seeds copy the same wrong answers: the first attempt has no duplicate flag until the second candidate has answered and ended, and then both have the band `review` with the reason duplicate answers. A third copying attempt is abandoned: while it runs it is not flagged, and after it ends its job at the deadline (the worker clock is moved past it) flags it. Honest attempts with correct answers are not flagged even when a low-entropy answer coincides, and an attempt with one session and one network has exactly one origin mark.
- Candidate reads of the attempt, the result, and the availability contain no band, reasons, fingerprints, or signal names. The operator command prints the band and its audit rows are written for a found and a missing attempt; an actor without the `operator:` prefix is refused. Facts, reviews, and audit rows refuse UPDATE and DELETE, and the audit refuses TRUNCATE.
- The logs and the text of the new tables and of `scheduled_jobs` contain no network address, answer value, session token, or CSRF token.
`TestAssessmentSignalReviewHonestPopulationHasNoDuplicateFlag` creates 30 honest candidates with different seeds who answer each item correctly or not at random (a fixed generator) and two who copy the same answers: no honest attempt is flagged as a duplicate and both copied attempts are. The population is small, so the test uses thresholds of 32 and 44 bits instead of the demo ones. `TestAssessmentSignalReviewConcurrentJobsFlagEveryCopiedAttempt` ends four copied attempts at the same moment among eight honest ones and runs their jobs on four workers at once: no job fails or is retried and every copied attempt is flagged. `TestAssessmentSignalReviewJobWaitsForTheReviewLock` holds the review lock of an attempt in one transaction and checks that the review job waits, writes nothing, and computes the review from the committed facts once the lock is released; this is the ordering that prevents a stale evaluation from overwriting a newer review. The concurrent test was run ten times in a row (`-count=10`). `TestAssessmentSignalReviewMigrationDownRetainsAudit` checks that the rollback of migration 33 is refused while the audit holds a row (the tables and the row stay, TRUNCATE is refused) and succeeds with an empty audit.
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 4 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 the current version, and its versions follow `CurrentSignalNoticeVersion`.
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 4. 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.
## Assessment watermark tests
`backend/internal/domain/assessment_watermark_test.go` covers the mark: two attempts that were served one real generated variant get different marked statements whose canonical text and reference answer are equal; marking is deterministic and idempotent; the invisible run decodes to the visible code, survives a copy of two sentences, and a cut, padded, or mis-checked run is ignored; the accessible text holds the words only; the alignment of a stored statement with a leak reads only the phrases that it finds there (words around the statement, such as a quotation or a message, are ignored), the wording agreement of the attempt that wrote the text holds for every phrase group, other seeds disagree, a fragment yields the phrases of the fragment, an unrelated text aligns nothing, and another variant of the same family aligns for fewer characters than the leaked one; the pieces between the phrases are the same in every copy of a statement; the number guard keeps `at most` at the end of a sentence; codes parse the way an operator or OCR reads them. `usecase/assessment/watermark_test.go` checks that only root and corrective attempts are marked, that the stored snapshot is not changed, that the visible code equals the invisible one, and that a missing `Watermarker` leaves snapshots alone; `adapter/primary/http/v1/assessment_test.go` checks that every attempt response goes through the presenter and that a presenter failure is an error. `TestAssessmentWatermarkOverHTTP` (PostgreSQL) checks over HTTP that a real attempt shows the code derived on the server and a marked prompt on creation, on a read, and on a replay, that a training run shows neither, that the response holds only the code, and that the stored statement has no mark. In the frontend, `features/assessment-watermark` has Vitest tests of the text split, of the accessible text of the rendered markup (everything in `aria-hidden` removed leaves exactly the words), and of the tile (code and UTC time, no `@`, hidden from assistive technology). `e2e/assessment-watermark.spec.ts` runs against the mocked API (also on the Vite server, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-watermark.spec.ts --project=chromium`): the tile is on the task screen with the code and the time and without the account e-mail, is faint and takes no click, an attempt without a code shows no tile, and the accessibility tree of the marked prompt holds the words and no format character while the document keeps them. These tests do not run a real screen reader, a braille display, or another browser, so they do not show how a reader speaks the text; they do not show how many attempts a leak can be told from either, because the wording channel gives about one bit per phrase group.
## Assessment capture hint and work session tests
Domain and usecase. `assessment_signal_review_test.go` has the band rules: capture hints, extra User-Agents, and every weak signal together stop at attention however large their counts, the extra agents reach review only beside a strong signal, and a policy without the capture thresholds ignores the hints. `assessment_signal_policy_test.go` checks that a version published before these fields decodes with them off and encodes back to the same document (so its content hash holds), that the demo policy was not edited, that the thresholds round-trip, and that out-of-range or inconsistent values are rejected. `assessment_signal_test.go` covers the two new event kinds and their refusal with a measurement. `assessment_work_lease_test.go` covers the hold: one page admitted, a second refused until release or expiry, a renewal that keeps the acquisition time, release only by the holder, and invalid leases. `usecase/assessment/work_session_test.go` runs the steps of the hold and the check of the answer and the session start against in-memory repositories: a second page, a page without the header, and a request after an expiry; a training run and a service without work sessions are never refused; the origin of a hold is recorded with the User-Agent digest only. `signal_review_test.go` checks that the origin mark keeps the User-Agent as a keyed digest, writes a new mark only on a change, and that the review counts the extra agents and capture hints and stops at attention. `keyring_test.go` checks the new digests are keyed, bound to the attempt, and separate from each other. The HTTP adapter tests check the mapping of the hold, the release, the refusal of a held attempt on the session start and the answer, the new event variants and their mismatches, and the User-Agent bound.
Over HTTP with PostgreSQL. `TestAssessmentWorkSessionOverHTTP` creates a real attempt and checks that the first page holds the session, that a second page, and a request without the header, are refused for the hold, the session start, and the answer with 409 and nothing is stored, that the refusal is not stored under the key (the holder reuses both keys), that another page's release changes nothing, that the holder's release frees the session at once, that a hold that stopped renewing ends by itself, that bad page identifiers answer 400 and a missing CSRF token 403, that only digests of the page and the User-Agent are stored (no table text holds a page identifier or a browser string), that the capture events are stored without a measurement and refused with one, and that the review job gives the band attention with the extra agents and capture hints counted. `TestAssessmentSignalNoticeOverHTTP` follows `CurrentSignalNoticeVersion`. The migration 50 constraints are exercised by these tests.
Frontend. Vitest covers the key rules (`capture-keys.test.ts`), the heuristic and its watcher with fake windows and timers (`devtools-heuristic.test.ts`), the collector (one event for a press and its release, no cancelling, no event without an item), the session wiring of the watcher, the work session controller (held, busy, lost at a renewal, a network gap, a release during a renewal, the renewal bounds, `work-session.test.ts`), the page identifier header of the answer command, and the notice version 4 text. `e2e/assessment-capture.spec.ts` runs against the mocked API (also on the Vite server, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-capture.spec.ts --project=chromium`): PrintScreen and Cmd+Shift+4 are recorded as `screenshot_key` events with no key or image, the key event is not cancelled and the test goes on to an answer; a faked docked panel is recorded as `devtools_open`; a second tab opened on the attempt is refused with the explanation and shows no task, nothing is started in it, the first tab is undisturbed, and after the first tab leaves the second continues; `pagehide` releases the session; a tab that loses the session at a renewal stops and says so. These tests do not show behavior in other browsers or on a phone, whether the operating system hands a shortcut to the page, what a real screenshot looks like, or how often the heuristic is wrong on real windows; the mock server stands for the rules of the real one, which the HTTP test covers.
## Assessment leak trace tests
`backend/internal/usecase/assessment/leak_trace_test.go` runs the tracer against in-memory repositories with real watermarks: the leaked text of a variant, among other words, finds the right one of three attempts that were served the same statement (by the invisible mark); with the invisible characters removed, the visible code of the tile text finds the attempt, and the wording alone separates the attempts that were served the same statement and chose different phrases; the visible code tolerates one misread character and not two; unrelated text, a text that is too short, and a mark of no attempt are not found and say why; a statement that only one attempt holds is found by the variant and excluded when its wording contradicts the text; attempts that chose the same phrases, or a text with no phrase group, are ambiguous without naming one; a mark attached to another text is found and flagged; a mark and a visible code that name different attempts are ambiguous; another variant of the same family does not compete with the leaked one, and the leak of a deleted attempt is not attributed to the variant of its family that is left; a leak cut inside the statement is found, while other words where the statement continues are not; every search is audited with a keyed digest and no part of the text, the same text gives the same digest, and a failed audit fails the search; bad requests are refused without quoting the text. `domain/assessment_watermark_test.go` covers the alignment and the wording agreement (only the phrases aligned with the stored statement are read, a fragment, unrelated text, another variant aligning for fewer characters), `domain/assessment_leak_trace_test.go` the audit record, `usecase/identity/keyring_test.go` the keyed text digest, `config/identity_test.go` the secret reader, and `adapter/primary/cli/leaktrace/command_test.go` the argument rules, the file and standard input reading with its limit, the output (the outcome and fixed notes, never the text, an honest not found), safe error messages, and that the environment is not read before the arguments are valid. `TestAssessmentLeakTraceOverHTTP` (PostgreSQL) creates two real attempts over HTTP and checks that the marked prompt finds the first by its mark, the prompt without invisible characters finds the second by its statement, the text of a screenshot with the tile finds the first by its visible code and the tile time, unrelated and short text are not found, a search changes no attempt version or state and no review or result, every search is audited without the text, the audit refuses UPDATE, DELETE, and TRUNCATE and a found row without an attempt, the audit outlives a deleted attempt (which is then not found), and the command with the secret of the server finds the attempt while one with another secret does not read the mark. They do not run an OCR tool, so what the command does with the real recognition errors of a screenshot, and how well the wording separates attempts on a real bank, are not measured here.
## Internal notification tests
Unit tests (`make -C backend test`, `make -C frontend test`):
- `domain/notification_inbox_test.go`: an entry accepts only the allowlisted pairs of event type and source type (the synthetic event with the organization, `invitation.delivered` with the invitation), a new entry starts unread, and `MarkRead` keeps the first time.
- `usecase/notification/inbox_test.go` with an in-memory repository and a fake unit of work: the list resolves each item against its current source and falls back to no content; a candidate cabinet refuses an employer, the organization cabinet refuses a candidate, an unknown or unverified account, and a revoked membership (which answers like an unknown organization, for the list and for the mark); a repository row outside the recipient scope is an internal error; an owner and a recruiter (and the other roles) read and mark only their own items of the organization, with the membership locked for the read; an unverified employer gets `ErrInboxEmailNotVerified`; a mark keeps the first time and cannot touch another recipient's item; content links reject an external URL, a protocol-relative URL, a query, a fragment, a backslash, an escape, a dot segment, and a long path; the synthetic resolver follows the recipient's standing and an unregistered source type is unavailable.
- `usecase/notification/inbox_handler_test.go`: a repeated event stores one row; a broken schema version, aggregate, unknown field, missing organization, non-object payload, trailing data, and an event ID reused with other metadata are rejected for good; a deleted recipient is skipped; a store failure stays retryable; an unverified address still gets its row (the inbox reads no mail state); a recipient that vanished between the check and the insert is retried and then skipped, not rejected; the synthetic event is ignored while its switch is off; an `invitation.delivered` event with the same payload contract stores the invitation as its source.
- `adapter/primary/http/v1/notifications_test.go` and `adapter/primary/http/notification_contract_test.go`: the mapping of content and fallback, the cursor bound to the account and the cabinet (a foreign or crossed cursor is a 400), the refusals, the conventions of the four operations, and closed schemas. `bootstrap/consumers_test.go` pins the two registered consumers.
- Frontend: `features/notifications/` tests the link check, the retry of a mark once after a 403 (and no retry of a 401, 404, or 500), the labels, the wording of an item without content, the query keys and their removal by account, and the rendered list (read state as a word, a mark button only for unread items, no unsafe link, the empty state, the refusal of the other cabinet).
Integration tests (`make -C backend test-int`; PostgreSQL and Redis, no Kafka): `TestNotificationInboxOverHTTP` writes a synthetic event through the real outbox writer and delivers it through the consumer store with the real handler. One event delivered twice and once more by a renamed consumer stores one row. The same router then checks the candidate list, a foreign candidate, the wrong cabinet, a missing CSRF token and a foreign Origin, the mark and its repeat (the first time is kept), the persistence of the read state, the loss of content when the candidate hides the organization, paging with a cursor bound to the account, the employer cabinet with only its own items of the organization, a recruiter with its own items, a non-member, an item of another organization, and the 404 for the list and the mark after the membership is revoked. `TestSyntheticNotificationMigrationAllowlistAndGuardedRollback` and `TestSyntheticNotificationMigrationRollsBackWithoutSyntheticRows` check the allowlist of migration 00036, the refused rollback with a synthetic row, and the restored constraint. `TestNotificationInboxStoreNamesTheMissingReference` checks that a missing recipient and a missing organization are told apart. `TestPostgresMigrations` covers up and down to zero.
Browser test: `frontend/e2e/notifications.spec.ts` runs in `make -C deploy test-e2e-registration`, whose overlay sets `NOTIFICATION_SYNTHETIC_ENABLED=true`. The `company-fixture` (Go build tag `e2e`, bearer token, synthetic `@example.test` recipients only) appends a synthetic event to the real outbox, so the relay, Kafka, and the `notification_inbox` consumer deliver it; the test waits for the item. It then replays the event through the fixture, which must report that the real consumer had already applied it, and checks that the list still has one item. A candidate then opens the list, marks the item with the keyboard, reloads and sees the state kept, and a second candidate gets an empty list and a 404 for the same ID. After the organization is hidden the item stays without content. A second test reads the organization inbox as an owner, checks a non-member, revokes the membership through the fixture, and checks that the same ID is refused and that the page shows no content.
What these tests do not show: a real invitation event through Kafka and the relay (`TestOrganizationInvitationSendOverHTTP` delivers it through the handler storage only), the behavior of the inbox when the mail provider fails (the handler reads no mail state by construction, and the unit test covers an unverified address), delivery latency or load, push or live updates, and the layout and the screen-reader behavior of the page (no automated check).
## Demo seed tests
`backend/internal/usecase/demoseed/seeder_test.go` checks without a database that a reset is allowed only for a database without accounts or with synthetic accounts only, that the synthetic bundles pass the loader rules and are identical between builds (so a repeated import changes nothing), that the prepared answers have the intended correctness, and that the dataset has two employers on the synthetic domain, one self-service candidate, and a cohort of at least five prepared candidates. `backend/internal/adapter/primary/cli/demoseed/command_test.go` checks the argument parsing, that every subcommand refuses without `DEMO_MODE=isolated` before it reads the database settings, that a short password is refused without echoing it, that the seed output names the logins and the prepared attempts but never the password, that failures become safe messages, and that `check-reset` fails on any account outside the synthetic domain.
`TestDemoSeedCommand` in `backend/integration_test/demo_seed_test.go` uses `bootstrap(t, postgresService)` and runs the operator command against migrated databases that carry the startup policy:
- Without the isolated mode, also against an unreachable database, every subcommand refuses, and nothing is written.
- A database with an ordinary account and no seed is refused by both the seed and the reset check; the account and the policy stay as they were.
- The first seed creates nine confirmed synthetic accounts, two organizations, three memberships (the owner of Alpha is a recruiter of Beta), six prepared attempts with results, current synthetic categories, evidence, and published cards, the seed policy version, 28 published families, one opening, one attestation, and one training binding. A second seed by another operator creates nothing and prints the same inventory.
- Every synthetic candidate stands at the onboarding step `candidate_assessment`, which a saved questionnaire leaves, and both employers stand at `employer_company`. A stand whose candidates were left at the consent step is repaired by one more run: it prints an `updated` line for each candidate on an earlier step, keeps a candidate on a later step, creates nothing, and keeps the inventory the same.
- Every organization, profile name, and prepared profile carries its synthetic or prepared marker, and every category is an uncalibrated `synthetic_demo` category.
- The owner of Alpha sees exactly the six prepared cards through the card listing that the search uses, and not the unpublished self-service candidate.
- A perfect express run of the self-service candidate through the attempt operations draws three items from the training category, ends as `demonstration` with the Russian training summary, and adds no category and no evidence; the same candidate can then start the full test.
- After an ordinary account registers on the seeded database, the reset check refuses and counts it, a repeated seed still creates nothing, and the account is unchanged.
`make -C deploy check-demo` (part of `make -C deploy check`) runs `deploy/scripts/demo.sh` against a recording stub of the docker CLI: every action refuses without `DEMO_MODE=isolated`, with a project name that equals `APP_PROJECT` or lacks `demo`, with an invalid actor, or without the env file, before any Docker command; a project volume without the demo label is refused before any Compose command; a refused reset check stops the reset before `down`; a reset addresses only the demo project and seeds again; `down` keeps the volumes; a release manifest that cannot be restored stops `seed` and `reset` before any Compose command, and `down` ignores it. With the docker CLI it also renders the overlay: only the frontend is published, on loopback; the seed container has only the default network, a read-only root, and the explicit profile; every volume carries the demo label; the demo backend enables synthetic categories; the release overlay names the seed image `lincodex.invalid/demo-seed:<tag>` with `pull_policy: never`; and the backend images do not contain the command.
The tests do not run the Make targets against a real stack. A manual check on a throwaway project: `make -C deploy demo-seed DEMO_MODE=isolated DEMO_PROJECT=lincodex-demo-check DEMO_HTTP_PORT=18090` twice with identical inventories, a sign-in of the prepared accounts with mail disabled, an express run and the start of the full test, then `demo-reset` refused after a visitor registered. Remove the project afterwards with `docker compose -p lincodex-demo-check down --volumes` and the same variables. The tests do not validate the content of the synthetic bank or any grade, and the browser route of the jury is not covered here. Integration tests need Docker.
## Code runner tests
| Command | What it checks |
| --- | --- |
| make -C runner test | Unit tests with the race detector: checkers, configuration, judge outcomes on a scripted sandbox, idempotency and busy handling of the run manager, the HTTP API (token, 202/200/422/503, 400, 413, 404), and that logs carry no source, input, or token |
| make -C runner lint | golangci-lint for Linux, including the isolation tests |
| make -C runner check-generated | The generated ogen server matches the bundle |
| make -C runner test-sandbox | Reference solutions and isolation tests in a privileged dev container with real nsjail and cgroup v2 |
| make -C runner test-a16 | The A16 suite only, with a report in `runner/.reports/`; `A16_ENV` passes `RUNNER_*` variables |
| make -C runner a16-bundle | A bundle of the A16 suite for the runner host |
| make -C deploy check-runner-dev | Dev switches stay out of production files |
| make -C deploy check-runner-vm | The runner VM script keeps the VM boundary: a VM with only its profile, no shared device, privileged or raw setting, sudo, or dev switch, the sandbox and budget settings of the unit, a static address without a route, and secrets outside the repository |
| make -C deploy runner-vm-check | On the app host: the live runner VM, see [DEPLOY.md](DEPLOY.md#steps-of-the-vm-script) |
| make -C deploy runner-vm-a16 | On the app host: the A16 suite in the runner VM with the service's sandbox settings |
First, `test-sandbox` runs the reference solutions of `runner/testdata/judge/manifest.json` on three tasks with one public and three hidden groups: correct and incorrect Python and Go solutions get the expected outcome of every group (`exact` and `tokens`; `numbers` on fractional answers with an absolute and a relative tolerance; `custom` with a Python and a Go checker in nsjail); Go code with a compile error gives `compile_error` with a `main.go:` message and no test runs. The test also checks that a group stops at its first failed test, hidden tests carry no diagnostic, and the run directories and cgroups are removed.
Then `test-sandbox` runs the A16 suite (see below).
### A16 hostile-program suite
`make -C runner test-a16` builds the image and runs only the A16 suite in a privileged dev container without network and without an init; a JSON report is written to `runner/.reports/` (ignored by Git). The cases and expectations are in `runner/testdata/hostile/manifest.json`, with programs in Python and in Go:
| Category | Attempts | Expectation |
| --- | --- | --- |
| network | TCP, UDP, listen, DNS, raw ICMP, AF_PACKET, and netlink sockets | all refused; the probe prints `blocked` |
| files_and_secrets | `/etc/passwd`, `/etc/shadow`, `/run/secrets` and the API token, runner files, `/proc`, `/sys`, `/dev/mem`, environment variables with `RUNNER`, `TOKEN`, or `SECRET`, writes to the root, the source, and `/out` | nothing is visible or writable except `/tmp` |
| privileges | setuid, setgid, chown to root, raising an rlimit | refused; uid and gid are not 0 |
| escape | ptrace, mounting a fresh procfs, unsharing a user namespace | the process is killed by seccomp (SIGSYS, `runtime_error`) |
| processes | fork bomb, and a thread bomb in Go (256 goroutines blocked in system calls, so the stacks stay far below the memory limit) | the cgroup process limit (`runtime_error`, limit `processes`) |
| memory | unbounded allocation, and in Go unbounded goroutines parked on a channel (no new threads) | the cgroup memory limit (`memory_limit_exceeded`) |
| disk | one large file and filling `/tmp` | refused by the file size limit and the tmpfs size |
| output | endless output | the output limit (`output_limit_exceeded`) |
| timeout | a busy loop that ignores signals, a sleep, a detached daemon in its own session | the CPU limit, the wall-clock limit; the daemon dies with the PID namespace |
Baseline cases check that a correct solution is accepted and a syntax error gives `compile_error`. After every case the test checks that the run directory is empty, the run cgroups are gone, no live uid 99999 process is left, and no new unreaped (zombie) process appeared; the suite runs without an init, so this confirms that nsjail reaps every stopped process.
The report records the runner version (`git describe`), the kernel (`uname`), the cgroup controllers, the nsjail package version and SHA-256, the isolation profile (nsjail arguments of a sample test run, the seccomp policy, cgroup and rlimit limits), the result of every case, and the verdict. Any failed case gives the verdict `fail` and `practice_may_be_enabled: false`: practice must not be enabled until the suite passes on the runner host.
Checking the suite itself: `TestA16WeakenedProcessLimitIsDetected` raises the process limit to 4096 in a test copy of the configuration and requires the processes cases to fail. The same by hand: `make -C runner test-a16 A16_ENV="RUNNER_SANDBOX_MAX_PROCESSES=4096"` exits with an error and a `fail` report on exactly the three processes cases.
On the runner host the suite runs from a bundle: `make -C runner a16-bundle` (`A16_GOARCH=amd64` by default) builds `runner/bin/a16-bundle.tar.gz` with the test binary, the fixtures, and `run-a16.sh`; on the VM it is unpacked and started with `sudo sh run-a16.sh [report.json]` and the same `RUNNER_*` variables as the service. The script does not use the network and writes only the report and the work directory. On the production VM, `make -C deploy runner-vm-a16` does this in a transient systemd unit with the sandbox settings of the service; the results of 2026-10-11 (20 of 20 runs pass with exit status 0) are in [DEPLOY.md](DEPLOY.md#verification-on-the-app-host).
What the tests do not prove: isolation in the production VM until the suite has passed there; protection against kernel, nsjail, or cgroup vulnerabilities; the absence of side channels (timing, CPU caches); or behavior under load.
## Code practice tests
`TestAssessmentPracticeSubmissionStorage` in `backend/integration_test/assessment_practice_http_test.go` uses `bootstrap(t, postgresService, redisService)`, an isolated migrated database, the real router, the practice usecase, and the PostgreSQL repository. No flow serves practice items yet, so the test moves a real attempt to `practice_pending` and creates its main and additional practices directly; the synthetic task marks every hidden test text. The sequential cases are:
- A debug run answers 202 with `Cache-Control: no-store`, is stored with exactly one queued job, and a repeat with the same key and body returns the same run without a new row; the same key with another body answers 422. Another candidate, another attempt, and an unknown run read as 404.
- Refusals store nothing: a practice of another candidate (404), the additional practice while the attempt is at the main one (409), and a source over the bound of the task (400).
- A stored result that also holds a hidden group is shown with the public tests only; the response has only the contract fields and no hidden text, source, or test text.
- A final solution marks the practice `pending` and is stored with one job; a replay returns it, the same solution under a new key stores nothing, another solution conflicts, and a reused key with another body is refused. The database refuses to replace the source or the language of the stored solution, to delete it, and to write a second result. After a sandbox failure the practice accepts another solution, and the first one stays as it was.
- With the runner disabled a run is refused as unavailable and nothing is stored. At the end every stored submission has exactly one job.
`backend/internal/usecase/practice/request_test.go` checks that the runner request of a debug run holds only the public examples and the candidate's tests, and that of a final solution exactly the three hidden groups.
`TestAssessmentPracticeQueue` in `backend/integration_test/assessment_practice_queue_test.go` uses the same harness with the Redis limiter (two debug runs a minute), the real PostgreSQL job store, executor, and worker, a fake runner that is idempotent by run key and counts the runs it starts, and a test clock for leases and waits. Its sequential cases are:
- Twelve candidates start a debug run at the same moment: eleven are accepted and exactly one answers 503 `service_unavailable` with `Retry-After` and stores nothing. While the runner holds the run, the jobs are one `running` and ten `queued`, and a second worker claims nothing. After the runner finishes, all eleven are `finished`, each submission ran once, and eleven results are stored.
- With eleven runs queued, a final solution is answered with the practice `failed` and `sandbox_busy`: no submission is stored and the attempt version does not move. After the queue drains, the same solution is accepted and finished.
- A busy runner puts the job back without a counted attempt and the job waits for the runner's `Retry-After`; an infrastructure failure counts one attempt, raises the generation, and keeps the practice `pending` without a result; after the backoff the next try finishes it.
- A worker is killed mid-job (its pool closed, so it cannot give the job back): another worker claims nothing while the lease lives, takes the job over after it expires, and finishes it on the same run key, with one run on the runner, one counted takeover, and one result; a late completion by the killed worker is refused and leaves the result unchanged.
- A second debug run while the first is unfinished, and a third within a minute, answer 429 `rate_limited` with `Retry-After` and store nothing.
Unit tests: `usecase/practice/execute_test.go` checks with fakes that an unreachable runner keeps the run key, an infrastructure failure and a reused key raise the generation, an invalid request and the last attempt fail without a stored result, a lost run is submitted again, and a shutdown gives the job back uncounted. `config/practice_test.go` checks the defaults and refused values of the practice settings. The tests do not run code in a sandbox and do not prove the timing of a real runner.
## Semantic matching tests
- ML service (`make -C ml test`, no model, no network): `tests/test_embeddings.py` checks the `POST /v1/embeddings` contract on the deterministic hash encoder: response order, normalization, equal vectors for two equal requests, micro-batches by length, 503 `service_unavailable` before readiness and ready only after the warm-up, 400 for too many texts, a length, and unknown fields, 413 for a body over the limit (with Content-Length and streamed), and no request text in the logs; `tests/test_model_files.py` checks the lock file (only safetensors and configs, a full revision, no code or pickle) and the size and SHA-256 verification.
- Ensemble and ML token (`make -C ml test`): `tests/test_ensemble_and_auth.py` checks the choice of one of several loaded models by `model` and 400 for another one, readiness only after every model, a refusal of two encoders with one id, 503 and a readiness cool-down after a lack of device memory with recovery, a retried load on a lack of memory and the exit through `ML_EXIT_ON_LOAD_FAILURE` on another failure, 401 without a token, with a wrong token, with the Basic scheme, and on `/metrics`, open `/healthz` and `/readyz`, loopback only without a token, a refusal before the body is read, no token in logs or settings errors, and the entry point refusing a non-loopback address without a token. Checked by hand on CUDA: a load without enough memory is retried while the process stays alive and not ready; a request over the allocator limit answers 503, `/readyz` answers 503 for 30 seconds, and then the service answers 200 again.
- The real models: `make -C ml model-fetch` and `make -C ml test-model` (marker `slow`, skipped by the ordinary checks) compare the Giga-480M and Qwen3-Embedding-0.6B vectors with the study's vectors for four texts (difference below 1e-4) and a repeated encode (the same vector); `ML_TEST_DEVICE=cuda` runs them on the GPU in float32. On 2026-10-11 both models passed on CPU and on CUDA on the GPU host. This checks that the recipe is reproduced, not model quality; the float16 against float32 comparison and the fit of the ensemble policy are a separate evaluation on the study's DEV data (see [DEPLOY.md](DEPLOY.md#ml-service-on-a-gpu-host)).
- Backend unit: need and card views (`domain/semantic_test.go`: the exact study text, confirmed values only, metadata only for a verified repository), the float32 codec and cosine, the calibration (interpolation, steps, a monotone demo table), the thresholds, validation and the round trip of the V5 policy document; projects and GitHub addresses (`domain/candidate_project_test.go`: accepted and rejected addresses, normalization, limits, a repeated repository, no address in the card); explanation selection (`usecase/matching/semantic_test.go`: order, limit, a stale title, a hidden stack or hidden projects explain nothing, the `projects` field record); Fit with a known and the neutral Sem; the ML client (batches of 32, response checks, the circuit breaker, no text in errors); GitHub (`adapter/secondary/github`: httptest, public repositories only, the token only when set, ETag and 304, 403/429 limits with the wait, server errors, a refused redirect to another origin, size caps, README text without markup or HTML); jobs and the trigger (keys and payloads without the repository address, disabled features schedule nothing).
- Integration (Testcontainers): `TestSemanticMatchingOverHTTP` runs over HTTP, PostgreSQL, and the real job worker with a fake ML service (httptest on the contract) and a fake GitHub: a profile save schedules jobs without the address in their keys, the repository check and the card vectors, the neutral Sem and flag before the need vectors, then the candidate with the close project first, the explanation names the project and `repository_verified`, and neither the response nor the card carries the repository address or owner; equal responses of two searches; the access history with the `projects` field; a repeated backfill with the same label schedules nothing twice and calls ML for no unchanged text; unpublishing `projects` removes the project vectors and the title from the explanation; an unavailable ML keeps the job in retry while the search answers; the refresh limit (429, then 202).
- Ensemble and token in the backend: unit tests `domain/policy_matching_ensemble_test.go` (the ensemble policy validates, Giga explains with its thresholds, the fused score is 0 at the means, the calibration is monotone and clipped, the V6 document round trip), `usecase/policy` (the ensemble published on top of V5, a repeat publishes nothing, the single-model command leaves the ensemble alone), `cli/policypublish` (the `semantic-ensemble` track), `adapter/secondary/ml` (the bearer token on every request, 401 as unavailability without the token text, no client without a token), `config` (the token is required while matching is enabled, short and spaced tokens are refused, formatted settings hide the tokens). In `TestSemanticMatchingOverHTTP` the fake ML requires the token and serves both models; after the ensemble publication and before the backfill every entry has the neutral `Sem`, and the backfill adds Qwen3 `whole` vectors for the six cards and the need without re-encoding Giga and without Qwen3 item vectors, after which every entry has a known `Sem`.
- Not checked: ranking quality and explanation precision on real data, latency on the production server, the ML image build on this machine, and a stand with the model. Tests never call the real GitHub.
## Future software validation
Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter.
Isolate test data by database/schema or run scenarios with a sequential reset. Do not run parallel cases against shared truncation. Reuse the bootstrap environment within a parent test; independent tests create their own environments. Integration CI must not silently skip tests when its container runtime is unavailable.
Validate contract changes with bundle, lint, codegen for every Go, TypeScript, and Python consumer, and generated drift, including new untracked files. Frontend component tests do not replace browser tests of the complete flow. After product implementation, extend the Playwright suite with both roles and a synthetic candidate without FSP history.
Critical future checks:
- Before offer acceptance, another company sees no contacts through API, search, PDF, errors, or ML explanations.
- A candidate cannot access another user's invitations, files, jobs, or attempts; a company cannot access another company's needs or search runs.
- Assessment failure does not lower grade; the first lower-level retry is allowed; concurrent requests cannot bypass cooldown.
- Repeated submission or acceptance is idempotent; concurrent status transitions are serialized.
- The manual path works with ML off; expired worker leases recover; stale results do not overwrite a newer profile.
- Missing FSP history differs from an integration error and does not exclude the candidate.
- Search refinement preserves an earlier snapshot; a withdrawn profile disappears from it.
## Future quality evaluation
Evaluate ranking separately from functional tests. Initial plan: 60-100 synthetic candidates, 8-12 needs, two independent labelers, disagreement review, and a holdout split by need. Near-duplicate profiles must not appear in both tuning and holdout.
Compare keyword search, verified skills, and ML. Measure Precision@5, nDCG@5, hard-filter violations, category coverage, and the share of relevant results without FSP history. Define the denominator before the run when fewer than five candidates qualify and report result-set size. Synthetic data does not prove quality for the real market.
Assessment evaluation needs a human pilot and independent expert skill ratings. Compare equivalent forms, vary their order, and measure grade agreement, score spread, task-level decisions, and group separation. Synthetic answers help debug a rubric; they do not replace a pilot.
ML evaluation records a fixed document set and field labels, extraction precision, invented facts, recommendation usefulness, schema-valid rate, latency, and failures. Record model, prompt/schema version, parameters, and date. Compare against a simple baseline and use lawfully handled de-identified documents.
Proposed targets are 30 concurrent users, p95 profile reads under 500 ms, and baseline search under one second on demo data excluding external network time. These are future acceptance criteria; no results are available. Set a separate ML latency budget.