docs: simplify project guides and add GPLv3
This commit is contained in:
1 parent
e4de6d0f9a
commit
76d32bb79f
59 files changed
+2267
-8843
No files matched your search
+2
-3
@@ -4,11 +4,10 @@
|
||||
|
||||
Guides to the project's structure and development workflow. Russian documents live in `ru/`, with English translations in `en/`.
|
||||
|
||||
- [ARCHITECTURE](en/ARCHITECTURE.md) covers service boundaries, layers, and planned product workflows.
|
||||
- [ARCHITECTURE](en/ARCHITECTURE.md) covers components, data flows, and implementation boundaries.
|
||||
- [DEVELOPMENT](en/DEVELOPMENT.md) covers project structure, code generation, and development rules.
|
||||
- [DEPLOY](en/DEPLOY.md) covers the MVP quick start and the demo stand, startup, environment settings, and monitoring.
|
||||
- [DEPLOYMENT](en/DEPLOYMENT.md) covers the MVP quick start and the demo stand, startup, environment settings, and monitoring.
|
||||
- [TESTING](en/TESTING.md) describes test types, commands, and check boundaries.
|
||||
- [SECURITY](en/SECURITY.md) describes scanners, reports, and security exceptions.
|
||||
- [MVP](en/MVP.md) is the submission package of the minimal release: what is implemented, how to run it, limits, what is not implemented, and checks.
|
||||
|
||||
Update both language versions together. From the repository root, `make docs-check` checks documentation structure and local links. Source requirements and brand assets live in [requirements/](../requirements/README.en.md).
|
||||
+2
-3
@@ -4,11 +4,10 @@
|
||||
|
||||
Руководства по устройству проекта и работе с ним. Русские документы находятся в `ru/`, английские переводы - в `en/`.
|
||||
|
||||
- [ARCHITECTURE](ru/ARCHITECTURE.md) - границы сервисов, слои и запланированные продуктовые сценарии.
|
||||
- [ARCHITECTURE](ru/ARCHITECTURE.md) - компоненты, потоки данных и границы реализации.
|
||||
- [DEVELOPMENT](ru/DEVELOPMENT.md) - структура проекта, кодогенерация и правила разработки.
|
||||
- [DEPLOY](ru/DEPLOY.md) - быстрый старт MVP и демонстрационный стенд, запуск, настройки окружения и мониторинг.
|
||||
- [DEPLOYMENT](ru/DEPLOYMENT.md) - быстрый старт MVP и демонстрационный стенд, запуск, настройки окружения и мониторинг.
|
||||
- [TESTING](ru/TESTING.md) - виды тестов, команды и границы проверок.
|
||||
- [SECURITY](ru/SECURITY.md) - сканеры, отчеты и исключения безопасности.
|
||||
- [MVP](ru/MVP.md) - пакет сдачи минимального выпуска: что реализовано, запуск, ограничения, нереализованное и проверки.
|
||||
|
||||
Обе языковые версии обновляются вместе. Из корня репозитория: `make docs-check` проверяет структуру документации и локальные ссылки. Исходные ТЗ и брендбук находятся в [requirements/](../requirements/README.md).
|
||||
+103
-1283
File diff suppressed because it is too large.
Load diff
@@ -1,47 +0,0 @@
|
||||
# Company quotas
|
||||
|
||||
Company quota reservations are implemented in the domain, `companyquota` usecase, and PostgreSQL adapter. They provide a transaction-bound storage port for invitation and candidate-card usage. An invitation spends one place of the weekly quota when it is sent (`SendOrganizationInvitation`): a draft spends nothing, and a repeat of the send of the same invitation does not spend a second place. An invitation that leaves the waiting state (a decline, an expiry, an acceptance) frees its place in the per-need pending limit, but never returns the weekly quota; see [Pending limit, cooldown, and expiry](ARCHITECTURE.md#pending-limit-cooldown-and-expiry).
|
||||
|
||||
## Policy and trusted organization level
|
||||
|
||||
Each operation takes one UTC application-clock snapshot and reads the effective version of `ProductPolicyKey`. Limits come from that versioned policy. The bundled demo policy currently enables E0 at 10 invitations per rolling 7 days and 50 distinct candidate-card views per rolling 24 hours. E1 is 40 invitations per 7 days and 150 distinct views per 24 hours.
|
||||
|
||||
E2 has configured limits of 100 invitations and 400 distinct views, but its tier is inactive in the bundled demo policy. E2 can be used only when an effective policy activates it and the organization loaded from storage has the corresponding verified level and basis. E3 has no quota tier and is denied. The caller cannot choose or raise a tier.
|
||||
|
||||
The quota snapshot captures the policy version and the stored organization verification level, basis, and change time. Before writing, the PostgreSQL adapter locks the organization and checks those values and the effective policy version again. If either changed, it returns `outbound.ErrCompanyQuotaSnapshotChanged` without writing usage. The caller must reload policy and organization state, then retry the whole transaction.
|
||||
|
||||
## Reservation and transaction order
|
||||
|
||||
Call `companyquota.Service.ReserveInvitation` or `ReserveCardView` with repositories from the current `outbound.UnitOfWork`. The repository returned by `UnitOfWork.CompanyQuotas()` is transaction-scoped and must not be retained. Make the quota reservation and its eventual business change in the same transaction so rollback removes both. The service is constructed with the application clock and reads the effective policy once per operation.
|
||||
|
||||
Tenant authorization remains the caller's responsibility. Recheck active membership and owner permission inside the same transaction. Writers follow this order: organization, then for an E0 organization its holding (see [Holding pool](#holding-pool)), active membership, invitation or visibility record, then quota usage. The quota adapter locks the organization row first and, for an E0 organization, the holding row right after it; a caller that already holds those rows may lock them again in the same transaction. Do not reverse this order.
|
||||
|
||||
The organization lock serializes concurrent reservations of one organization, and the holding lock serializes the shared E0 pool. The adapter checks existing usage, counts the active window, and inserts or refreshes usage while those locks are held. A decision is either allowed or denied; reuse implies allowed. A denied reservation writes no usage and includes `RetryAt`, the earliest active usage expiry that can free capacity.
|
||||
|
||||
## Windows and retries
|
||||
|
||||
An invitation is keyed by `(organization_id, invitation_id)`. Repeating the same invitation ID is allowed as reused, even with a different request idempotency key and after the rolling window. Its usage evidence remains for the organization's lifetime, so removing an invitation in a future workflow will not refund quota.
|
||||
|
||||
A card view is keyed by `(organization_id, candidate_id)`, so viewing the same candidate again during the active window does not consume another distinct-view slot. The repeat refreshes `last_seen_at` monotonically: a backdated application clock cannot move the stored time backward.
|
||||
|
||||
The active-window query uses a strict comparison with the cutoff. A row exactly at `now - window` has expired. Invitation usage is counted over seven rolling days; card views are counted over 24 rolling hours. The limits apply across requests and users of the organization, except that an E0 organization shares its limits with the other E0 organizations of its holding (see [Holding pool](#holding-pool)).
|
||||
|
||||
Expired card-view rows are deleted in batches of at most 100 after a successful allowed reservation. Window expiry is logical; this cleanup does not promise deletion at an exact time. Deleting a candidate account cascades its card-view usage row. Deleting an organization cascades both quota tables. Invitation usage has no invitation foreign key, so future invitation withdrawal cannot erase its idempotency evidence.
|
||||
|
||||
## Holding pool
|
||||
|
||||
A holding groups the organizations that one founder account created; the `holdings` table and the migration `00041_create_holdings.sql` store it. `CreateWithOwner` stores each new organization in the holding of its owner account in the same transaction. The holding of an account is created with its first organization, and concurrent creations of one account end in one holding, because the insert ignores an existing founder key and the transaction then reads the stored holding. A holding carries no profile and no right; its only effect is the shared E0 pool.
|
||||
|
||||
The E0 limits (10 invitations per 7 days and 50 distinct card views per 24 hours in the bundled demo policy) are shared by the E0 organizations of a holding. An E0 reservation counts the usage rows of every organization of its holding whose trust level is E0 when the count runs. Each usage row stays attributed to the organization that consumed it, and usage of an organization that is no longer E0 leaves the shared pool. An organization at E1 or above counts only its own usage and keeps its own pool, so its usage does not count toward the E0 pool.
|
||||
|
||||
Idempotency stays per organization. The same invitation ID, or a repeated view of one candidate by the same organization inside the window, is not charged twice. The same candidate viewed by two organizations of one holding is two charges of the shared pool.
|
||||
|
||||
Locks: for an E0 organization, `CompanyQuotaRepository.LockOrganization` and each reservation take the holding row with `FOR NO KEY UPDATE` right after the organization row. Reservations of one pool therefore run one after another, and the second one counts the usage that the first one committed, because it counts only after the holding lock. Every writer takes the organization lock before the holding lock, and no code takes an organization lock while it holds a holding lock, so the holding lock adds no cycle to the documented order. The cost is that E0 searches, card reads, and invitation drafts or sends of one holding wait for one another while their transactions are open; a search holds the lock for its whole ranking transaction.
|
||||
|
||||
The migration gives each founder one holding: the founder of an organization is the account of its earliest membership, which is the creator's owner membership, and the holding is dated by its first organization. The rollback refuses while a holding groups several organizations, because the schema without holdings could not keep their E0 pool together. Merging holdings of different owners is out of scope.
|
||||
|
||||
## Verification
|
||||
|
||||
`TestHoldings` in `backend/integration_test/holding_test.go` covers the shared E0 pool of two organizations of one account with a verified organization apart, a second account's own holding, usage leaving the pool when its organization is raised, concurrent reservations from two organizations that never exceed the shared limits, concurrent creations ending in one holding, and a refused creation of an unknown founder. `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` in `backend/integration_test/holding_migration_test.go` covers the backfill and the guarded rollback.
|
||||
|
||||
`TestCompanyQuota` in `backend/integration_test/company_quota_test.go` exercises the real PostgreSQL adapter in an isolated database. It checks concurrent E0 reservations, E0/E1 boundaries, exact window cutoffs and `RetryAt`, same-ID invitation reuse, cross-request card-view reuse, monotonic refresh, rollback, policy or organization snapshot changes, an allowed reservation with an active E2 policy and stored E2 verification, rejection of a forged E2 snapshot for a stored E0 company, inactive E2 and E3 denial, and candidate-deletion cleanup. It does not test a delivered invitation because that workflow is not implemented.
|
||||
-1047
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,276 @@
|
||||
# Running and deploying
|
||||
|
||||
Run commands from the repository root. Install Docker with Compose, GNU make, Python 3, and OpenSSL. Go operator commands need the toolchain from `backend/go.mod`; they read exported environment variables rather than loading `.env` automatically. Settings are described in [.env.example](../../.env.example); defaults and container environment bindings are in [deploy/Makefile](../../deploy/Makefile) and [Compose](../../deploy/docker/).
|
||||
|
||||
## Running the MVP: quick start
|
||||
|
||||
If `.env` does not exist, copy `.env.example`, replace `replace-this-*`, and set `IDENTITY_KEY_SECRET` to a random secret (`openssl rand -base64 48`). The PostgreSQL password is part of the connection URL, so use URL-safe characters such as hex. This file contains secrets and must stay out of Git.
|
||||
|
||||
```sh
|
||||
make -C deploy config
|
||||
make -C deploy up
|
||||
curl --fail http://localhost:8080/api/v1/healthz
|
||||
```
|
||||
|
||||
`config` validates example settings; `up` reads the real `.env`. The `app` project starts frontend Nginx, the Go backend, PostgreSQL, Redis, SeaweedFS, and Kafka. The backend applies migrations on startup. An empty database has no question bank or prepared accounts; use the [demo stand](#isolated-demo-stand) to demonstrate the product.
|
||||
|
||||
| Component | Start | Default address |
|
||||
| --- | --- | --- |
|
||||
| Core | `make -C deploy up` | `http://localhost:8080` |
|
||||
| Synthetic demonstration | `make -C deploy demo-seed DEMO_MODE=isolated` | `http://localhost:8090` |
|
||||
| ML, after core | `make -C deploy ml-up` | `127.0.0.1:8000` |
|
||||
| Monitoring, after core | `make -C deploy monitoring-up` | Grafana: `127.0.0.1:3000` |
|
||||
| Development code runner | `make -C deploy runner-dev-up` | `127.0.0.1:8070` |
|
||||
|
||||
ML, monitoring, the runner, and labd do not start with core. Pass the same project name to every command, for example `APP_PROJECT=my-app` for `up`, `logs`, and `down`. Make does not read the project name from `.env`.
|
||||
|
||||
## Core service
|
||||
|
||||
`make -C deploy logs` follows logs. `make -C deploy down` preserves named volumes; stop monitoring before core. PostgreSQL, SeaweedFS, and Kafka persist data in volumes; Redis is a bounded cache without persistence. Removing volumes destroys their data. A single Compose host provides neither HA nor off-host backups.
|
||||
|
||||
### Public perimeter and client address
|
||||
|
||||
Frontend Nginx is the HTTP entry point, serving the SPA and `/api/v1/` on one origin. Open exactly `APP_PUBLIC_URL`; unsafe requests check Origin and, for sessions, a CSRF token. Use `localhost` for local HTTP and HTTPS for a public hostname: the session cookie has the `Secure` flag.
|
||||
|
||||
Keep `APP_HTTP_BIND=127.0.0.1` locally or use a private tunnel address. Do not publish the backend, `/metrics`, databases, broker, or storage. Docker port publishing can bypass ufw rules. `TRUSTED_PROXY_CIDRS` must trust only frontend Nginx; coordinate proxy addresses and ACLs when changing `APP_SUBNET` or `APP_FRONTEND_IP`.
|
||||
|
||||
### Outbox relay
|
||||
|
||||
The backend publishes outbox records to Kafka and runs event consumers and scheduled jobs in the same process. `RELAY_*`, `CONSUMER_*`, and `JOBS_*` settings live in [backend/config](../../backend/config/). Adding a variable to `.env` affects a container only if Compose explicitly passes it. Keep a margin in `stop_grace_period` when increasing shutdown timeouts.
|
||||
|
||||
### Event consumers
|
||||
|
||||
Watch outbox age, consumer errors, and due jobs in Grafana. Inspect dead letters in the database and Kafka lag through the broker CLI. Delivery permits retries; handlers deduplicate events. Changing `CONSUMER_GROUP_PREFIX` creates new groups that read retained events from the beginning.
|
||||
|
||||
#### Dead letters and replay
|
||||
|
||||
After fixing the cause, inspect the record in `consumer_dead_letters`. For a known `event_id`, republish its retained outbox row by clearing only that row's `published_at`; successful handlers recognize the duplicate. This does not repair an `invalid_record`. Stop all members of the affected group before manually resetting Kafka offsets. `consumer_processed_events` records successful processing; do not copy payloads or personal data into incident logs.
|
||||
|
||||
### Scheduled jobs
|
||||
|
||||
`scheduled_jobs` stores state and errors. After fixing the cause, retry only the affected job according to its handler; do not reset the entire queue. Synchronize backend clocks through NTP because deadlines and leases use application time. Practice uses a separate queue described below.
|
||||
|
||||
## Mail
|
||||
|
||||
| Mode | Requirements |
|
||||
| --- | --- |
|
||||
| `EMAIL_PROVIDER=disabled` | Sends nothing; a newly registered account remains unverified |
|
||||
| `EMAIL_PROVIDER=resend` | `RESEND_API_KEY`, `EMAIL_FROM` on a verified domain, and the correct `APP_PUBLIC_URL` |
|
||||
| `EMAIL_PROVIDER=smtp` | Configuration exists, but the transport is not implemented; backend startup fails |
|
||||
|
||||
### Mail deliveries
|
||||
|
||||
Resend sends email confirmation and supported product notifications through the outbox. A transport failure is not a successful delivery. `make -C deploy test-e2e-registration` uses a local Resend-compatible inbox, not a real provider account.
|
||||
|
||||
### Mail quotas
|
||||
|
||||
`EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` limit recipients by UTC periods, defaulting to 100 and 3000. `EMAIL_SERVICE_RESERVE_*` reserve part of those limits for service mail. `EMAIL_ACCOUNT` identifies the actual provider account; do not rename it to bypass local accounting. Application defaults do not guarantee a provider plan or quota.
|
||||
|
||||
### Mail templates
|
||||
|
||||
Templates and rendering live in `backend/internal/usecase/notification/mailtemplate/`. Send only data the recipient needs; the one-time link and code belong in verification mail. Service keys and data the recipient may no longer access must not be included.
|
||||
|
||||
## Isolated demo stand
|
||||
|
||||
```sh
|
||||
make -C deploy demo-seed DEMO_MODE=isolated
|
||||
make -C deploy monitoring-up DEMO_MODE=isolated
|
||||
make -C deploy demo-down DEMO_MODE=isolated
|
||||
```
|
||||
|
||||
The seed creates a separate `lincodex-demo` project, bank, and synthetic accounts; repeated runs are idempotent. The local frontend is available at `http://localhost:8090`; you do not need to pass `APP_HTTP_BIND` on the command line. The target uses the root `.env` and `deploy/demo/demo.env`, falling back to the public example if the latter is absent. The command prints logins; `DEMO_ACCOUNT_PASSWORD` sets their password. For external access, choose your own password and share it separately with participants.
|
||||
|
||||
The guide is at `/demo`. Main accounts: `candidate@demo.lincodex.test`, `prepared-1@demo.lincodex.test` through `prepared-6@demo.lincodex.test`, `employer-alpha@demo.lincodex.test`, and `employer-beta@demo.lincodex.test`. Follow the candidate from assessment to result, then send an invitation as the employer and accept it as the candidate with selected contacts.
|
||||
|
||||
`demo-reset DEMO_MODE=isolated` deletes and reseeds only its project; it refuses to run when ordinary accounts exist. Do not use this stand for real people. Demo categories are uncalibrated, and the express run awards no grade. The official FSP integration is not connected.
|
||||
|
||||
### Demonstration scenario
|
||||
|
||||
1. Complete the candidate profile and questionnaire, take a test or open a prepared result. The Backend Junior bank with Go is synthetic; `demo_express` assigns neither a grade nor evidence.
|
||||
2. Grant C2 and publish the card after previewing it. Anonymous results need a sufficiently large group: one published candidate may not appear in search.
|
||||
3. As the company owner, create a hiring need with a salary range, find a candidate, open the explanation and send an invitation.
|
||||
4. Accept it as the candidate with C4 and selected contacts. Check that the company can read only those fields, then revoke access or hide the company and verify refusal.
|
||||
|
||||
The `synthetic_demo` category demonstrates mechanics, not established assessment quality. Built-in consent texts are marked `demo`. Practice requires a separate runner and a suitable bank, so do not present it as part of the ordinary demonstration test. See [ARCHITECTURE.md](ARCHITECTURE.md) for other implementation limits and [TESTING.md](TESTING.md) for acceptance.
|
||||
|
||||
The presentation slot is 10 minutes; video is allowed instead of a live demonstration. Rehearse with a timer and state limitations. Keep the stand available throughout evaluation where possible; exact dates and whether jury questions count within the ten minutes need confirmation.
|
||||
|
||||
### Demonstration categories on a stand
|
||||
|
||||
The seed prepares categories itself. Manual setup requires an open category with a published bank, a demo policy, `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`, and operator attestation:
|
||||
|
||||
```sh
|
||||
make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:maintainer'
|
||||
```
|
||||
|
||||
The command requires `DATABASE_URL`. Attestation binds the category opening, bank, and policy version; reopen and attest after changing them. Synthetic categories remain disabled in environments with real candidates.
|
||||
|
||||
### Match search policy on a stand
|
||||
|
||||
The initial policy on an empty stand has no `matching` section. Publish it before demonstrating search:
|
||||
|
||||
```sh
|
||||
make -C backend policy-publish ARGS='matching --actor operator:maintainer'
|
||||
```
|
||||
|
||||
The command requires `DATABASE_URL` and publishes the next demo version. The seed handles this preparation itself. A policy change requires reopening and attesting demo categories; attempts already started keep their previous version.
|
||||
|
||||
### Assessment review band
|
||||
|
||||
```sh
|
||||
make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operator:maintainer'
|
||||
```
|
||||
|
||||
The command requires `DATABASE_URL` and shows signals for manual review. They do not prove misconduct or automatically lower a score. The `operator:*` label is for auditing; database access remains the operator's access boundary.
|
||||
|
||||
### Leak trace
|
||||
|
||||
```sh
|
||||
make -C backend assessment-leak-trace ARGS='search --actor operator:maintainer --file leaked.txt'
|
||||
```
|
||||
|
||||
Set `DATABASE_URL` and the same `IDENTITY_KEY_SECRET` used when issuing attempts. Pass text in a file or through `--stdin` to keep it out of shell history. Results and audit records omit the original text; a match supports manual review rather than an automatic decision.
|
||||
|
||||
## Separate ML Compose project
|
||||
|
||||
ML serves Giga-Embeddings-instruct-480M and Qwen3-Embedding-0.6B embeddings. Its image downloads pinned weights at build time, verifies SHA-256, and runs offline. Compose uses CPU with a limit of 4 CPUs and 8 GiB. The separate project joins the external core network as `ml`.
|
||||
|
||||
1. Set the same `ML_SERVICE_TOKEN` for ML and backend in `.env`: at least 32 printable characters without spaces.
|
||||
2. Start core, then run `make -C deploy ml-build` and `make -C deploy ml-up`.
|
||||
3. Wait for `/readyz` 200. `/healthz` checks the process, not model loading.
|
||||
|
||||
`ML_EMBEDDER=giga,qwen3` loads both models; `none` keeps the service unready, and `fake` is for fixtures. All routes except health/readiness require the configured bearer token. Without a token, the service permits only loopback clients and refuses to start the container listener on `0.0.0.0`. `ml-logs` and `ml-down` manage this project separately.
|
||||
|
||||
For development, run `make -C ml install`, `make -C ml model-fetch`, then `make -C ml run` with `ML_EMBEDDER` and model directories in the environment. `model-fetch` downloads about 2.2 GB of weights. `make -C ml test-model` tests real models separately from ordinary tests.
|
||||
|
||||
### ML service on a GPU host
|
||||
|
||||
Use the [systemd template](../../deploy/ml-gpu/lincodex-ml.service) and [example settings](../../deploy/ml-gpu/ml.env.example). The service expects code at `~/lincodex-ml/app/ml`, a virtualenv at `~/lincodex-ml/venv`, and settings in `~/.config/lincodex-ml/ml.env` with mode 0600. Use the Python version from `ml/.python-version`; `make -C ml cuda-requirements` prepares pinned dependencies with a CUDA torch build, which must be installed from the matching PyTorch index.
|
||||
|
||||
Prepare weights from the lock files; select a private address, `ML_DEVICE=cuda`, dtype, and `ML_CUDA_MEMORY_LIMIT_MB` for the host's resources. After installing the unit and configuring lingering, run `systemctl --user daemon-reload`, then `systemctl --user enable --now lincodex-ml.service`. Check `/readyz`, logs, and real model tests on the target device. Memory and latency measurements from another host are not guarantees for yours.
|
||||
|
||||
Restrict access to the backend address. The service does not terminate TLS; use a protected channel across an untrusted network. CUDA memory exhaustion returns 503 and retries loading; other persistent loading failures exit with `ML_EXIT_ON_LOAD_FAILURE=true` so the supervisor can restart the process.
|
||||
|
||||
### Semantic matching
|
||||
|
||||
Search reads precomputed vectors and does not invoke a model within the HTTP request.
|
||||
|
||||
1. Wait for ML readiness, set `SEMANTIC_MATCHING_ENABLED=true`, the shared token, and `ML_SERVICE_URL` (default `http://ml:8000`), then rerun `make -C deploy up`.
|
||||
2. With the stand's `DATABASE_URL`, run `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:maintainer'`. This policy needs both models; `semantic` uses Giga alone.
|
||||
3. Queue existing data: `make -C backend semantic-backfill ARGS='all --run initial'`. Repeating the same run label is idempotent; use a new label for another pass.
|
||||
|
||||
Reopen and attest demo categories after publishing a policy. Missing or incompatible vectors use neutral `Sem=0.5` with `ml_unavailable`. GitHub repository checks are enabled separately through `GITHUB_REPOSITORY_CHECKS_ENABLED`; they are not a requirement for ML startup.
|
||||
|
||||
## Separate monitoring Compose project
|
||||
|
||||
```sh
|
||||
make -C observability check
|
||||
make -C deploy monitoring-up
|
||||
make -C deploy monitoring-logs
|
||||
make -C deploy monitoring-down
|
||||
```
|
||||
|
||||
By default, the project joins the core network. After starting the demo, run `make -C deploy monitoring-up DEMO_MODE=isolated` to connect it to the `lincodex-demo` network. Grafana is bound to loopback; Prometheus, Loki, Alloy, and exporters remain internal. Dashboards cover Go, PostgreSQL, Redis, SeaweedFS, the host, and product metrics. Kafka has no dedicated scrape yet. The React telemetry SDK is not connected. Alert rules exist; notification delivery needs separate configuration.
|
||||
|
||||
Prometheus retains metrics for 14 days with a 4 GB cap; Loki retains logs for 7 days. Keep contacts, resumes, raw URLs, and user identifiers out of labels. Alloy accesses the Docker API through a restricted socket proxy; even read-only Docker API access can expose sensitive container configuration. Treat this component as privileged.
|
||||
|
||||
The PostgreSQL exporter role is created only on first initialization of an empty volume: set `POSTGRES_EXPORTER_USER` and `POSTGRES_EXPORTER_PASSWORD` beforehand. Provision the role separately for an existing database. `ML_METRICS_TARGET` adds a private target, but the current scrape template sends no bearer token; protected ML also requires Prometheus authorization configuration.
|
||||
|
||||
`make -C observability verify-product-metrics` starts disposable core and monitoring stacks, checks metrics and the absence of fixture personal data in telemetry, then removes them. This integration check is separate from `check`.
|
||||
|
||||
## Edge proxy, HTTPS and tunnel
|
||||
|
||||
Public requests follow browser -> edge HTTPS Nginx -> private AmneziaWG tunnel -> frontend Nginx -> Go. Templates and scripts live in [deploy/edge](../../deploy/edge/); core Compose does not terminate TLS.
|
||||
|
||||
1. Prepare `deploy/edge/edge.env` from the example: domain, dedicated `EDGE_LISTEN_IP`, tunnel addresses, and port. Check DNS, free listeners, and subnet overlap. Preserve existing sites and routes on a shared edge host.
|
||||
2. `make -C deploy edge-config` checks templates and runs containerized `nginx -t`; `edge-render` writes Nginx configuration into `deploy/edge/rendered/`. These targets install nothing on the host.
|
||||
3. On edge, install the HTTP configuration for ACME, obtain a certificate with certbot, then install the HTTPS configuration and [reload-nginx.sh](../../deploy/edge/certbot/reload-nginx.sh) hook. Run `nginx -t` before reload and test renewal with `certbot renew --dry-run`.
|
||||
4. Create tunnel keys through `deploy/edge/scripts/awg-keys.sh` and render each side through `render.sh --params`. Keep key files outside the repository, accessible only to root. Prepare AmneziaWG and the required systemd drop-ins on both hosts.
|
||||
5. On app, set `APP_HTTP_BIND` to its tunnel address and `APP_PUBLIC_URL=https://<domain>`. The firewall permits the core port only from edge; frontend trusts forwarded headers only from the edge address. Check both sides; Docker publishing does not replace a firewall.
|
||||
|
||||
Before opening access, check HTTPS and the certificate chain, HTTP redirects, SPA deep links, sign-in and CSRF, and denial of `/metrics` and administrative paths. Edge replaces forwarded headers instead of trusting client values. Run `make -C deploy check-perimeter` and `make -C deploy perimeter-test`; the latter starts disposable Nginx containers.
|
||||
|
||||
Keep previous configuration and certificates for rollback and validate them before reload. Do not remove unrelated interfaces, firewall rules, or sites. A successful template check does not prove public domain availability.
|
||||
|
||||
## Isolated runner and lab host (LXD)
|
||||
|
||||
LXD needs Linux with KVM, space for the btrfs pool, and operator privileges. Review [acls.sh](../../deploy/labs/acls.sh) and [lxd-preseed.yaml](../../deploy/labs/lxd-preseed.yaml) against the host's network, then apply ACLs before the preseed. The scripts create separate runner and lab-management bridges; guests use static addresses without NAT, DHCP, or DNS. Do not apply the layout over unrelated objects with the same names.
|
||||
|
||||
The backend never receives the LXD socket. The `lxd` group grants root-equivalent access; only the operator and labd receive it. Test guest isolation from core, the host, LAN, and the internet on the actual host; configuration alone does not prove it.
|
||||
|
||||
## Code runner
|
||||
|
||||
The `runner/` service executes Python and Go in nsjail with cgroup v2, seccomp, and limits. The supervisor needs isolation privileges; candidate code runs as an unprivileged user. Run history is in runner memory and is lost on restart.
|
||||
|
||||
### Local development only
|
||||
|
||||
`make -C deploy runner-dev-up` creates a token at `runner/.dev/api-token` and starts a separate privileged container with loopback HTTP. Stop it with `runner-dev-down`. This mode is forbidden on the core host and is excluded from release. The backend requires TLS and cannot connect directly to this HTTP mode.
|
||||
|
||||
### Production: the runner VM
|
||||
|
||||
Use a dedicated LXD VM with its own kernel and no core directory, Docker socket, application secrets, or default route. The network permits API connections only from the app network and host side, while denying guest-initiated connections. TLS 1.3 and a bearer token are required. nsjail needs delegated cgroup v2 and a work tmpfs with `exec,nosuid,nodev`.
|
||||
|
||||
### Steps of the VM script
|
||||
|
||||
On a prepared app host, as a member of the `docker` and `lxd` groups:
|
||||
|
||||
```sh
|
||||
make -C deploy runner-vm-up
|
||||
make -C runner a16-bundle
|
||||
make -C deploy runner-vm-a16 A16_BUNDLE=/path/to/a16-bundle.tar.gz
|
||||
make -C deploy runner-vm-check
|
||||
```
|
||||
|
||||
The A16 bundle can be built on a machine with Go and transferred to app. `runner-vm-up` prepares secrets, rootfs, VM, and service in sequence. Separate targets are `runner-vm-secrets`, `runner-vm-rootfs`, `runner-vm-create`, and `runner-vm-install`. Secrets and reports stay in `RUNNER_VM_STATE_DIR`, defaulting to `~/lincodex-runner`, outside the repository.
|
||||
|
||||
### Verification on the app host
|
||||
|
||||
Before enabling practice, pass A16 on the target VM and `runner-vm-check`: TLS, token, harmless programs, limits, cleanup, and network denial. A failure blocks practice activation. Repeat checks after changes to the kernel, runtime, or isolation settings. A passing run on an older release does not replace them.
|
||||
|
||||
### Code runner client
|
||||
|
||||
Set backend `CODE_RUNNER_URL` to HTTPS, `CODE_RUNNER_TOKEN`, a distinct `CODE_RUNNER_RUN_KEY`, and exactly one of `CODE_RUNNER_CA_FILE`/`CODE_RUNNER_CA_PEM`. Mount the CA file into the container yourself. Set `CODE_RUNNER_SERVER_NAME` if required; certificate verification stays enabled. `CODE_RUNNER_REQUEST_TIMEOUT` bounds each request.
|
||||
|
||||
Without a URL, all other `CODE_RUNNER_*` settings must be empty; practice reports unavailable. Invalid configuration prevents startup. `make -C backend test-code-runner-live` tests the client against a prepared TLS runner with `CODE_RUNNER_URL`, `CODE_RUNNER_TOKEN`, and `CODE_RUNNER_CA_FILE` from the environment; it does not replace A16.
|
||||
|
||||
### Practice queue and debug run limits
|
||||
|
||||
The backend already connects the practice handler and PostgreSQL queue when `DATABASE_URL` and a runner are configured. The queue allows one running and ten waiting jobs; Redis limits candidate debug requests. `PRACTICE_*` settings live in `backend/config/` but are not passed by ordinary Compose. Infrastructure failure ends without grading, not as a wrong answer; inspect the queue through `assessment_practice_jobs`.
|
||||
|
||||
## Labs and labd
|
||||
|
||||
labd runs as a systemd service on the app host and exclusively manages LXD. Use its [unit](../../deploy/labs/lincodex-labd.service) and [settings](../../deploy/labs/labd.env.example): TLS, token, allowed networks, state file, and memory budget. Preserve its state file with the LXD objects; it is needed to recover and delete labs.
|
||||
|
||||
The built-in template registry is currently empty, backend does not connect the labd adapter, and the WebSocket console returns 501. A usable workflow requires prepared images, templates, and integration. Before enabling it, verify L2 isolation, MAC/port filtering, cloud-init, and node authentication during checks. `make -C labd test-live` creates and deletes a lab on a separate test LXD with `LABD_LIVE_SOCKET` and `LABD_LIVE_SOURCE`; never run it against production.
|
||||
|
||||
## Release manifest
|
||||
|
||||
A reproducible release needs a clean working tree and passing checks of those exact images:
|
||||
|
||||
```sh
|
||||
make -C deploy release-build
|
||||
make -C deploy release-smoke
|
||||
make -C deploy release-e2e
|
||||
make -C deploy release-manifest RELEASE_ID=demo-stage-1
|
||||
make -C deploy release-manifest-check RELEASE_ID=demo-stage-1
|
||||
make -C deploy release-up RELEASE_ID=demo-stage-1
|
||||
make -C deploy release-manifest-verify RELEASE_ID=demo-stage-1
|
||||
```
|
||||
|
||||
The manifest in `deploy/release/<id>/` records source, dependencies, Compose, image IDs/digests, and inputs. Each ID is immutable; a new delivery needs a new ID. These are local artifacts and stay out of Git. `RELEASE_DATA_MANIFEST` adds bank, policy, and seed versions; the absence of an accepted bank remains an explicit limitation rather than proof of product readiness.
|
||||
|
||||
`release-up` requires local images and matching files; it neither builds nor pulls them. For another project, use matching `APP_PROJECT` and `RELEASE_VERIFY_PROJECT`. Restore the demo with `demo-seed DEMO_MODE=isolated RELEASE_ID=<id>`; stop core with `release-down` using the same ID. `release-clean` removes only image references not retained by manifests.
|
||||
|
||||
The manifest does not back up data or deploy edge, the GPU host, runner, or labd. Back up data and configuration before upgrades; rolling back an image does not undo migrations. Test recovery of PostgreSQL and SeaweedFS objects separately.
|
||||
|
||||
## Checks
|
||||
|
||||
| Command | Coverage |
|
||||
| --- | --- |
|
||||
| `make -C deploy check` | Compose and tooling checks without starting the stack |
|
||||
| `make -C deploy smoke` | Dependency health and network boundaries of a disposable stack |
|
||||
| `make -C frontend install`, then `make -C deploy test-e2e` | Browser scenarios on a disposable stack |
|
||||
| `make -C deploy test-e2e-registration` | Scenarios with a local mail fixture |
|
||||
| `make -C observability check` | Monitoring configuration and alert rules |
|
||||
|
||||
Test coverage and environment requirements are in [TESTING.md](TESTING.md). A passing health check does not confirm the complete business flow.
|
||||
+89
-229
@@ -1,251 +1,111 @@
|
||||
# Development
|
||||
|
||||
This guide describes implemented components and repository commands. Current business workflows are listed below; see [ARCHITECTURE.md](ARCHITECTURE.md) for the target design.
|
||||
[Русский](../ru/DEVELOPMENT.md)
|
||||
|
||||
## Stack and version sources
|
||||
Run commands below from the repository root. [ARCHITECTURE.md](ARCHITECTURE.md) explains the services, [DEPLOYMENT.md](DEPLOYMENT.md) covers the environment, and [TESTING.md](TESTING.md) covers checks.
|
||||
|
||||
| Component | Version source |
|
||||
## Tools
|
||||
|
||||
Use the versions declared by the build inputs:
|
||||
|
||||
| Tool | Source |
|
||||
| --- | --- |
|
||||
| Go | exact 1.26.9 in backend/go.mod, toolchain, and Go build image |
|
||||
| Node.js | frontend/.node-version |
|
||||
| Frontend dependencies | current stable releases in package manifests and pnpm-lock.yaml |
|
||||
| Python and uv | ML toolchain declarations and uv.lock |
|
||||
| Go | `backend/go.mod`, `runner/go.mod`, `labd/go.mod`, and their Dockerfiles |
|
||||
| Node.js | `frontend/.node-version` |
|
||||
| pnpm and frontend | `frontend/package.json`, `frontend/pnpm-lock.yaml` |
|
||||
| Python and uv | `ml/.python-version`, `ml/pyproject.toml`, `ml/uv.lock` |
|
||||
| Go generators | `tool` directives and dependencies in Go modules |
|
||||
| Containers | `deploy/docker/` and service Dockerfiles |
|
||||
|
||||
Select current stable frontend dependency releases and keep pnpm-lock.yaml committed for repeatable installs. ML dependencies are locked in uv.lock; Go dependencies are in backend/go.mod. An update must change its lock/configuration and pass checks for that service. Container images use the requested moving `latest` or `alpine` tags; inspect their current Compose/Dockerfile references instead of treating the tag as a fixed version.
|
||||
Container checks require Docker with the Compose plugin. The race detector needs a supported C toolchain. Keep lockfiles and test consumers when updating dependencies. Moving `latest` and `alpine` tags can change image content; a reproducible release pins digests.
|
||||
|
||||
## Implementation status
|
||||
```sh
|
||||
make install
|
||||
make help
|
||||
```
|
||||
|
||||
MVP implementation is ongoing. Values below are read from the named files; when updating a dependency, change its source and lockfile and update this table in both languages.
|
||||
`install` installs API, frontend, and ML dependencies and downloads backend, runner, and labd Go modules. It does not start services or install Docker or system compilers.
|
||||
|
||||
| Component | Pinned version | Source |
|
||||
| --- | --- | --- |
|
||||
| Go | 1.26.9 (`go` directive; no separate `toolchain` line) | backend/go.mod; build image `golang:1.26.9-alpine` in backend/Dockerfile |
|
||||
| Node.js | 26.11.1 | frontend/.node-version |
|
||||
| pnpm | 12.9.1 | `packageManager` in frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| React, React DOM | 19.3.0 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| React Router (`react-router-dom`) | 7.18.4 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| TanStack Query (`@tanstack/react-query`) | 5.104.1 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Zod | 4.6.5 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Vite | 8.3.2 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| TypeScript | 7.0.2 (`@typescript/native`, `tsc`); 6.0.2 API (`typescript` alias of `@typescript/typescript6`) for ESLint | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Vitest | 5.0.3 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Orval | 8.40.0 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Python | 3.14.8 (`requires-python >=3.14,<3.15`) | ml/.python-version, ml/pyproject.toml |
|
||||
| uv | 0.12.22 | `[tool.uv] required-version` in ml/pyproject.toml; `setup-uv` in .github/workflows/ci.yml |
|
||||
| FastAPI | 0.142.2 | ml/pyproject.toml, ml/uv.lock |
|
||||
| Pydantic | 2.13.5 | ml/pyproject.toml, ml/uv.lock |
|
||||
| uvicorn | 0.54.0 | ml/pyproject.toml, ml/uv.lock |
|
||||
| ogen | v1.24.0 | backend/go.mod (`require` and `tool`) |
|
||||
| sqlc | v1.31.1 | backend/go.mod (`tool`) |
|
||||
| wire (`github.com/goforj/wire`) | v1.2.0 | backend/go.mod (`require` and `tool`) |
|
||||
| mockery | v3.8.0 | backend/go.mod (`tool`) |
|
||||
| golangci-lint | v2.14.0 | backend/go.mod (`tool`) |
|
||||
| goose | v3.28.0 | backend/go.mod (`require` and `tool`) |
|
||||
| chi | v5.3.2 | backend/go.mod |
|
||||
| pgx | v5.11.0 | backend/go.mod |
|
||||
| testcontainers-go | v0.44.0, including modules/postgres | backend/go.mod |
|
||||
| franz-go (`kgo`, `kadm`) | v1.22.1, kadm v1.19.0; outbox relay producer, event consumer group members, and integration tests | backend/go.mod |
|
||||
## Normal workflow
|
||||
|
||||
What exists now:
|
||||
1. Locate the source of the change: contract, usecase, SQL, UI, or configuration.
|
||||
2. Change source files and add a check for observable behavior.
|
||||
3. Run `make generate` if generator inputs changed.
|
||||
4. Check the affected area; use `make check` for the combined checks.
|
||||
5. Review the diff, update both documentation languages, and run `make docs-check`.
|
||||
|
||||
- Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail.
|
||||
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and `identity.Credentials` are wired for registration and email confirmation. A generated Go client for the ML contract exists but is not wired into bootstrap.
|
||||
- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Product notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but notification sending is not implemented. With `resend`, the backend runs a worker for identity service mail: registration and resend queue verification messages bound to their tokens; the worker checks the token and account before sending and uses a quota gate and stable idempotency key. Password reset is not implemented yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries).
|
||||
- OpenAPI contracts api/core/, api/ml/, and api/runner/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA uses the generated API client; MSW handlers provide test data. Implemented forms are listed below, while remaining routes still show placeholders.
|
||||
- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`).
|
||||
- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs two product handlers, the mail delivery consumer and the inbox consumer, and no product flow emits their events yet; see [Event consumers](#event-consumers).
|
||||
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite.
|
||||
- Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet.
|
||||
|
||||
The API and SPA implement registration, email confirmation, sign-in, consents, the private candidate profile and questionnaire, company profiles, needs, and account-owned support cases. The API also creates and resumes assessment attempts; answer submission and result calculation are not connected yet. Matching, invitations, contact disclosure, and product notification delivery remain in development. The worker sends identity service mail through Resend; SMTP is not implemented. Each workflow's boundaries are described in the [backend README](../../backend/README.en.md) and [frontend README](../../frontend/README.en.md).
|
||||
|
||||
`make -C deploy test-e2e` checks the technical shell on a disposable stack. `make -C deploy test-e2e-registration` also exercises business workflows with an isolated local mail receiver and synthetic data; it does not prove real Resend delivery. See [TESTING.md](TESTING.md#browser-e2e-suite).
|
||||
|
||||
## Install and work loop
|
||||
|
||||
The frontend uses TypeScript 7.0.2 (`tsc`) for type checking. The `@typescript/native` npm alias points to that compiler, while `typescript` points to the compatible `@typescript/typescript6` API for ESLint. This follows [Microsoft's side-by-side setup](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0): current typescript-eslint does not support the TS7 API yet. Type checking covers source files, Vite configuration, and the TypeScript files in `codegen/`.
|
||||
|
||||
Orval writes directly to `frontend/src/shared/api/endpoints/` and `schemas/`, without an extra `generated/` directory. The adjacent `client.ts` and root `shared/api/index.ts` are handwritten. A Node test exercises the generated MSW handler together with the generated client. After Orval, the `frontend/codegen/mock-patterns.ts` step replaces `faker.helpers.fromRegExp` in the MSW mocks with `fakeFromPattern` and the length bounds from the contract, and `mock-validity.test.ts` checks every response mock with its Zod schema; see [frontend/README.en.md](../../frontend/README.en.md#api-client-generation). Vitest still reports a peer warning expecting MSW 2; the current Node path is tested with MSW 3, and browser mode is not used.
|
||||
|
||||
Ignore rules belong to each component's `.gitignore`; root rules cover only root files. CI installs pnpm from frontend/package.json's `packageManager` declaration and does not require bundled Corepack. To check ML locally with a different global uv version, pass `UV='uv tool run --from uv==0.12.22 uv'` to Make.
|
||||
|
||||
Run make help at the repository root for the current target list. Main targets:
|
||||
|
||||
- make install installs dependencies for api, frontend, ML, and backend.
|
||||
- make generate bundles both OpenAPI contracts and updates generated Go/TypeScript/Python output.
|
||||
- make fmt and make fmt-check format or check formatting.
|
||||
- make lint runs configured linters.
|
||||
- make test runs backend, frontend, and ML unit/component/service tests.
|
||||
- make check checks api, backend, frontend, ML, deploy, observability, and documentation.
|
||||
- make verify runs generation, drift checks, root check, API/backend validation, and a technical Compose smoke.
|
||||
- make docs-check validates RU/EN docs, local links, routes, and imports.
|
||||
|
||||
Use each area's Makefile for its focused loop, for example make -C backend help, make -C frontend help, make -C ml help, make -C api help, make -C deploy help, and make -C observability help.
|
||||
|
||||
make check is not a business end-to-end suite. make verify runs a deployment smoke with Docker and a backend integration target. See [TESTING.md](TESTING.md) for validation scope and [DEPLOY.md](DEPLOY.md) for the local stack.
|
||||
|
||||
Security tools have a separate install and work loop: `make -C security install`, then `make -C security check`. Use `make -C security test` after changing local rules or scanner integration and `make -C security images` to build and scan service images. These checks are separate from the ordinary root `make check`; see [SECURITY.md](SECURITY.md) for prerequisites, policies, and reports.
|
||||
|
||||
### Sessions on local HTTP
|
||||
|
||||
The session cookie is `__Host-lincodex_session` with `Secure`, `HttpOnly`, and `SameSite=Strict` (see [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). The local stack serves plain HTTP. Chromium and Firefox treat `http://localhost` and `http://127.0.0.1` as secure contexts and keep a `Secure` cookie there; WebKit and Safari may reject it. Use Chromium or Firefox for local sign-in, or put a local TLS proxy in front. The project adds no flag that drops `Secure` or the `__Host-` prefix, so the local cookie never differs from production.
|
||||
|
||||
`ConfirmEmail` requires Origin to match `APP_PUBLIC_URL` exactly; a missing Origin, the literal value `null`, or any other value answers 403 `csrf_check_failed`. The same check applies to other unsafe identity operations and protected session requests; the latter also require the session-bound CSRF token. The server does not use Host to derive an allowed Origin.
|
||||
|
||||
## Layout
|
||||
|
||||
Each top-level directory except `.github/` has a short Russian `README.md` and an English `README.en.md`. A README and its translation are optional in `.github/`. Detailed guides live in `docs/ru/` and `docs/en/`; READMEs are not added below the first directory level. `make docs-check` validates language pairs and links and runs the checker's own tests.
|
||||
|
||||
| Directory | Purpose |
|
||||
| Command | Purpose |
|
||||
| --- | --- |
|
||||
| api/core/ | Public browser-to-Go OpenAPI contract |
|
||||
| api/ml/ | Internal Go-to-ML OpenAPI contract |
|
||||
| api/runner/ | Internal OpenAPI contract between Go and the code runner |
|
||||
| scripts/ | Shared schema merge, generated drift, and docs-check |
|
||||
| backend/ | Go HTTP service, adapters, bootstrap, SQL, and consumer codegen |
|
||||
| backend/config/ | Shared Go configuration outside internal |
|
||||
| frontend/ | Vite SPA, Orval configuration, generated TypeScript |
|
||||
| ml/ | Python service, lockfile, and Pydantic model generator |
|
||||
| runner/ | Go code runner service: nsjail, cgroup v2, judge, ogen server, and isolation tests |
|
||||
| deploy/ | Compose, Nginx, and smoke script |
|
||||
| observability/ | Prometheus, Loki, Alloy, provisioning, and dashboard JSON |
|
||||
| security/ | Scanner configuration, installation, Make targets, and local reports |
|
||||
| .agents/ | Canonical project instructions and working standards |
|
||||
| docs/ru/, docs/en/ | User documentation in Russian and English |
|
||||
| `make fmt` | Reformat source files |
|
||||
| `make fmt-check` | Check formatting without edits |
|
||||
| `make test` | Service unit and component tests |
|
||||
| `make check` | Code, documentation, and configuration checks |
|
||||
| `make verify` | Generation, drift, checks, race, integration tests, and smoke |
|
||||
|
||||
Codegen directories belong to the services that use the generated code: backend/codegen/, frontend/codegen/, and ml/codegen/. The Go client for the internal ML API is generated from backend/codegen/ogen-ml.yml and consumed at backend/internal/adapter/secondary/ml/api/. The Go client for the code runner is generated from backend/codegen/ogen-code-runner.yml into backend/internal/adapter/secondary/code_runner/api/. The public Go handler is generated from backend/codegen/ogen.yml and mounted in chi. sqlc configuration is backend/codegen/sqlc.yml, with generated SQL under backend/internal/adapter/secondary/postgres/sqlc/. Orval reads the public bundle from frontend/codegen/orval.config.ts. backend/cmd/app/main.go calls bootstrap.Run() and handles its error; startup, dependency wiring, and lifecycle logic live in backend/internal/bootstrap/app.go.
|
||||
`verify` requires Docker. It does not include Playwright, security scanners, or real-model checks; select those separately for the change.
|
||||
|
||||
## Local environment
|
||||
|
||||
Use Compose for the complete application. `.env.example` describes its variables; keep secrets in the local `.env`, outside Git and command examples.
|
||||
|
||||
`make -C backend run` reads process environment variables, not `.env`. PostgreSQL, Redis, SeaweedFS, and Kafka addresses inside Compose may not be reachable by a host process. Do not disable required dependencies just to make startup succeed.
|
||||
|
||||
`make -C frontend dev` starts Vite and proxies `/api` to `127.0.0.1:8080`. Authentication validates the public Origin, so `APP_PUBLIC_URL` must match the browser address. Use the application behind Nginx for the complete cookie flow.
|
||||
|
||||
Mail is disabled by default. Develop registration against the isolated mail E2E stand or configure Resend; the SMTP transport is not implemented. A separate demo stand provides prepared synthetic accounts.
|
||||
|
||||
## Contracts and generation
|
||||
|
||||
Source YAML stays beside its contract. Run make -C api bundle to merge schemas separately for api/core/, api/ml/, and api/runner/ and then bundle each input. The public and internal APIs remain separate contracts.
|
||||
Edit `routes/` and `components/` grouped by subject in `api/core/`, `api/ml/`, `api/runner/`, or `api/labd/`. [api/README.en.md](../../api/README.en.md) summarizes HTTP conventions.
|
||||
|
||||
Root make generate prepares both bundles once, then runs Go, TypeScript, and Python consumers. Merged schemas, bundles, and generated clients are tracked derived files; change their sources and regenerate them. After changing a contract, regenerate every consumer and check drift. A service-local Make target can generate one consumer when its inputs are ready and the shared contract owner has agreed.
|
||||
|
||||
The target is OpenAPI 3.2.0, with ogen for Go, Orval for TypeScript, and datamodel-code-generator for Python/Pydantic v2. Verify the actual feature subset used by the project through pinned tools and the runtime path. A version string does not prove full specification support.
|
||||
|
||||
datamodel-code-generator 0.83.0 reads api/ml/openapi.bundle.yml and writes ml/src/lincodex_ml/api/models.py. Settings live in ml/codegen/pyproject.toml; this file configures the tool, while dependencies remain in ml/pyproject.toml and uv.lock. Health/readiness handlers import the generated models instead of maintaining handwritten schema copies. make -C ml generate bundles the API first; when called by root make generate, API_PREPARED=1 reuses the prepared bundle. make -C ml check-generated compares output with --check without rewriting the file. CI uses the shared make generate target, which includes the Python models.
|
||||
|
||||
Errors, retries, versions, pagination, and time follow the [contract conventions](../../api/README.en.md#contract-conventions). Implemented: every error of the public Go API and of the ML service is an RFC 9457 problem (`application/problem+json`) with a stable `code`. The Go mapping of ogen errors lives in backend/internal/adapter/primary/http/problem/: request validation gives 400, unknown routes under /api 404, unimplemented operations 501, and other errors and panics 500 without internal text; errors are logged at that boundary, panics only by type and stack. The frontend API client throws `ApiRequestError` for problems, network failures (`network_error`), and invalid 2xx bodies (`invalid_response`); a caller's abort propagates unchanged. The ML service maps FastAPI errors in ml/src/lincodex_ml/api/problems.py and routes uvicorn logs through its JSON format without exception text. Idempotency-Key storage, If-Match checks, and pagination are planned: the contract defines their components, and the first business operation that needs them implements them.
|
||||
|
||||
## Code boundaries
|
||||
|
||||
SQL linter dependencies are listed in `backend/requirements-quality.txt` beside `.sqlfluff`. The `make -C backend lint-sql` command installs them in the local `.venv-quality` environment and checks migrations and queries. Running the Go service does not require this environment.
|
||||
|
||||
Go follows domain, usecase, port, adapter, and bootstrap boundaries. The HTTP adapter mounts the generated ogen handler in chi. SQL belongs in backend/db/queries/; schema changes belong in backend/db/migrations/. sqlc output and wire_gen.go are generated.
|
||||
|
||||
Shared backend settings live in backend/config/. The service uses go-logkit 0.6.0 through its slog bridge and go-httpkit 0.7.0 for request IDs and panic recovery. Request logging is the service's own `middleware.RequestLog`: the go-httpkit logger writes the raw path and every query value not on its fixed redaction list, so an address in a path or query would reach the logs. It retains custom Prometheus middleware because it bounds method labels and uses chi route patterns; go-httpkit/metrics accepts the raw method name as a label.
|
||||
|
||||
PostgreSQL uses pgxpool.NewWithConfig, and a generated SELECT 1 readiness query checks connectivity. Pool construction must not wait for the database during startup. go-pgkit 1.4.0 is not used because its constructor probes and retries before returning a pool, coupling service startup to database availability. Health handlers remain explicit: go-httpkit's helper returns ok/degraded with check details, while the shared contract uses ok/ready/not_ready. Do not add pgkit, httpkit/metrics, JWT or WebSocket without a concrete need and a check of the pinned version's behavior.
|
||||
|
||||
Redis connects through the outbound cache port and `backend/internal/adapter/secondary/redis/`. The adapter uses `go-cachekit` 0.7.0 for key/value operations over go-redis; library details stay behind this boundary. Bootstrap constructs the client without waiting for connectivity and closes it on shutdown; shared /readyz checks PostgreSQL, Redis, and SeaweedFS. Use Get/Set/Del with a positive TTL and distinguish a missing key from a Redis error. This is a technical adapter; product cache consumers have not been added. Connection settings are described in [DEPLOY.md](DEPLOY.md).
|
||||
|
||||
S3 storage connects through the outbound `ObjectStorage` port and `backend/internal/adapter/secondary/seaweedfs/`. SeaweedFS is a separate server; AWS SDK for Go v2 is the Go client inside the adapter. Put/Get stream content; Put requires a known byte length, and callers must close the body returned by Get. The Get timeout covers reading the response body. The adapter bounds operation time and distinguishes a missing object from a service error. The container initializes its bucket; Go checks it with HeadBucket instead of creating infrastructure while handling requests. Do not add direct Nginx delivery of private files or product upload/download endpoints without access rules.
|
||||
|
||||
The frontend is a React/Vite SPA. Keep FSD boundaries as product screens are added.
|
||||
|
||||
Implemented frontend scaffold: a React Router data router with public routes and separate candidate and employer cabinet shells, a TanStack Query client over the shared same-origin `apiRequest`, dark graphite theme tokens in CSS variables, and shared primitives for loading, empty, error, forbidden, and saving states. JetBrains Mono, Inter, and Unbounded (for the Lincodex wordmark) are self-hosted with their OFL licenses. Sign-in, registration, email confirmation, support, and cabinet screens are placeholders; business screens are later tasks. /status is a technical API liveness page, not product readiness. Vitest runs in the Node environment without a DOM. The Playwright suite in `frontend/e2e/` loads pages in Chromium but does not yet test interactions, so clicks and keyboard focus are verified manually in a browser until it covers them. See [frontend/README.en.md](../../frontend/README.en.md). Generated transport types are not automatically entity models. MSW supports UI development; its fixtures do not prove that the API is implemented.
|
||||
|
||||
ML runs as a separate FastAPI process. It currently provides operational health/readiness only. Readiness stays at 503 without a model. Do not add placeholder inference that looks like a real result.
|
||||
|
||||
Write all source comments and docstrings in English. Keep canonical agent instructions in one English version; maintain user documentation in Russian and English.
|
||||
|
||||
### Database migrations
|
||||
|
||||
Migrations are goose SQL files in `backend/db/migrations/` named `NNNNN_description.sql` with sequential five-digit versions. Each file has a `-- +goose Up` section and a working `-- +goose Down` section. sqlc reads the same directory as its schema, and `make -C backend lint-sql` lints it. `backend/db/migrations.go` embeds the files, so the binary applies exactly the schema it was built with. `make -C backend check` loads the embedded set without a database and fails on a malformed name, a missing Down section, or a duplicate version. A deployed migration is immutable; change the schema with a new file. Two branches that add the same version must renumber before merging. To create a file with the next sequential number, run `go tool goose -dir db/migrations -s create <name> sql` in `backend/`.
|
||||
|
||||
goose runs each migration in its own transaction. A statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`, needs a file of its own with the `-- +goose NO TRANSACTION` annotation. Every migration connection sets `lock_timeout` to 10 seconds, so DDL fails instead of queueing behind long transactions and blocking later queries on the table, and `statement_timeout` to 4 minutes.
|
||||
|
||||
At startup bootstrap applies pending migrations after configuration validation and before the HTTP and metrics listeners open. The runner in `backend/internal/adapter/secondary/postgres/migrator.go` uses the goose v3 Provider API with the pgx database/sql driver and a PostgreSQL session advisory lock, so instances that start together apply migrations one at a time. Lock waiting and migration work are limited to five minutes. A migration error stops startup; the error omits the connection string and the password. Without `DATABASE_URL` the step is skipped with a warning, and readiness stays `not_ready` as before.
|
||||
|
||||
`DATABASE_MIGRATE_ON_START` accepts only `true` or `false` (case-insensitive, surrounding spaces ignored); the default is `true`. It is a local and development option, for example to start the service against a database that a developer migrates by hand. The Compose stack does not pass it, and the backend image contains no separate migration command, so a deployed backend always migrates at startup and its database role needs DDL rights on the application schema. A separate migration role and job with a least-privilege runtime role is future work.
|
||||
|
||||
For a local database, export `DATABASE_URL` in your shell and use these targets:
|
||||
|
||||
- `make -C backend migrate-status` lists each embedded migration as applied, with its time, or pending.
|
||||
- `make -C backend migrate-up` applies pending migrations.
|
||||
- `make -C backend migrate-down-one` rolls back the latest applied migration.
|
||||
|
||||
The targets run `backend/cmd/migrate` with the same runner, lock, and timeouts as startup. The Makefile contains no connection strings; keep credentials out of committed files. Integration tests apply all migrations to the PostgreSQL container from the shared bootstrap; see [TESTING.md](TESTING.md).
|
||||
|
||||
### Identity storage
|
||||
|
||||
Migration `00002_create_identity_tables.sql` creates `users`, `email_tokens`, and `sessions`; the queries are in `backend/db/queries/identity.sql`. Migration 00014 adds the password hash, scenario, and onboarding step for each registration to its token. Migration 00016 binds registration C1 to the account registration version and backfills existing records without using live tokens. The identity ports are used by registration, verification resend, and email confirmation; login and the session principal are not implemented.
|
||||
|
||||
The database never receives a password, a raw email token, or a raw session token. Repositories take a `domain.PasswordHash` (an Argon2id v19 PHC string) and a `domain.SecretTokenHash` (the SHA-256 of a `domain.SecretToken`). Email addresses are ASCII only for now; IDN and SMTPUTF8 support is future work that needs IDNA ToASCII for the domain. `SecretToken`, `PasswordHash`, and `EmailAddress` redact themselves in `fmt` and `slog` output; `SecretToken.Reveal` and `EmailAddress.Address` return the real values where they are needed. Every stored time comes from the application clock that the caller passes, and PostgreSQL keeps microseconds. A deadlock or serialization failure is reported as `outbound.ErrTransactionConflict`, and the caller may retry the whole operation. The schema and its decisions are described in [ARCHITECTURE.md](ARCHITECTURE.md#identity-storage).
|
||||
|
||||
Passwords enter the backend only as `domain.Password`: `domain.NewPassword` for a new password (15 to 128 code points after NFKC) and `domain.ParseLoginPassword` at login (1 to 128). Raw input over 512 bytes or with invalid UTF-8 is rejected before normalization, and every length check runs before hashing. The `argon2id` adapter implements `outbound.PasswordHasher` with m=65536 KiB, t=3, p=4, a memory budget of `PASSWORD_HASH_CONCURRENCY` derivations (1 to 4; unset means the smaller of 2 and GOMAXPROCS), `ErrPasswordMismatch` for a wrong password, `ErrPasswordHashCorrupt` for a malformed or out-of-bounds stored hash, a `needsRehash` result for older parameters, and `VerifyDummy` for unknown accounts. A stored hash that fails parsing or bounds wraps both `ErrPasswordHashCorrupt` and `domain.ErrInvalidPasswordHash`. Unit tests use cheap parameters; the 64 MiB reference vector is skipped with `-short`; `go test -run '^$' -bench . ./internal/adapter/secondary/argon2id/` in `backend/` measures one hash with the production parameters. See [ARCHITECTURE.md](ARCHITECTURE.md#password-hashing).
|
||||
|
||||
### Product policy store
|
||||
|
||||
Migration `00003_create_policy_versions.sql` creates `policy_versions`, the trigger that stamps `created_at` from the database clock, and the triggers that refuse UPDATE, DELETE, and TRUNCATE; the queries are in `backend/db/queries/policy.sql`. `outbound.PolicyRepository` is available through `UnitOfWork.Policies()` and through `postgres.PolicyStore` outside a transaction; `policy.Publisher` publishes a version under the next free number and seeds the demo policy. To change a value, publish a new version; a stored version is never edited. `product` is the only policy family.
|
||||
|
||||
At startup the backend publishes `domain.DemoProductPolicyV1()` as version 1 of `product` when that family has no version. The seed runs right after the startup migrations and only when they run (`DATABASE_MIGRATE_ON_START` is true and `DATABASE_URL` is set). With startup migrations disabled, nothing seeds the policy. The seed checks presence only, never changes or decodes an existing version, and logs only the key, number, kind, and ID. The demo values are the accepted initial policy, not calibrated values.
|
||||
|
||||
A record that depends on policy values adds `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)`, stores the version it used, and reads it back by ID; do not recompute an existing record through `GetEffective`. Tests use their own values and do not stand in for the demo policy. Since `product` is the only family and the table refuses TRUNCATE, the integration tests give every case its own database. A new document layout needs a new `schema_version` and decoder; do not edit the golden document in `backend/internal/domain/policy_test.go` to accept a changed canonical form. See [ARCHITECTURE.md](ARCHITECTURE.md#product-policy-versions).
|
||||
|
||||
### Assessment bank
|
||||
|
||||
Migration `00011_create_assessment_bank.sql` creates `assessment_families` (immutable family versions) and `assessment_category_openings`; the queries are in `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` is available through `UnitOfWork.AssessmentBank()` and `postgres.AssessmentBankStore` outside a transaction; `assessment.Bank` imports a `Bundle`, publishes a version as an operator (retiring the published older one), retires it, opens a category under the policy version in force, reports live availability, and generates a variant of a seed. To change a family, import a new version; a stored version is never edited, and a pending draft is approved by importing a new version that carries the review. A new seed algorithm gets a new versioned name in `domain/assessment_algorithms.go`, its required placeholders, a solver test with hand-computed cases, and a golden test; never change a registered algorithm. An algorithm with the answer format `choice` sets `generateChoice` instead of `generate` and returns the correct value with the wrong values of named error models (`lru_hits_choice.v1` is the example); its tests recompute the error models from the statement. A family whose variants are fixed data uses a table generator instead of an algorithm: `seed_generator.table.rows` with `values`, `answer`, and for `choice` the `distractors`, validated at import with the row index in the error and stored with hash scheme 2; use a Go algorithm when the answer must be computed. Migration `00047_allow_table_hash_scheme.sql` allows scheme 2. Statement templates are plain text with `{{.name}}` placeholders only. The demo bundle in `backend/testdata/assessment/` is an unreviewed AI draft: do not fill in its reviewer to open the category. See [ARCHITECTURE.md](ARCHITECTURE.md#assessment-bank).
|
||||
|
||||
### Outbox relay
|
||||
|
||||
The relay moves committed `outbox_events` rows to Kafka. The loop lives in `backend/internal/worker/outboxrelay/` and its backoff in `backend/internal/worker/retry/`; it depends on the `outbound.OutboxRelayStore` and `outbound.EventPublisher` ports in `backend/internal/port/outbound/outbox_relay.go`. `postgres.OutboxRelayStore` runs the claim transaction with the `LockPendingOutboxEvents` and `MarkOutboxEventsPublished` queries from `backend/db/queries/outbox.sql`, and `kafka.Publisher` in `backend/internal/adapter/secondary/kafka/` builds the record envelope, provisions the topic, and produces with franz-go. `bootstrap.newOutboxRelay` creates the relay with its own PostgreSQL pool of at most two connections and its own Kafka client, and the application runs it while the HTTP servers run. Product code never calls the relay: a usecase only appends events with `UnitOfWork.Outbox()` in its business transaction.
|
||||
|
||||
A directly launched backend with `DATABASE_URL` set runs the relay against `KAFKA_BROKERS` (`localhost:9092` by default). Without a reachable broker it keeps logging retry warnings and the events stay pending; set `RELAY_ENABLED=false` when you do not need publication. Selection, ordering, envelope, and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#outbox-relay); settings are in [DEPLOY.md](DEPLOY.md#outbox-relay); tests are in [TESTING.md](TESTING.md#outbox-relay-tests).
|
||||
|
||||
### Event consumers
|
||||
|
||||
The consumer runtime applies events from Kafka to this service's own state, once per consumer. The loop lives in `backend/internal/worker/eventconsumer/`; it depends on the `inbound.EventHandler` port (`backend/internal/port/inbound/event_handler.go`) and on the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`). `kafka.EventSource` is the franz-go group member that decodes the envelope and commits offsets, and `postgres.EventConsumerStore` runs the dedup transaction with the queries in `backend/db/queries/event_consumer.sql`. The backoff is shared with the relay in `backend/internal/worker/retry/`.
|
||||
|
||||
Two product handlers are registered: `notification.DeliveryHandler` stores mail deliveries (see [Mail deliveries](#mail-deliveries)) and `notification.InboxHandler` stores inbox references (see [Internal notifications](#internal-notifications)). To add another, implement `inbound.EventHandler` in the module's usecase package: return a stable snake_case `ConsumerName()`, accept only the event types it applies in `Handles`, and write the effect in `Handle` only through the `UnitOfWork` it receives. Return an error that wraps `inbound.ErrEventRejected` for an event that can never be applied, such as an unknown `schema_version`; any other error is retried. Then add the handler to `eventHandlers()` in `backend/internal/bootstrap/consumers.go`. Bootstrap gives it a consumer group, a share of the consumer pool, and a lifecycle next to the HTTP servers. Test the effect with a real PostgreSQL through the store, as `TestEventConsumer` does.
|
||||
|
||||
A directly launched backend with a registered handler and `DATABASE_URL` set consumes from `KAFKA_BROKERS`; set `CONSUMER_ENABLED=false` when you do not need it. Design and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers); settings, metrics, and the dead letter procedure are in [DEPLOY.md](DEPLOY.md#event-consumers); tests are in [TESTING.md](TESTING.md#event-consumer-tests).
|
||||
|
||||
### Mail deliveries
|
||||
|
||||
To send a notification from a usecase, call `notification.MailRequester.RequestNotification(ctx, unit, request)` with the usecase's `UnitOfWork`, the recipient account ID, and `mailtemplate.NotificationData`; it returns the delivery ID. It stores the text in `mail_requests` and appends an event that carries only the request ID and kind, both in the usecase's transaction. The consumer `notification_delivery` then stores the delivery with the address read from the account and the rendered content, and deletes the request; it skips accounts whose address is not verified. Never put an email address, a token, notification text, or another person's contact into any event payload, and never put a token or another person's contact into a request. Verification and password reset mail carry a token and cannot use the event: the identity flows create those deliveries with `domain.NewDelivery` and `UnitOfWork.Deliveries().Create` in the transaction that issues the token. A new template version changes new deliveries only; never update a stored delivery's content. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries), operations in [DEPLOY.md](DEPLOY.md#mail-deliveries), and tests in [TESTING.md](TESTING.md#mail-delivery-tests).
|
||||
|
||||
Every send must pass `notification.QuotaGate`: build it with the configured account and limits and the transport's idempotency window (`resend.IdempotencyWindow`, or zero for SMTP); call `PrepareSend` in the transaction that claims the delivery and commit before calling `MailSender.Send`; then call `SettleSend` in the transaction that records the attempt, and use the time it returns as the attempt's `next_attempt_at` for a `quota_exhausted` rejection. A transport sets `SendResult.QuotaPeriod` from the provider's own error name for a quota rejection. Never call a transport without a permit, and never fall back to another transport or account when the quota is used up. To show an account its own mail status, call `notification.DeliveryStatusReader.LatestForUser` with the authenticated account's ID only. The rules are in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas).
|
||||
|
||||
### Internal notifications
|
||||
|
||||
To put a notification into a recipient's inbox, append an event with `unit.Outbox().Append` in the usecase's own transaction. The type must be allowlisted (`domain.NotificationInboxSourceFor`), the payload must be exactly `recipient_user_id` and `organization_id`, and the aggregate must be the one the type names (`invitation` for `invitation.delivered`). Never put text or contacts in the payload. The `notification_inbox` consumer stores a reference. The text is produced when the recipient reads the list, by a resolver that you register for your source type in `notification.DefaultInboxSourceResolvers()`: an `InboxSourceResolver` that reads the current state through the `UnitOfWork`, applies the recipient's current visibility, and returns `ErrInboxContentUnavailable` when the content must not be shown. For a new event type add the pair to `domain.NotificationInboxSourceFor`, the entry to `inboxProjections` in `usecase/notification/inbox_handler.go`, a migration that widens the CHECK constraint of `notification_inbox_events` (never edit a deployed migration), a `NotificationKind` value to the contract, and the mapping in `adapter/primary/http/v1/notifications.go`. A producer needs no email: mail is requested separately with `MailRequester`, and the inbox state does not depend on it. The path can be tried end to end with the synthetic event `notification.synthetic_delivered` (`notification.SyntheticNoticeEventPayload` builds its payload); it has no product meaning and is handled only when `NOTIFICATION_SYNTHETIC_ENABLED=true`. See [Internal notifications](ARCHITECTURE.md#internal-notifications).
|
||||
|
||||
### Scheduled jobs
|
||||
|
||||
To run something when it falls due, such as an expiry or a reminder, schedule a job in the usecase's own transaction: build it with `domain.NewScheduledJob` (a kind such as `invitation.response_deadline`, a key that identifies the logical job, for example the aggregate ID, the due time from the injected clock, and a payload of identifiers only) and call `unit.ScheduledJobs().Schedule(ctx, job)`. The first schedule of a kind and key wins and a repeat is ignored, so use a new key, for example `<id>:<version>`, for a new occurrence. Cancel with `unit.ScheduledJobs().Cancel(ctx, kind, key)` before locking the product rows that the handler touches.
|
||||
|
||||
Then implement `inbound.JobHandler` in the module's usecase package: return the kind from `JobKind()` and write the effect in `Handle` only through the `UnitOfWork` it receives, deciding by `job.DueAt` and the current product state, so the handler is a no-op when the state already moved on. A handler may cancel its own job through the unit, for example from a shared helper that cancels the deadline; the job then counts as finished. It must not change its own job in any other way. Return an error that wraps `inbound.ErrJobRejected` for a job that can never run; any other error is retried. Add the handler to `jobHandlers()` in `backend/internal/bootstrap/jobs.go`. Take the clock as a `func() time.Time` and test deadlines with `testutil.FakeClock` from `backend/pkg/testutil/` and `Worker.RunDue`, which runs the due jobs once without polling, as `TestScheduledJobs` does. Design and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#scheduled-jobs); settings, metrics, and the dead job procedure are in [DEPLOY.md](DEPLOY.md#scheduled-jobs); tests are in [TESTING.md](TESTING.md#scheduled-job-tests).
|
||||
|
||||
## Go readability
|
||||
|
||||
- Extract repeated parsing, setup, and cleanup into small typed helpers near their consumers. Move code to `pkg/` when several packages actually reuse it. Avoid wrappers that only rename a call.
|
||||
- Name non-obvious limits, timeouts, retry settings, protocol bounds, and shared fixture values with constants in the owning package. Derive counts with `len` when they depend on data. Equal numbers with different meanings need separate names. Obvious zero values, indexes, and clear test inputs can stay inline.
|
||||
- Environment settings belong in config with named defaults and validation. Parse each value once; distinguish an unset variable from an explicitly invalid value.
|
||||
- Give each function one clear purpose. Prefer early returns, shallow nesting, and named complex conditions. Do not add generic helpers, interfaces, or layers without consumers.
|
||||
- Pass `context.Context` first. Keep resource ownership and dependencies explicit; register cleanup immediately after acquisition, including partial startup. Helpers must not hide goroutines or global mutable state.
|
||||
- Check errors and explain non-obvious discarded results. Do not use error-string comparisons for control flow or expose internal errors in HTTP responses.
|
||||
- Write English comments explaining constraints and decisions. Use gofmt/goimports. Refactors preserve behavior; tests cover meaningful boundaries and edge cases rather than constant names or helper internals.
|
||||
|
||||
## Error format
|
||||
|
||||
Handwritten Go errors use `Component.Method - operation: %w` when wrapping a cause and `Component.Method - reason` without a cause. For a free function, use `package.Function`. For example:
|
||||
|
||||
```go
|
||||
if err != nil {
|
||||
return fmt.Errorf("EmailUseCase.Send - read ctf_name: %w", err)
|
||||
}
|
||||
```sh
|
||||
make -C api check
|
||||
make generate
|
||||
make check-generated
|
||||
```
|
||||
|
||||
Create a static error without a cause using `errors.New("EmailUseCase.Send - ctf_name is empty")`. The prefix identifies the actual method; descriptions are in English without trailing punctuation. Preserve `errors.Is/As` and sentinel identities, adding context at the error's origin. Avoid redundant wrappers for pass-through returns. Sanitize external SDK errors before wrapping to exclude secrets, URLs, and private object keys. Do not edit generated code. Log errors at the handling boundary rather than at every layer.
|
||||
Generation order is API bundles, Go backend, runner, labd, frontend, and Python ML. `make check-generated` compares output with Git without running generators. Intentional contract changes should include updated output in the same commit; investigate unexpected differences.
|
||||
|
||||
## Change rules
|
||||
- ogen writes Go HTTP code into the relevant adapter's `api/` directory.
|
||||
- sqlc writes PostgreSQL queries into `backend/internal/adapter/secondary/postgres/sqlc/`.
|
||||
- wire assembles dependencies in `backend/internal/bootstrap/`.
|
||||
- mockery generates only interfaces selected in `backend/codegen/mockery.yml`.
|
||||
- Orval writes the client, query hooks, Zod schemas, and MSW into `frontend/src/shared/api/endpoints/` and `schemas/`.
|
||||
- datamodel-code-generator creates Pydantic models from the ML contract.
|
||||
|
||||
- Inspect current code and ownership before editing a shared file.
|
||||
- Preserve other contributors' current changes.
|
||||
- Coordinate changes to OpenAPI, migrations, shared Makefiles, lockfiles, and generated output with one owner of that shared surface.
|
||||
- Regenerate derived files through Make targets.
|
||||
- Label current behavior and intended behavior separately.
|
||||
- Do not commit local paths, secrets, or personal developer settings.
|
||||
Do not edit output by hand. Generator configuration belongs to its consumer's `codegen/` directory: the Go ML client belongs to backend and the Python models belong to ML.
|
||||
|
||||
For backend, frontend, ML, API, database, and infrastructure tasks, use the routes in the root [AGENTS_ROUTING.md](../../AGENTS_ROUTING.md).
|
||||
## Backend and data
|
||||
|
||||
Domain types live directly in `internal/domain/`. Usecases depend on ports; adapters provide HTTP, database, and external-service access. `internal/bootstrap/` assembles dependencies and manages their lifecycle; `cmd/app/main.go` calls it.
|
||||
|
||||
- Put business rules in domain/usecase and HTTP conversion in `adapter/primary/http/v1/`.
|
||||
- Define the required port and adapter for new infrastructure. Services do not access another service's tables directly.
|
||||
- Edit SQL in `db/queries/`, then run `make -C backend gen-sqlc`.
|
||||
- Add schema changes as new migrations in `db/migrations/` and test on an isolated database. Do not rewrite applied migrations.
|
||||
- Save business changes and their outbox event in one transaction. Handlers must tolerate repeated delivery.
|
||||
- Extract repeated code into small helpers; use named constants or configuration for values with domain meaning.
|
||||
|
||||
Errors identify the location and reason: `fmt.Errorf("ProfileUseCase.Update - save profile: %w", err)`. Use the same format without `%w` when there is no underlying error. HTTP responses expose safe problem codes, not internal errors or personal data.
|
||||
|
||||
`make -C backend help` lists maintenance commands. Migrations, mail retries, policy publication, and backfills change state: select the intended environment explicitly.
|
||||
|
||||
## Frontend
|
||||
|
||||
FSD layers are `app`, `pages`, `widgets`, `features`, `entities`, and `shared`. Import lower layers through slice public APIs; do not couple neighboring slices through internal imports. Common components and styles belong in `shared/`; use generated API types.
|
||||
|
||||
Keep server state in TanStack Query and drafts in form state. Preserve entered data on version conflicts and offer to reload the server state. Asynchronous screens need loading, empty, error, and retry states.
|
||||
|
||||
Check keyboard access, focus, field labels, and narrow screens. Vitest checks logic; Playwright checks the interface in a browser.
|
||||
|
||||
## ML and additional services
|
||||
|
||||
ML commands: `make -C ml help`. Ordinary checks use Ruff, mypy, and pytest; model quality and real inference are separate checks. Pin model weights and evaluation data versions.
|
||||
|
||||
Runner and labd are separate Go modules. Unit tests do not replace runner isolation checks or testing labd on a separate LXD test host. Their environments are described in [runner/](../../runner/README.en.md) and [labd/](../../labd/README.en.md).
|
||||
|
||||
## Documentation and Git
|
||||
|
||||
A directory README explains its purpose, startup, and main commands. Details belong in contracts, source files, and the relevant guide. Keep execution history and inventories of individual tests out of documentation.
|
||||
|
||||
Write code comments in English. Maintain documentation in RU/EN pairs. Plans and their identifiers stay in local `PRD/`, which must not be committed. Use a short, single-line commit message describing the change, without assistant authorship or coauthor trailers.
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
# Lincodex MVP: submission package
|
||||
|
||||
Verified commit: `c9f029471ed78ce5ec4583009abdc5a4c8c3bd97` (branch dev, 2026-10-10).
|
||||
|
||||
Release: `mvp-2026-10-10`, built from `392d117` (the same code plus this document). The manifest `deploy/release/mvp-2026-10-10/manifest.json` is a local artifact of the machine that built the images (it is not kept in Git, see [release manifest](DEPLOY.md#release-manifest)); the core is `verified`, the smoke and the browser suite passed on the release images, and restore is available.
|
||||
|
||||
This document describes what the minimal release contains, how to run it, what limits the demonstration category, what is not implemented, and how the release was checked. Details live in the guides: [ARCHITECTURE](ARCHITECTURE.md), [DEPLOY](DEPLOY.md), [TESTING](TESTING.md), [SECURITY](SECURITY.md), [COMPANY_QUOTAS](COMPANY_QUOTAS.md), and the [frontend guide](../../frontend/README.en.md). The HTTP API contract is in [api/](../../api/README.en.md). The statements below are derived from the code, the contract, and these guides; planned behavior is kept apart from working behavior.
|
||||
|
||||
## 1. What is implemented
|
||||
|
||||
### Registration and sign-in
|
||||
|
||||
- Registration of a candidate and an employer with the C1 consent. The address is confirmed with a link from the email or with a six-digit code from the same email; after confirmation, sign-in returns the user to the saved step. See [registration and confirmation](ARCHITECTURE.md#registration-email-verification-and-resend).
|
||||
- Email is sent only with `EMAIL_PROVIDER=resend`. With `disabled`, registration is accepted but there is no way to confirm the address, and sign-in answers 403 `email_not_verified`. The prepared accounts of the demo stand are confirmed in advance. See [mail](DEPLOY.md#2-mail-resend-or-disabled).
|
||||
|
||||
### Candidate
|
||||
|
||||
- Consents C1-C5 in settings. C3 allows automatic categorization; without it, a manual assessment can be requested through a support case.
|
||||
- The profile is filled in manually, step by step, without a resume and without an FSP ID. The questionnaire holds specializations and self-assessment. The home page shows the next step. See [candidate profile](ARCHITECTURE.md#candidate-profile).
|
||||
- Skill assessment in two modes (see [assessment](ARCHITECTURE.md#assessment-and-grade-verification)):
|
||||
- the full `demo_basic` Backend Junior with Go test: 25 tasks from a synthetic bank, a 72-hour window, two work sessions, no practice. The result is compared with the pass mark of the policy version; on the demo stand a passed test gets a category with the basis `synthetic_demo`, otherwise the result is `not_confirmed`;
|
||||
- the `demo_express` test: three tasks; it never assigns a grade, a category, a percentile, or evidence and does not appear in the result history.
|
||||
- Results, history, and skill evidence are available to the candidate; the declared grade is always kept apart from the confirmed one. See [evidence](ARCHITECTURE.md#skill-evidence).
|
||||
|
||||
### Publication and visibility
|
||||
|
||||
- The anonymous card is published only after an explicit C2 and carries no name, contact, or salary amount. The candidate sees a preview built from the same response that the card for organizations uses.
|
||||
- Search status, hiding of individual organizations, change history, and the history of card views and contact reads. A card is shown to organizations only in a group of at least five. See [visibility](ARCHITECTURE.md#candidate-visibility).
|
||||
|
||||
### Employer
|
||||
|
||||
- Organizations (one account can own several), a company profile, and a step-by-step need with a salary range. A need stores requirement versions; a search by a version does not change after an edit. See [organizations](ARCHITECTURE.md#organizations-and-memberships).
|
||||
- Candidate search by a need or by the bank with filters: specialization, confirmed and declared grade, confirmation status, stack, work format, and salary compatibility. The result is split into the groups `main`, `near`, and `unconfirmed`, and the server builds the explanation (score components and unknown flags).
|
||||
- The baseline match works without ML: semantic similarity is a neutral 0.5 marked with the flag `ml_unavailable`; for a cohort below 30 the flag `cohort_below_30` is added. See [matching and explanations](ARCHITECTURE.md#matching-and-explanations).
|
||||
|
||||
### Invitations and contacts
|
||||
|
||||
- The organization creates a draft from a search result, changes the terms with versions, and sends the invitation with a salary range in rubles. Sending spends one place of the weekly quota; a pending limit applies per need, a pair pause applies after a decline, and an unanswered invitation expires at its deadline. See [drafts](ARCHITECTURE.md#invitation-drafts), [sending](ARCHITECTURE.md#sending-invitations), and [limit and expiry](ARCHITECTURE.md#pending-limit-cooldown-and-expiry).
|
||||
- A delivered invitation reaches the candidate inbox. The candidate marks it viewed, declines it, or accepts it with the C4 consent and a choice of contact fields. See [view and decline](ARCHITECTURE.md#candidate-view-and-decline) and [acceptance](ARCHITECTURE.md#candidate-acceptance).
|
||||
- Acceptance creates a contact grant for exactly this pair. The organization reads the chosen fields on the invitation page, and every read checks the grant and the visibility again. Revoking C4, revoking C2, closing the publication, and hiding the organization close the read at once; republishing does not reopen a closed grant. See [contact reads and revocation](ARCHITECTURE.md#contact-reads-and-revocation).
|
||||
|
||||
### Company isolation and holdings
|
||||
|
||||
- Organization operations answer a foreign identifier with the same refusal as for a random identifier. Search, invitations, and contact reads are available only to the owner of the organization.
|
||||
- Organizations of one account form a holding: E0 companies share common quotas (in the demonstration policy, 10 invitations per 7 days and 50 unique card views per 24 hours). The number of organizations per account is not limited. See [COMPANY_QUOTAS](COMPANY_QUOTAS.md#holding-pool).
|
||||
|
||||
### Notifications and mail
|
||||
|
||||
- An inbox in both cabinets; the only product source is a delivered invitation. The entry appears through the outbox, the relay, and Kafka after the commit, not inside the sending transaction. See [internal notifications](ARCHITECTURE.md#internal-notifications).
|
||||
- The invitation email goes through the outbox and the delivery consumer, and a separate notification loop (a worker in the backend process) sends it; before each send it checks the recipient rights again and leaves a quota reserve for service mail. The body is neutral and holds no contacts. See [sending product notifications](ARCHITECTURE.md#sending-product-notifications).
|
||||
- Support cases in both cabinets.
|
||||
|
||||
### Privacy guarantees
|
||||
|
||||
- Before the C4 record and the grant, the organization receives no contacts; cards, search results, invitation lists, and notifications contain no email, phone, or name.
|
||||
- The server log, outbox payloads, inbox rows, and mail requests carry no contact or profile values (checked by the isolation integration test, see section 5).
|
||||
- Organization responses contain no PDFs and no stored search snapshots: there are no such operations.
|
||||
|
||||
## 2. How to run
|
||||
|
||||
Run all commands from the repository root. You need Docker with Compose, GNU make, python3, and openssl; no GPU or external keys are required. Full instructions: [quick start](DEPLOY.md#running-the-mvp-quick-start).
|
||||
|
||||
### Working stand
|
||||
|
||||
cp .env.example .env # replace every replace-this-... value and set IDENTITY_KEY_SECRET
|
||||
make -C deploy config
|
||||
make -C deploy up
|
||||
curl http://localhost:8080/api/v1/healthz
|
||||
|
||||
Open http://localhost:8080 (the value of `APP_PUBLIC_URL`). For email, set `EMAIL_PROVIDER=resend`, `RESEND_API_KEY`, and `EMAIL_FROM` in the server environment. A clean stand holds migrations and the starting policy; operator steps (`DATABASE_URL` is required):
|
||||
|
||||
1. Publish the matching section; without it the search answers 500: `make -C backend policy-publish ARGS='matching --actor operator:<handle>'`. See [match search policy](DEPLOY.md#match-search-policy-on-a-stand).
|
||||
2. For a passed full test to receive the demonstration category, set `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`, restart the backend, and attest the category opening with `make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:<handle>'`. Publishing a new policy version requires a new opening and a new attestation, so do step 1 before candidates start attempts. See [demonstration categories](DEPLOY.md#demonstration-categories-on-a-stand).
|
||||
|
||||
The task bank is not loaded on the core stand, and the DEPLOY guide describes loading it only as part of the demo stand seed, so a test cannot be started on the core stand. Use the demo stand to show the full path.
|
||||
|
||||
### Demo stand and the jury route
|
||||
|
||||
make -C deploy demo-seed DEMO_MODE=isolated
|
||||
|
||||
The command starts a separate project at http://localhost:8090, publishes the policy with the matching section, loads the synthetic bank, attests the category, and creates the accounts `candidate@`, `prepared-1@` to `prepared-6@`, `employer-alpha@`, and `employer-beta@` in the domain `demo.lincodex.test`; the password comes from `deploy/demo/demo.env` or `demo.env.example`. The jury guide is at http://localhost:8090/demo; it takes eight minutes and exists only in the build of this stand. The route: the express and full tests of the candidate, prepared candidates with published cards, a need and a search by the owner of "Alpha", an invitation, acceptance with C4, and a contact read. See [demo stand](DEPLOY.md#3-demo-stand), [route](DEPLOY.md#4-demonstration-route), and [isolated stand](DEPLOY.md#isolated-demo-stand). Reset: `make -C deploy demo-reset DEMO_MODE=isolated` (it refuses when the stand holds ordinary accounts).
|
||||
|
||||
### Restoring from a release manifest
|
||||
|
||||
make -C deploy release-build
|
||||
make -C deploy release-smoke
|
||||
make -C deploy release-e2e
|
||||
make -C deploy release-manifest RELEASE_ID=<id>
|
||||
make -C deploy release-up RELEASE_ID=<id>
|
||||
make -C deploy release-manifest-verify RELEASE_ID=<id> RELEASE_VERIFY_PROJECT=<project>
|
||||
make -C deploy demo-seed DEMO_MODE=isolated RELEASE_ID=<id>
|
||||
|
||||
The manifest is immutable: it pins the sources, lockfiles, Compose files, and image IDs, and `release-up` starts those images without building or pulling and checks the hashes. A manifest is published only for a clean tree and after successful smoke and E2E runs on those images. `release-manifest-verify` compares the running containers with the manifest. A demo stand restored from a manifest has no `/demo` guide because it uses the frontend of the main release. The assessment bank is not snapshotted in the manifest (`product_data_status` is `partial`). See [release manifest](DEPLOY.md#release-manifest).
|
||||
|
||||
## 3. Limits of the demonstration category
|
||||
|
||||
- The task bank is small and synthetic: 25 families for the full test and three for the express test. The families go through the regular publication pipeline with author and reviewer labels, but their content did not receive a subject-matter review.
|
||||
- Thresholds are not calibrated, no percentile is computed, and there is no adaptive test. The result shows the mechanics, not a measured qualification.
|
||||
- In the API the category basis is `synthetic_demo`, described in the contract as a demonstration category that is not a validated measurement. By the product owner's decision the interface shows it as an ordinary confirmation (the label "Test result"). The API and this documentation keep the basis.
|
||||
- The express test assigns no grade under any settings.
|
||||
- The consent texts C1-C5 are published by migrations as `demo`, without legal review. Do not register real people on the demo stand.
|
||||
|
||||
## 4. What is not implemented
|
||||
|
||||
The following belongs to the full product and does not work in this release:
|
||||
|
||||
- coding practice (a sandbox) and an adaptive test;
|
||||
- the final bargaining round and counter-offers: no operation creates the `counter` state, and a salary raise answers 501 `not_implemented`;
|
||||
- interview scheduling and reminders;
|
||||
- withdrawal of an invitation by the organization and cancellation by the candidate: both operations answer 501;
|
||||
- roles other than the owner and need assignments: only the owner of an organization can search, invite, and read contacts;
|
||||
- PDF documents and stored search snapshots;
|
||||
- category recommendations for a need: the need response reports the state `pending` or `not_available` with an empty list;
|
||||
- enabled ML inference: the ML service starts separately without a model, and the backend does not call it;
|
||||
- FSP integration: there is no mode, fixture provider, or call to an external API;
|
||||
- the SMTP transport: selecting `EMAIL_PROVIDER=smtp` stops the backend at startup;
|
||||
- ATS integration;
|
||||
- password reset, resume upload and parsing, and emails for events other than confirmation and a new invitation.
|
||||
|
||||
## 5. How it was verified
|
||||
|
||||
Acceptance result on the verified commit (2026-10-10): `make verify` passed, including 110 integration tests and the technical smoke; `make -C deploy test-e2e-registration` - 95 passed, 1 skipped; `make -C deploy test-e2e` - 64 passed, 32 skipped; `make -C security install test check` and `make security-images` passed with no blocking findings (the scanners ran in a Linux container, as in CI, because their installer supports only Linux; the exception for CVE-2026-93687 is valid until 2026-10-19). The boundaries of every check are described in [TESTING](TESTING.md#commands).
|
||||
|
||||
| Check | What it proves |
|
||||
| --- | --- |
|
||||
| `make verify` | Contract generation without drift, formatting, linters, types, build, Compose, documentation, backend with the race detector, integration tests on PostgreSQL, Redis, SeaweedFS, and Kafka, and a technical smoke |
|
||||
| `make -C deploy smoke` | Stack startup, dependency readiness, and dependency failures; it does not check a business flow |
|
||||
| `make -C deploy test-e2e` | The Playwright suite on a throwaway stack with mail disabled, including `mail-unavailable.spec.ts`: the user sees that the email may arrive later and cannot sign in before confirmation |
|
||||
| `make -C deploy test-e2e-registration` | Registration, confirmation by link and by code, and sign-in through the local Resend-compatible inbox, and within it `acceptance-path.spec.ts` |
|
||||
| `acceptance-path.spec.ts` | The minimal path on the real backend: five candidates, the full test with a `synthetic_demo` category, publication, a need, a search with an explanation and a filter, invitations, acceptance with C4, a contact read, a decline, C2 revocation, and no duplicates after a refresh and a double acceptance. See [the path to contacts](TESTING.md#minimal-path-from-registration-to-disclosed-contacts) |
|
||||
| `TestCompanyIsolationAndRevocationOverHTTP` | Isolation of companies and candidates, immediate closure after hiding and after revoking C4 and C2, and no contacts in the log, outbox, inbox, and mail requests. See [organization tests](TESTING.md#organization-tests) |
|
||||
| `TestInvitationNoticesSurviveRelayAndConsumerRestarts` | Exactly one notice and one email per recipient after relay and consumer restarts and a lost offset |
|
||||
| `TestHoldings`, `TestCompanyQuota` | The shared E0 quota pool inside a holding and no overrun under concurrent reservations |
|
||||
| `make -C security check`, `make -C security images` | Dependency vulnerabilities, secrets, dangerous constructs, and images; see [SECURITY](SECURITY.md) |
|
||||
| `make -C deploy check-demo`, `make docs-check` | Guards of the demo stand targets and the documentation structure |
|
||||
| `make -C deploy release-smoke`, `release-e2e` | The same smoke and browser suite on the release images; a passing run produces evidence for the manifest |
|
||||
|
||||
The checks do not prove: assessment calibration, match accuracy, email delivery through the real Resend, operation behind HTTPS, and production load.
|
||||
+27
-35
@@ -1,62 +1,54 @@
|
||||
# Security checks
|
||||
# Security
|
||||
|
||||
The repository provides local and CI checks for known dependency vulnerabilities, selected configuration risks, secrets, and selected unsafe source patterns. These checks cover the technical scaffold. They do not establish complete security or verify future authorization and personal-data workflows.
|
||||
Server-side authorization and service boundaries protect data. Scanners check known vulnerabilities and selected risky patterns; they do not replace business-flow checks or an audit.
|
||||
|
||||
## Commands
|
||||
## Checks
|
||||
|
||||
Run from the repository root:
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
make -C security install
|
||||
make -C security check
|
||||
make -C security test
|
||||
make -C security test check
|
||||
make -C security images
|
||||
```
|
||||
|
||||
Installation requires Python, uv, Go, and network access. The Trivy/Gitleaks binary installer supports Linux amd64 and arm64. Tools stay in `security/.bin/`, `.tools/`, and `.cache/`; installation does not change global tools. The installer selects current stable Trivy and Gitleaks releases and verifies their downloaded archives against upstream SHA256 checksums. govulncheck is installed with `go install ...@latest`. Semgrep uses an isolated uv tool environment with Python 3.13; uv stores its managed Python under `security/.tools/python/`. Tool versions may change on a later installation; inspect installation output when reproducing a finding.
|
||||
|
||||
| Target | Scope |
|
||||
| Tool | Current scope |
|
||||
| --- | --- |
|
||||
| `filesystem` | Trivy scans repository dependencies and configuration with `trivy/filesystem.yml` |
|
||||
| `secrets` | Gitleaks scans tracked and non-ignored untracked files, plus all available Git history with `gitleaks/gitleaks.toml` |
|
||||
| `go` | govulncheck analyzes the backend's use of known vulnerable Go code |
|
||||
| `semgrep` | Local rules in `semgrep/frontend.yml` and `semgrep/python.yml` inspect frontend and ML source |
|
||||
| `rule-test` | Semgrep fixtures check expected matches and non-matches for the local rules |
|
||||
| `test` | Runs Semgrep rule fixtures and tests for installer integrity, Gitleaks input and report handling, govulncheck failure status, and stale reports |
|
||||
| `check` | Runs filesystem, secrets, Go, and Semgrep checks; attempts every check and returns failure if any fails |
|
||||
| `images` | Builds backend, frontend, and ML images, then scans each exact local image ID with Trivy |
|
||||
| Trivy filesystem | Repository dependencies, lockfiles and configuration |
|
||||
| Gitleaks | Tracked and non-ignored files, complete available Git history |
|
||||
| govulncheck | Use of vulnerable code in `backend/` |
|
||||
| Semgrep | Local rules for `frontend/src/` and `ml/src/` |
|
||||
| Trivy images | Exact local backend, frontend and ML image IDs |
|
||||
|
||||
Gitleaks requires a full Git checkout. A missing repository or shallow history fails the check rather than silently omitting history. Its current-file scan uses tracked files and untracked files that Git does not ignore. Tracked ignored files remain in the scan, while ignored local files such as `.env` stay out of it. Deleted tracked paths and symlinks are omitted from the current scan; symlink targets are never followed or read. The history scan still covers every ref, including values committed before a file was ignored or removed. Gitleaks copies the current input set to an owner-only temporary directory and fails if either scanner fails or its JSON report is missing or invalid. Reports redact detected secret values. Developer tool caches and build output are excluded where configured; application lockfiles remain scan inputs. Trivy also recognizes `requirements-*.txt`, including `backend/requirements-quality.txt` and `scripts/requirements-codegen.txt`.
|
||||
These checks do not include separate runner/labd Go modules or images. The backend Go linter also runs gosec. Image checks need Docker; installation needs network access, Python, uv and Go. Tools are installed locally, and current versions are recorded with reports.
|
||||
|
||||
Image checks require Docker. The backend build context is `backend/`; frontend and ML use the repository root. Images are tagged `lincodex-security-<service>:local` and resolved to image IDs before scanning. This command does not start containers or publish images. Scanning frontend source dependencies remains necessary because the final Nginx image contains compiled assets rather than the development dependency tree.
|
||||
Trivy `HIGH`/`CRITICAL` findings, including unfixed vulnerabilities, block the check. Other scanner findings and tool errors fail too. Incomplete Git history and missing or corrupt reports are not success. Reports in `security/reports/` are local and redact secret values; review before sharing.
|
||||
|
||||
## Findings and exceptions
|
||||
CI calls the same Make targets. A workflow file does not prove a successful run on the current code; releases need evidence from the actual run. Images must be checked alongside source lockfiles: a static frontend image does not contain every development dependency.
|
||||
|
||||
Trivy findings of severity `HIGH` or `CRITICAL` fail the check, including findings without a published fix, unless an active, narrowly scoped exception applies. Gitleaks findings, configured Semgrep findings, govulncheck findings, and scanner errors also fail their targets. The existing Go lint configuration retains gosec; this complements the added checks.
|
||||
## Exceptions
|
||||
|
||||
Review the reported package, installed version, affected path, and available remediation before changing dependencies or configuration. Keep reports local: `security/reports/` is ignored. govulncheck uses text output so its native failure status is preserved. Trivy saves JSON reports and prints their tables in the check log. A scan error, missing report, or report conversion error keeps the check failing.
|
||||
[Trivy ignore](../../security/trivy/ignore.yml) contains a specific exception for `CVE-2026-93687`, `braces@3.0.3` in the frontend lockfile, until 2026-10-19. It was accepted when no fix was available; maintainers must remove it after updating or review it before expiry. It does not exclude all package versions or images.
|
||||
|
||||
One temporary exception in [security/trivy/ignore.yml](../../security/trivy/ignore.yml) was approved by the project owner on 2026-10-05: `CVE-2026-93687` for `pkg:npm/braces@3.0.3` in `frontend/pnpm-lock.yaml`. At approval, no fixed release was available; the exception unblocks dependency CI until its expiry on 2026-10-19. Project maintainers own the exception and must remove it when a fix becomes available or review it before expiry. Trivy enforces the expiry date. Only filesystem scanning uses this exception file; suppressed findings remain visible in its JSON report. Image scanning is unaffected.
|
||||
The [Gitleaks allowlist](../../security/gitleaks/gitleaks.toml) limits exceptions to exact test examples, paths and rules. Manual review is due on 2026-11-07; Gitleaks does not enforce that date. New exceptions require a specific finding, reason, owner and expiry. Do not disable scanners or hide every unfixed vulnerability to make CI pass.
|
||||
|
||||
Eight Gitleaks exceptions cover exact public API examples, test fixtures, a release-manifest fixture, and a fixed Redis rate-limit key prefix. Each requires the matching rule ID, repository path, and complete finding text. Project maintainers own them. Manually review or remove them by 2026-11-07; Gitleaks does not enforce that review date. See the official [Gitleaks configuration reference](https://github.com/gitleaks/gitleaks#configuration) for allowlist behavior.
|
||||
## Data and network boundaries
|
||||
|
||||
For any further exception, scope it to the specific finding and affected input, record the reason, owner, and expiry, and have the change reviewed. The current integration does not enforce expiry uniformly across every tool, so review expiry explicitly where needed. Do not disable an entire scanner or globally suppress unfixed vulnerabilities to obtain a passing result.
|
||||
- Authorization, company membership, consent, publication and contact grants are checked on the server at each access. A cache, snapshot or hidden button is not authorization.
|
||||
- Passwords, session tokens, one-time codes, contacts, resume text and request bodies must not enter logs or metric labels. Verification mail sends the code only to its recipient; API errors do not disclose internal error text.
|
||||
- SeaweedFS stays on a separate internal network; browsers receive neither S3 keys nor direct bucket access. Some internal interfaces do not enforce S3 authentication, so network membership is tightly limited.
|
||||
- Secrets belong in the local environment or secret files, not Git. Nginx does not publish readiness, metrics or administration interfaces.
|
||||
|
||||
## Outbound requests and ML
|
||||
|
||||
- GitHub. Project repository checks call only `https://api.github.com`: the profile accepts an address only as `https://github.com/<owner>/<repo>`, the owner and name are checked against the GitHub patterns and escaped into the path, the base origin is fixed in code (tests replace it only inside the package), no proxy from the environment is used, TLS 1.2+, connect and response timeouts, a redirect is followed only to the same origin (at most three), responses are capped at 1 MiB and the README at 64 KiB. User input therefore cannot point the server at another host (SSRF). The checks are off by default (`GITHUB_REPOSITORY_CHECKS_ENABLED`), a repeated check is limited per candidate (`REPOSITORY_CHECK_INTERVAL`), and the GitHub limit is respected from its headers.
|
||||
- Token. `GITHUB_TOKEN` is optional, needs read access to public data only, and is sent only to `api.github.com`; it never reaches logs, errors, jobs, or the database. The check log carries the job id, attempt, state, and error class, never the repository; the job key and payload carry only a digest of the repository.
|
||||
- GitHub data. The description, topics, languages, and README text are untrusted data: the README becomes plain text, is stored only for a public repository, is used only for ranking, and is never shown, let alone as HTML. The repository address and owner never reach an organization, neither in the card, nor in the explanation, nor after C4.
|
||||
- ML. Every route of the service except `/healthz` and `/readyz` requires `Authorization: Bearer <token>`: a shared random token of at least 32 printable characters (`ML_SERVICE_TOKEN` in the backend, `ML_SERVICE_TOKEN` or `ML_SERVICE_TOKEN_FILE` in the service) is compared in constant time and never reaches a log, a response, or an error message; a missing or wrong token answers 401 `unauthenticated`, and the request is refused before its body is read. Without a token the service answers loopback callers only, and the entry point `python -m lincodex_ml.serve` refuses to listen on a non-loopback address; the backend does not enable semantic matching without a token. In Compose the backend reaches the service over the network (`http://ml:8000`) and the host port is loopback; on a GPU host it listens on a private LAN address without TLS, so restrict the port to the app host address with host or network rules. `/metrics` requires the token too. The backend sends ML only the texts of the published card and of the organization's need, with no contact and no private profile. The weights are pinned by lock files with SHA-256, no remote model code is executed, no pickle is loaded, and the service runs offline.
|
||||
GitHub checking is disabled by default. It accepts only public `https://github.com/<owner>/<repo>` links, calls the fixed `api.github.com` origin, and bounds redirects, time and response size. An arbitrary URL cannot become a network destination. README and metadata remain untrusted data; they are not executed or rendered as user HTML. Tokens stay out of jobs and logs.
|
||||
|
||||
## CI and limits
|
||||
Backend sends ML only the allowed card and hiring-need projections, without contacts or private profiles. Every ML route except `/healthz` and `/readyz` requires a bearer token; without one, the service accepts loopback clients only. `/metrics` uses the same token, but the current Prometheus ML scrape does not yet send it. Restrict ML port access across hosts: a token does not encrypt HTTP traffic.
|
||||
|
||||
CI runs `make -C security test check` for source checks and `make -C security images` for images, and includes both jobs in its required aggregate result. Reports are uploaded as artifacts with a 14-day retention period, including when checks fail. Gitleaks redacts secret values, but reports can still reveal repository paths and dependency details; restrict artifact access accordingly.
|
||||
|
||||
The local Semgrep rules are a bounded frontend/ML rule set, not a complete application audit. Scanner results depend on the actual checkout, rule versions, vulnerability databases, build inputs, and time of execution. Checked-in workflows do not prove that a GitHub run occurred or that the current tree is free of findings. Record actual results when preparing a release; see [TESTING.md](TESTING.md) for other validation boundaries.
|
||||
Model files are pinned by SHA-256 and loaded locally; remote model code and pickle are not executed. Model output is data, not an instruction to run a command, use a tool or change permissions.
|
||||
|
||||
## Code runner VM
|
||||
|
||||
The code runner executes untrusted candidate code, so production runs it only in the LXD VM `lincodex-runner` (see [DEPLOY.md](DEPLOY.md#production-the-runner-vm)). The boundary has three layers: nsjail with seccomp, namespaces, cgroup v2 limits, and no network for the program; a separate guest kernel; and the bridge ACL, which lets only the app network and the host side open TCP 8443 and drops every connection the guest starts. The VM holds only its own TLS pair and API token. The CA key and the database, mail, storage, and identity secrets never enter it, and it has no shared folder, no Docker socket, and no guest API (`security.devlxd=false`).
|
||||
Production runs the runner in a dedicated VM. Inside it, nsjail restricts programs through namespaces, seccomp, cgroup v2 and no network. The VM receives no database, mail, storage or identity secrets, shared directories or Docker socket. TLS and a token protect the API; network ACLs restrict access and guest-initiated connections.
|
||||
|
||||
`make -C deploy check-runner-vm` checks the VM script without LXD. On the app host, `make -C deploy runner-vm-check` checks the running VM and `make -C deploy runner-vm-a16` runs the hostile-program suite in it. These checks do not cover vulnerabilities of the kernel, QEMU, KVM, nsjail, or LXD, side channels, or the host itself: the `lxd` group is equivalent to root on the host, and its members can open a root shell in the guest through the LXD agent. The token is a shared secret without automatic rotation: to replace it, remove `api-token` from the secrets directory, run `runner-vm-secrets` and `runner-vm-install`, and give the backend the new value. The VM has no monitoring yet.
|
||||
`make -C deploy check-runner-vm` checks configuration without starting a VM. Live VM and isolation checks run separately as described in [DEPLOYMENT.md](DEPLOYMENT.md) and [TESTING.md](TESTING.md). They do not establish that the kernel, hypervisor or nsjail has no vulnerabilities. A privileged development container is not the production boundary; automatic token rotation and VM monitoring are not connected yet.
|
||||
+99
-670
@@ -1,715 +1,144 @@
|
||||
# Checks and quality evaluation
|
||||
# Testing
|
||||
|
||||
Routine checks prove individual code properties. They do not establish ranking accuracy, grade validity, production latency, or complete product readiness.
|
||||
[Русский](../ru/TESTING.md)
|
||||
|
||||
Choose checks for the change. Unit tests cover rules, integration tests exercise real dependencies, and browser E2E tests exercise user actions. Run commands from the repository root.
|
||||
|
||||
## Commands
|
||||
|
||||
Use the root Make targets:
|
||||
| Area | Command | Requirements |
|
||||
| --- | --- | --- |
|
||||
| Backend, fast tests | `make -C backend test-fast` | Go |
|
||||
| Backend, race | `make -C backend test` | Go and a C toolchain |
|
||||
| Backend, integration | `make -C backend test-int` | Go, Python 3, Docker |
|
||||
| Frontend | `make -C frontend check` | Node.js, pnpm, installed dependencies |
|
||||
| ML API | `make -C ml verify` | Python, uv, installed dependencies |
|
||||
| Contracts | `make -C api check` | Installed API tools |
|
||||
| OpenAPI 3.2 generators | `make -C api check-toolchain` | Go, frontend, and ML toolchains |
|
||||
| Technical smoke | `make -C deploy smoke` | Docker Compose |
|
||||
| Browser E2E | `make -C deploy test-e2e` | Docker Compose, frontend dependencies |
|
||||
| E2E with mail | `make -C deploy test-e2e-registration` | The same dependencies |
|
||||
| Documentation | `make docs-check` | Python 3 |
|
||||
|
||||
make test
|
||||
make check
|
||||
make verify
|
||||
make docs-check
|
||||
`make test` runs service tests. `make check` adds formatting, lint, types, builds, and configuration checks. `make verify` also generates code and checks drift, the OpenAPI toolchain, backend race tests, integration tests, and smoke.
|
||||
|
||||
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.
|
||||
Playwright, security scanners, real ML models, and the runner sandbox have separate checks. Passing `verify` does not replace them.
|
||||
|
||||
Useful focused commands:
|
||||
## Backend: unit and race
|
||||
|
||||
| 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) |
|
||||
Tests next to source files cover domain/usecase behavior and adapters without external infrastructure. Use configured mockery mocks or small behavior-specific fakes for ports.
|
||||
|
||||
make -C deploy test-e2e currently runs a technical browser suite, not a business-flow suite; see [Browser E2E suite](#browser-e2e-suite).
|
||||
```sh
|
||||
make -C backend mocks
|
||||
make -C backend test-fast
|
||||
make -C backend test-race
|
||||
```
|
||||
|
||||
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.
|
||||
For a changed workflow, cover success, domain rejection, and dependency failure. Concurrent operations need version, retry, and cancellation checks. Assert results and persisted effects rather than incidental internal call order.
|
||||
|
||||
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.
|
||||
## Integration tests
|
||||
|
||||
## Current scaffold coverage
|
||||
Tests in `backend/integration_test/` use the `integration` build tag and Testcontainers with real PostgreSQL, Redis, SeaweedFS, and explicitly selected Kafka.
|
||||
|
||||
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.
|
||||
```sh
|
||||
make -C backend test-int-compile
|
||||
make -C backend test-int-list
|
||||
make -C backend test-int
|
||||
```
|
||||
|
||||
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.
|
||||
`test-int-compile` compiles without containers; `test-int-list` lists selected top-level tests. Neither command proves that scenarios passed. `test-int` requires working Docker and fails if it is unavailable.
|
||||
|
||||
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.
|
||||
### Shared bootstrap
|
||||
|
||||
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.
|
||||
In `bootstrap_test.go`, `bootstrap(t)` starts PostgreSQL, Redis, and SeaweedFS, applies migrations, and returns configuration and clients. Select only what a test needs, for example `bootstrap(t, postgresService)` or `bootstrap(t, postgresService, kafkaService)`.
|
||||
|
||||
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.
|
||||
Each call owns its containers and dynamic ports. `t.Cleanup` releases resources, including after startup failures. Call bootstrap in a parent test and share its environment with subtests; keep neighboring tests' data isolated.
|
||||
|
||||
Shared helpers create pools, separate databases, and Kafka topics. Use them instead of duplicating container setup. Add the HTTP server and domain fixtures for the specific scenario.
|
||||
|
||||
For SQL, check real transactions, constraints, and migrations. For outbox and events, check repeated delivery and recovery after failure. For data access, cover allowed requests, another account/organization, and revoked permission.
|
||||
|
||||
`TestCompanyQuota`, `TestHoldings` and the holding migration test check real PostgreSQL quotas: window boundaries, retries, the shared E0 pool, concurrency, policy changes and guarded rollback. Separate HTTP tests cover invitation sending, company isolation and immediate contact closure after revocation.
|
||||
|
||||
### Shards
|
||||
|
||||
`backend/scripts/run-integration-suite.py` discovers tests and distributes a sorted list. A top-level test and all its subtests stay in one shard. Indexes start at 1; set both variables together.
|
||||
|
||||
```sh
|
||||
TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 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
|
||||
make -C backend test-scripts
|
||||
```
|
||||
|
||||
With no variables, the whole suite runs. CI uses two shards. `test-scripts` checks distribution coverage, test selection, and failure propagation. Distribution is deterministic but does not balance individual test durations.
|
||||
|
||||
## Frontend
|
||||
|
||||
Vitest runs in Node and checks logic, data transformations, and components in its available environment. Browser specs in `frontend/e2e/` are excluded from this run.
|
||||
|
||||
```sh
|
||||
make -C frontend test
|
||||
make -C frontend typecheck
|
||||
make -C frontend check
|
||||
```
|
||||
|
||||
`check` includes formatting, ESLint, Stylelint, types, Vitest, FSD boundaries, and a production build. MSW and replaced API responses verify frontend behavior, not server authorization or persistence.
|
||||
|
||||
## 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
|
||||
make -C frontend install
|
||||
make -C deploy test-e2e
|
||||
make -C deploy test-e2e-registration
|
||||
```
|
||||
|
||||
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`.
|
||||
Both commands create a throwaway Compose project with its own secrets and volumes. The browser reaches the application through Nginx. The script removes test containers and volumes on exit; results remain in `frontend/test-results/e2e/`.
|
||||
|
||||
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 30-minute budget of the whole suite between shards with a floor of 10 minutes: an unsharded local run gets 30 minutes, each of the two CI shards gets 15.
|
||||
Ordinary `test-e2e` disables mail. It runs technical and available UI scenarios while skipping tests that require mail and special fixtures. `test-e2e-registration` enables a local Resend-compatible receiver and synthetic data for registration and business flows. It does not send mail through real Resend.
|
||||
|
||||
## Consent ledger tests
|
||||
The suite contains two kinds of checks:
|
||||
|
||||
Unit tests (`make -C backend test`) cover the ledger rules without a database:
|
||||
- Real backend flows: registration, profile, questionnaire, organizations, hiring needs, search, invitations, and the minimal path in `acceptance-path.spec.ts`. The mail stand enables their fixtures.
|
||||
- API replacement through `page.route`: screen states, errors, conflicts, and parts of assessment and accessibility scenarios. These tests verify browser behavior in the supplied state.
|
||||
|
||||
- `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.
|
||||
Playwright runs Chromium with one worker and no retries. The real-bank search runs first so other specs cannot change its results. The configuration accepts only a loopback stand address.
|
||||
|
||||
`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:
|
||||
Inspect the HTML report, trace, and screenshot on failure. Report passed, failed, and skipped counts: a green run with a required scenario skipped does not complete its acceptance. Never point E2E at a shared or production stand.
|
||||
|
||||
- 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.
|
||||
### Demonstration flow acceptance
|
||||
|
||||
`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:
|
||||
Before presenting, run `make docs-check`, `make -C deploy check`, smoke and the mail-enabled E2E suite. `acceptance-path.spec.ts` must pass the full test with a `synthetic_demo` category, publication, search with an explanation, invitation, C4 and contact disclosure; repeated acceptance must not create duplicates, and revocation must close contact access. A skipped spec is not acceptance.
|
||||
|
||||
- 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.
|
||||
Match the evidence to the deployed commit or images. A local mail fixture does not demonstrate real Resend delivery, local Nginx does not prove external HTTPS, and a synthetic bank does not establish grade accuracy. For a release, repeat smoke and E2E on the fixed images as described in [DEPLOYMENT.md](DEPLOYMENT.md).
|
||||
|
||||
`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.
|
||||
## ML and models
|
||||
|
||||
## Organization tests
|
||||
`make -C ml verify` checks formatting, Ruff, mypy, pytest, packaging, the contract, and Pydantic model drift. Ordinary tests are separate from slow checks using real weights.
|
||||
|
||||
Unit tests (`make -C backend test`) cover the organization rules without a database:
|
||||
```sh
|
||||
make -C ml model-fetch
|
||||
make -C ml test-model
|
||||
```
|
||||
|
||||
- `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.
|
||||
`model-fetch` downloads pinned Giga and Qwen3 embedding files and checks SHA-256; it requires access to the weight source and disk space. `test-model` compares real models with research vectors; set `ML_TEST_DEVICE=cuda` for a GPU. This checks inference reproducibility, not matching quality for real candidates.
|
||||
|
||||
`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:
|
||||
## Runner and labs
|
||||
|
||||
- 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.
|
||||
`make -C runner check` and `make -C labd check` check the Go modules. Their unit tests need neither a running sandbox nor LXD.
|
||||
|
||||
`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.
|
||||
Real runner, isolation, and lab checks run separately in environments intended for testing. [runner/](../../runner/README.en.md) and [labd/](../../labd/README.en.md) describe their requirements and commands. Results from a local development container do not establish isolation of the deployed runner.
|
||||
|
||||
`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.
|
||||
## Contracts, infrastructure, and security
|
||||
|
||||
`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.
|
||||
After an API change, run `make generate`, check its consumers, and run `make check-generated`. For intentional output updates, review and commit the expected diff together with its source.
|
||||
|
||||
## Candidate profile tests
|
||||
`make -C deploy check` validates configuration and supporting scripts. `smoke` checks infrastructure readiness and HTTP routes; `perimeter-test` checks Nginx rules using throwaway containers. Neither replaces a business flow. `make -C observability check` validates monitoring configuration.
|
||||
|
||||
Unit tests (`make -C backend test`) check the profile rules without a database:
|
||||
`make security` checks dependencies, source, and secrets; `make security-images` builds and scans images. [security/](../../security/README.en.md) explains tool installation and reports.
|
||||
|
||||
- `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.
|
||||
## Reporting checks
|
||||
|
||||
`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`:
|
||||
Record the command, checked commit or diff, outcome, and relevant limitations. Preserve a reproducible failure case without secrets. Assessment validity, matching quality, and performance need separate datasets, methods, and measurements.
|
||||
|
||||
- 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.
|
||||
|
||||
`TestAssessmentPracticeRunnerProtocol` in `backend/integration_test/assessment_practice_runner_test.go` uses the same harness with the real queue worker and the real TLS 1.3 client of the code runner (`adapter/secondary/code_runner`), against a local fixture of the runner protocol (`practice_runner_fixture_test.go`: an `httptest` TLS server with the bearer token, PUT and GET of `/v1/runs/{id}`, one run per run ID, and 422 for another payload). The fixture does not run code: it recognizes one Python and one Go program that print the sum of two integers and compares their output with the expected output of each test, and a failed public test carries the program output as its diagnostic. The production runner VM is not called. Sequential cases:
|
||||
|
||||
- A Python and a Go debug run of two candidates finish through the API. Each candidate's own test expects a wrong sum, so the diagnostic shows what that program printed: `got 42` for the Python submission and `got 123` for the Go one, never the other's. The job keeps the `runner_run_id` of the run, and the fixture started that run from the source of that submission. The wire request has the fields `groups`, `language`, `limits`, and `source` only, the groups `public` and `custom` and no hidden group, headers limited to transport and the service token, a version 8 run ID that is none of the user, attempt, practice, or submission IDs, and none of those IDs, the email, or the session cookie in the path, headers, or body. Another candidate reads the run as 404.
|
||||
- A final solution whose response is cut after the runner accepted the run (the connection is dropped) is retried after the backoff on the same run key: the runner holds one run, the job is `finished` with one counted attempt and generation 0, exactly one final result is stored, and its `runner_run_id` is that run. The wire request of a final solution has the groups `hidden-1` to `hidden-3` only.
|
||||
- A debug run whose answer outlasts the request timeout ends the try as a retry, the run reads as `queued`, and the repeat joins the run the runner already holds.
|
||||
- A worker that died mid-run (its pool is closed) is replaced by a worker with a new client built from the same settings after the lease expires. The new client derives the same run ID, so the runner still holds one run, one takeover is counted, and one result and one `runner_run_id` are stored.
|
||||
- With the runner stopped, a debug run stays `queued` while tries remain, then reads as `failed` with `sandbox_error`, no result, no `runner_run_id`, and a finished time. The attempt state and version, the result count, and the confirmed categories of the candidate are the same before and after, and the practice is still `not_started`. A new debug run on the same practice is accepted and finishes once a working runner is back. A final solution with the stopped runner makes the practice `failed` with `sandbox_error` and no result, leaves the candidate state unchanged, and is accepted again and finished by a working runner. In the end no `runner_run_id` belongs to two jobs.
|
||||
|
||||
The fixture proves the protocol path and the storage and retry rules; it does not prove that a real sandbox compiles or runs Python and Go or the timing of a real runner.
|
||||
|
||||
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, a shutdown gives the job back uncounted, and a finished run without a valid run ID is retried and stores no result while a valid one is stored with the result. `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.
|
||||
An old result does not verify a new commit. Health checks do not prove business flows, synthetic categories do not establish grade validity, and a replaced dependency does not prove the real service works.
|
||||
+103
-1283
File diff suppressed because it is too large.
Load diff
@@ -1,47 +0,0 @@
|
||||
# Квоты компании
|
||||
|
||||
Резервирование квот компании реализовано в домене, usecase `companyquota` и адаптере PostgreSQL. Для резервирования приглашений и просмотров карточек кандидатов используется порт, связанный с транзакцией. Приглашение тратит одно место недельной квоты при отправке (`SendOrganizationInvitation`): черновик квоту не тратит, а повтор отправки того же приглашения не тратит второе место. Уход приглашения из ожидания ответа (отказ, истечение, принятие) освобождает место в пределе ожидающих приглашений на потребность, но не возвращает недельную квоту; см. [Предел ожидающих, пауза и истечение](ARCHITECTURE.md#предел-ожидающих-пауза-и-истечение).
|
||||
|
||||
## Политика и доверенный уровень компании
|
||||
|
||||
Каждая операция один раз получает снимок часов приложения в UTC и читает действующую версию `ProductPolicyKey`. Лимиты берутся из этой версии политики. Подключенная демо-политика сейчас включает для E0 10 приглашений за скользящие 7 дней и 50 уникальных просмотров карточек кандидатов за скользящие 24 часа. Для E1 заданы 40 приглашений за 7 дней и 150 уникальных просмотров за 24 часа.
|
||||
|
||||
Для E2 заданы лимиты 100 приглашений и 400 уникальных просмотров, но в подключенной демо-политике этот уровень выключен. E2 можно использовать только если действующая политика включает его, а загруженная из хранилища компания имеет соответствующий подтвержденный уровень и основание. Для E3 квотного уровня нет, поэтому операция запрещается. Вызывающий код не может выбрать или повысить уровень.
|
||||
|
||||
Снимок квоты содержит версию политики, сохраненные уровень и основание проверки компании, а также время изменения проверки. Перед записью адаптер PostgreSQL блокирует компанию и повторно проверяет эти значения и действующую версию политики. Если данные изменились, он возвращает `outbound.ErrCompanyQuotaSnapshotChanged` и не записывает использование. Вызывающий код должен перечитать политику и компанию, затем повторить всю транзакцию.
|
||||
|
||||
## Резервирование и порядок транзакции
|
||||
|
||||
Вызывайте `companyquota.Service.ReserveInvitation` или `ReserveCardView`, передавая репозитории текущего `outbound.UnitOfWork`. Репозиторий из `UnitOfWork.CompanyQuotas()` привязан к транзакции и не должен сохраняться после нее. Резервирование квоты и связанное с ним бизнес-изменение выполняются в одной транзакции, чтобы откат отменял обе записи. Сервис создается с часами приложения и один раз читает действующую политику на операцию.
|
||||
|
||||
Проверка доступа к компании остается ответственностью вызывающего кода. В той же транзакции нужно повторно проверить активное членство и права владельца. Писатели соблюдают такой порядок блокировок: компания, для компании на E0 - ее холдинг (см. [Пул холдинга](#пул-холдинга)), активное членство, запись приглашения или видимости, затем использование квоты. Адаптер квот первым блокирует строку компании, а для компании на E0 сразу после нее - строку холдинга; вызывающий код может повторно заблокировать эти строки в этой транзакции. Не меняйте этот порядок на обратный.
|
||||
|
||||
Блокировка компании сериализует параллельные резервирования одной компании, а блокировка холдинга сериализует общий пул E0. Пока они удерживаются, адаптер проверяет существующую запись, считает активное окно и добавляет или обновляет использование. Решение либо разрешает операцию, либо запрещает ее; повторное использование означает разрешение. При отказе запись использования не создается, а `RetryAt` содержит ближайший момент освобождения места по истечении активной записи.
|
||||
|
||||
## Окна и повторы
|
||||
|
||||
Приглашение определяется парой `(organization_id, invitation_id)`. Повтор с тем же ID разрешается как уже учтенный, даже если ключ идемпотентности запроса другой или скользящее окно уже прошло. Запись использования остается на срок жизни компании, поэтому удаление приглашения в будущем не вернет квоту.
|
||||
|
||||
Просмотр карточки определяется парой `(organization_id, candidate_id)`. Повторный просмотр того же кандидата в активном окне не расходует еще один слот уникального просмотра. Время `last_seen_at` обновляется монотонно: часы приложения, переведенные назад, не уменьшают сохраненное время.
|
||||
|
||||
Для активного окна используется строгое сравнение с границей. Запись ровно в момент `now - window` уже истекла. Использование приглашений считается за скользящие 7 дней, просмотры карточек - за скользящие 24 часа. Лимиты общие для запросов и пользователей компании; исключение - компания на E0, которая делит свои лимиты с остальными E0-компаниями своего холдинга (см. [Пул холдинга](#пул-холдинга)).
|
||||
|
||||
Истекшие записи просмотров удаляются партиями максимум по 100 только после успешного разрешенного резервирования. Истечение окна логическое; очистка не обещает удаление в точно заданный момент. При удалении аккаунта кандидата его запись просмотра удаляется каскадно. При удалении компании удаляются обе таблицы квот. Для использования приглашений нет внешнего ключа на приглашение, поэтому будущее удаление приглашения не сможет удалить ключ идемпотентности.
|
||||
|
||||
## Пул холдинга
|
||||
|
||||
Холдинг объединяет компании, созданные одним аккаунтом-основателем; его хранит таблица `holdings`, миграция `00041_create_holdings.sql`. `CreateWithOwner` сохраняет каждую новую компанию в холдинге аккаунта-владельца в той же транзакции. Холдинг аккаунта создается с его первой компанией, а параллельные создания одного аккаунта дают один холдинг: вставка игнорирует уже существующий ключ основателя, а затем транзакция читает сохраненный холдинг. Холдинг не несет ни профиля, ни права; его единственный эффект - общий пул E0.
|
||||
|
||||
Лимиты E0 (в подключенной демо-политике 10 приглашений за 7 дней и 50 уникальных просмотров карточек за 24 часа) общие для E0-компаний одного холдинга. Резервирование E0 считает строки использования всех компаний холдинга, чей уровень проверки в момент подсчета равен E0. Каждая строка использования остается за компанией, которая ее потребила, а использование компании, которая уже не E0, выходит из общего пула. Компания на E1 и выше считает только свое использование и имеет собственный пул, поэтому ее использование не входит в пул E0.
|
||||
|
||||
Идемпотентность остается на уровне компании. Тот же ID приглашения или повторный просмотр одного кандидата той же компанией внутри окна не списываются второй раз. Один кандидат, просмотренный двумя компаниями одного холдинга, - два списания общего пула.
|
||||
|
||||
Блокировки: для компании на E0 `CompanyQuotaRepository.LockOrganization` и каждое резервирование берут строку холдинга с `FOR NO KEY UPDATE` сразу после строки компании. Поэтому резервирования одного пула идут друг за другом, а второе считает использование, которое первое уже зафиксировало: подсчет начинается после блокировки холдинга. Каждый писатель берет блокировку компании раньше блокировки холдинга, а ни один код не берет блокировку компании, удерживая блокировку холдинга, поэтому блокировка холдинга не добавляет цикл в документированный порядок. Цена: поиски E0, чтения карточек и черновики или отправки приглашений одного холдинга ждут друг друга, пока открыты их транзакции; поиск держит блокировку на всю транзакцию ранжирования.
|
||||
|
||||
Миграция дает каждому основателю один холдинг: основатель компании - аккаунт ее самого раннего членства, то есть владельца, созданного вместе с компанией, а холдинг датируется первой компанией. Откат отказывает, пока холдинг объединяет несколько компаний, потому что схема без холдингов не сохранила бы их общий пул E0. Слияние холдингов разных владельцев не входит в объем.
|
||||
|
||||
## Проверки
|
||||
|
||||
`TestHoldings` в `backend/integration_test/holding_test.go` проверяет общий пул E0 двух компаний одного аккаунта при отдельном пуле компании на E1, отдельный холдинг второго аккаунта, выход использования из пула при повышении компании, параллельные резервирования двух компаний, которые никогда не превышают общий лимит, параллельные создания, заканчивающиеся одним холдингом, и отказ создания с неизвестным основателем. `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` в `backend/integration_test/holding_migration_test.go` проверяет заполнение и защищенный откат миграции.
|
||||
|
||||
`TestCompanyQuota` в `backend/integration_test/company_quota_test.go` проверяет настоящий адаптер PostgreSQL на изолированной базе. Тест покрывает параллельные резервирования E0, границы E0 и E1, точные границы окон и `RetryAt`, повтор того же ID приглашения, повторный просмотр в рамках компании, монотонное обновление, откат, изменение снимка политики или компании, разрешенное резервирование при включенной E2 и сохраненной проверке компании, отказ для поддельного снимка E2 при сохраненном E0, отказ для выключенной E2 и E3, а также очистку после удаления кандидата. Проверки доставки приглашения нет, поскольку этот процесс пока не реализован.
|
||||
-1049
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,276 @@
|
||||
# Запуск и развертывание
|
||||
|
||||
Команды выполняются из корня репозитория. Нужны Docker с Compose, GNU make, Python 3 и OpenSSL. Для Go-команд оператора нужен toolchain из `backend/go.mod`; они читают экспортированные переменные окружения, а не `.env` автоматически. Настройки описаны в [.env.example](../../.env.example); значения по умолчанию и проброс в контейнеры - в [deploy/Makefile](../../deploy/Makefile) и [Compose](../../deploy/docker/).
|
||||
|
||||
## Запуск MVP: быстрый старт
|
||||
|
||||
Создайте `.env`, если его еще нет: скопируйте `.env.example`, замените `replace-this-*` и заполните `IDENTITY_KEY_SECRET` случайным секретом (`openssl rand -base64 48`). Пароль PostgreSQL входит в URL подключения, поэтому используйте URL-safe символы, например hex. Файл хранит секреты и не коммитится.
|
||||
|
||||
```sh
|
||||
make -C deploy config
|
||||
make -C deploy up
|
||||
curl --fail http://localhost:8080/api/v1/healthz
|
||||
```
|
||||
|
||||
`config` проверяет примеры настроек, а `up` читает настоящий `.env`. Основной проект `app` запускает frontend Nginx, Go backend, PostgreSQL, Redis, SeaweedFS и Kafka. Backend применяет миграции при старте. Чистая база не содержит банка заданий и подготовленных аккаунтов: для показа продукта используйте [демонстрационный стенд](#изолированный-демонстрационный-стенд).
|
||||
|
||||
| Контур | Запуск | Адрес по умолчанию |
|
||||
| --- | --- | --- |
|
||||
| Основной | `make -C deploy up` | `http://localhost:8080` |
|
||||
| Синтетическая демонстрация | `make -C deploy demo-seed DEMO_MODE=isolated` | `http://localhost:8090` |
|
||||
| ML, после core | `make -C deploy ml-up` | `127.0.0.1:8000` |
|
||||
| Мониторинг, после core | `make -C deploy monitoring-up` | Grafana: `127.0.0.1:3000` |
|
||||
| Dev-исполнитель кода | `make -C deploy runner-dev-up` | `127.0.0.1:8070` |
|
||||
|
||||
ML, мониторинг, исполнитель и labd не запускаются с основным стеком. Имя проекта передавайте одинаково всем целям: например, `APP_PROJECT=my-app` для `up`, `logs` и `down`. Make не берет имя проекта из `.env`.
|
||||
|
||||
## Core сервис
|
||||
|
||||
`make -C deploy logs` показывает журналы. `make -C deploy down` сохраняет именованные тома; остановите мониторинг перед core. PostgreSQL, SeaweedFS и Kafka хранят данные в томах, Redis работает как ограниченный по памяти кеш без persistence. Удаление томов уничтожает данные. Один узел Compose не обеспечивает HA или внешнюю резервную копию.
|
||||
|
||||
### Публичный периметр и адрес клиента
|
||||
|
||||
Единственная HTTP-точка входа - frontend Nginx: SPA и `/api/v1/` на одном origin. Открывайте ровно `APP_PUBLIC_URL`; небезопасные запросы проверяют Origin и, для сессии, CSRF-токен. Для локального HTTP используйте `localhost`, для публичного имени - HTTPS: cookie сессии имеет флаг `Secure`.
|
||||
|
||||
Оставляйте `APP_HTTP_BIND=127.0.0.1` локально или задавайте приватный адрес туннеля. Не публикуйте backend, `/metrics`, базы, брокер и хранилище. Публикация порта Docker может обходить правила ufw. `TRUSTED_PROXY_CIDRS` должен доверять только frontend Nginx; при изменении `APP_SUBNET` и `APP_FRONTEND_IP` согласуйте адреса прокси и ACL.
|
||||
|
||||
### Relay outbox
|
||||
|
||||
Backend публикует outbox в Kafka и запускает обработчики событий и задания по сроку в одном процессе. Настройки `RELAY_*`, `CONSUMER_*` и `JOBS_*` определены в [backend/config](../../backend/config/). Добавление переменной в `.env` действует на контейнер только при ее явном пробросе в Compose. Сохраняйте запас `stop_grace_period` при увеличении тайм-аутов завершения.
|
||||
|
||||
### Обработчики событий
|
||||
|
||||
В Grafana следите за отставанием outbox, ошибками обработчиков и наступившими заданиями. Dead letters смотрите в базе, Kafka lag - через CLI брокера. Доставка допускает повторы; обработчики используют дедупликацию. Смена `CONSUMER_GROUP_PREFIX` создает новые группы, читающие сохранившиеся события сначала.
|
||||
|
||||
#### Dead letters и повторный запуск
|
||||
|
||||
После устранения причины найдите запись в `consumer_dead_letters`. Для известного `event_id` можно повторно опубликовать сохраненную строку outbox, сбросив только ее `published_at`; успешные обработчики распознают дубликат. `invalid_record` так не исправляется. Перед ручной перемоткой Kafka остановите всех участников нужной группы. Подтверждение обработки находится в `consumer_processed_events`; payload и персональные данные не копируйте в журналы инцидентов.
|
||||
|
||||
### Задания по сроку
|
||||
|
||||
Состояния и ошибки хранятся в `scheduled_jobs`. После исправления причины повторяйте только конкретное задание с учетом его обработчика; не сбрасывайте всю очередь. Синхронизируйте часы backend через NTP: сроки и аренды сравниваются по часам приложения. Практика имеет отдельную очередь, описанную ниже.
|
||||
|
||||
## Почта
|
||||
|
||||
| Режим | Что требуется |
|
||||
| --- | --- |
|
||||
| `EMAIL_PROVIDER=disabled` | Ничего не отправляет; новый аккаунт останется неподтвержденным |
|
||||
| `EMAIL_PROVIDER=resend` | `RESEND_API_KEY`, `EMAIL_FROM` на подтвержденном домене, правильный `APP_PUBLIC_URL` |
|
||||
| `EMAIL_PROVIDER=smtp` | Конфигурация предусмотрена, транспорт пока не реализован: backend откажется стартовать |
|
||||
|
||||
### Доставки писем
|
||||
|
||||
Resend отправляет подтверждение адреса и поддержанные продуктовые уведомления через outbox. Ошибка транспорта не означает успешную отправку. Тест `make -C deploy test-e2e-registration` использует локальный Resend-совместимый inbox, а не настоящий аккаунт провайдера.
|
||||
|
||||
### Квоты почты
|
||||
|
||||
`EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` ограничивают получателей по UTC: по умолчанию 100 и 3000. `EMAIL_SERVICE_RESERVE_*` оставляют часть квоты для служебной почты. `EMAIL_ACCOUNT` обозначает реальный аккаунт поставщика; не меняйте его ради обхода локального учета. Значения приложения не гарантируют тариф или квоты провайдера.
|
||||
|
||||
### Шаблоны писем
|
||||
|
||||
Тексты и рендеринг находятся в `backend/internal/usecase/notification/mailtemplate/`. Передавайте только необходимые адресату данные; одноразовая ссылка и код допустимы в письме подтверждения. Ключи сервиса и данные, на которые получатель утратил права, в письмо не включаются.
|
||||
|
||||
## Изолированный демонстрационный стенд
|
||||
|
||||
```sh
|
||||
make -C deploy demo-seed DEMO_MODE=isolated
|
||||
make -C deploy monitoring-up DEMO_MODE=isolated
|
||||
make -C deploy demo-down DEMO_MODE=isolated
|
||||
```
|
||||
|
||||
Seed создает отдельный проект `lincodex-demo`, банк и аккаунты с синтетическими данными; повторный запуск идемпотентен. Локальный frontend доступен на `http://localhost:8090`; передавать `APP_HTTP_BIND` в командной строке не нужно. Цель использует корневой `.env` и `deploy/demo/demo.env`, а при отсутствии последнего - публичный пример. Логины печатает команда, пароль задает `DEMO_ACCOUNT_PASSWORD`. Для внешнего доступа выберите свой пароль и передайте его участникам отдельно.
|
||||
|
||||
Гид находится на `/demo`. Основные аккаунты: `candidate@demo.lincodex.test`, `prepared-1@demo.lincodex.test` - `prepared-6@demo.lincodex.test`, `employer-alpha@demo.lincodex.test` и `employer-beta@demo.lincodex.test`. Пройдите путь кандидата от теста до результата, затем от работодателя отправьте приглашение и примите его кандидатом с выбранными контактами.
|
||||
|
||||
`demo-reset DEMO_MODE=isolated` удаляет данные только своего проекта и заполняет его заново; цель отказывается работать при обычных аккаунтах. Не используйте стенд для реальных людей. Демонстрационные категории не откалиброваны, экспресс-прогон не присваивает грейд. Официальная интеграция ФСП не подключена.
|
||||
|
||||
### Сценарий демонстрации
|
||||
|
||||
1. Заполните профиль и анкету кандидата, пройдите тест или откройте подготовленный результат. Банк Backend Junior с Go синтетический; `demo_express` не присваивает грейд или доказательство.
|
||||
2. Выдайте C2 и опубликуйте карточку после предпросмотра. Для анонимной выдачи нужна достаточная группа: один опубликованный кандидат может не появиться в поиске.
|
||||
3. От владельца компании создайте потребность с зарплатной вилкой, найдите кандидата, откройте объяснение и отправьте приглашение.
|
||||
4. Примите его кандидатом с C4 и выбранными контактами. Проверьте чтение только этих полей компанией, затем отзовите доступ или скройте компанию и проверьте отказ.
|
||||
|
||||
Категория `synthetic_demo` демонстрирует механику, а не подтвержденное качество оценки. Встроенные тексты согласий имеют тип `demo`. Практика требует отдельного runner и подходящего банка, поэтому не заявляйте ее частью обычного демонстрационного теста. Остальные границы реализации перечислены в [ARCHITECTURE.md](ARCHITECTURE.md), приемка - в [TESTING.md](TESTING.md).
|
||||
|
||||
Регламент выступления - 10 минут; видео разрешено вместо живого показа. Прогоните рассказ по таймеру и обозначьте ограничения. По возможности сохраните стенд на период оценки; точные даты и включение вопросов жюри в десять минут требуют уточнения.
|
||||
|
||||
### Демонстрационные категории на стенде
|
||||
|
||||
Seed подготавливает категории сам. При ручной настройке нужны открытая категория с опубликованным банком, демонстрационная политика, `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` и аттестация оператора:
|
||||
|
||||
```sh
|
||||
make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:maintainer'
|
||||
```
|
||||
|
||||
Команда требует `DATABASE_URL`. Аттестация закрепляет открытие категории, банк и версию политики; после их изменения повторите открытие и аттестацию. В рабочей среде с реальными кандидатами синтетические категории выключены.
|
||||
|
||||
### Политика подбора на стенде
|
||||
|
||||
На чистом стенде стартовая политика не содержит раздела `matching`. Опубликуйте его до демонстрации поиска:
|
||||
|
||||
```sh
|
||||
make -C backend policy-publish ARGS='matching --actor operator:maintainer'
|
||||
```
|
||||
|
||||
Команда требует `DATABASE_URL` и создает следующую демонстрационную версию. Seed выполняет подготовку сам. Смена политики требует повторного открытия и аттестации демонстрационных категорий; уже начатые попытки сохраняют прежнюю версию.
|
||||
|
||||
### Полоса проверки оценки
|
||||
|
||||
```sh
|
||||
make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operator:maintainer'
|
||||
```
|
||||
|
||||
Команда требует `DATABASE_URL` и показывает сигналы для ручного разбора. Они не доказывают нарушение и не снижают оценку автоматически. Метка `operator:*` нужна для аудита; доступ к базе остается границей доступа оператора.
|
||||
|
||||
### Поиск источника утечки
|
||||
|
||||
```sh
|
||||
make -C backend assessment-leak-trace ARGS='search --actor operator:maintainer --file leaked.txt'
|
||||
```
|
||||
|
||||
Нужны `DATABASE_URL` и тот же `IDENTITY_KEY_SECRET`, которым выданы попытки. Передавайте текст файлом или через `--stdin`, чтобы он не попал в историю команд. Результат и аудит не содержат исходного текста; совпадение - повод для ручной проверки, а не автоматическое решение.
|
||||
|
||||
## Отдельный ML Compose
|
||||
|
||||
ML обслуживает эмбеддинги Giga-Embeddings-instruct-480M и Qwen3-Embedding-0.6B. Образ скачивает закрепленные веса при сборке, проверяет SHA-256 и работает офлайн. Compose использует CPU, лимит 4 CPU и 8 GiB. Это отдельный проект во внешней сети core с DNS-именем `ml`.
|
||||
|
||||
1. Задайте в `.env` общий `ML_SERVICE_TOKEN` для ML и backend: не менее 32 печатных символов без пробелов.
|
||||
2. Запустите core, затем `make -C deploy ml-build` и `make -C deploy ml-up`.
|
||||
3. Дождитесь `/readyz` 200. `/healthz` проверяет процесс, а не загрузку моделей.
|
||||
|
||||
`ML_EMBEDDER=giga,qwen3` загружает обе модели; `none` оставляет сервис неготовым, `fake` предназначен для фикстур. Все маршруты, кроме health/readiness, требуют bearer-токен при его настройке. Без токена сервис допускает только loopback, а контейнер с адресом `0.0.0.0` не стартует. `ml-logs` и `ml-down` управляют этим проектом отдельно.
|
||||
|
||||
Для разработки: `make -C ml install`, `make -C ml model-fetch`, затем `make -C ml run` с `ML_EMBEDDER` и каталогами моделей в окружении. `model-fetch` скачивает около 2.2 GB весов. `make -C ml test-model` проверяет реальные модели отдельно от обычных тестов.
|
||||
|
||||
### ML-сервис на GPU-хосте
|
||||
|
||||
Используйте [шаблон systemd](../../deploy/ml-gpu/lincodex-ml.service) и [пример настроек](../../deploy/ml-gpu/ml.env.example). Сервис ожидает код в `~/lincodex-ml/app/ml`, virtualenv в `~/lincodex-ml/venv`, настройки в `~/.config/lincodex-ml/ml.env` с правами 0600. Версию Python берите из `ml/.python-version`; `make -C ml cuda-requirements` готовит закрепленные зависимости с CUDA-сборкой torch, которую нужно установить с соответствующего индекса PyTorch.
|
||||
|
||||
Подготовьте веса из lock-файлов, укажите приватный адрес, `ML_DEVICE=cuda`, dtype и лимит `ML_CUDA_MEMORY_LIMIT_MB` под ресурсы хоста. После установки юнита и настройки linger: `systemctl --user daemon-reload`, затем `systemctl --user enable --now lincodex-ml.service`. Проверяйте `/readyz`, журнал и реальные модельные тесты на целевом устройстве. Чужие замеры памяти и задержки не являются гарантией для вашего хоста.
|
||||
|
||||
Ограничьте доступ адресом backend. Сервис сам не завершает TLS: для связи через недоверенную сеть нужен защищенный канал. Нехватка CUDA-памяти дает 503 и повтор загрузки; другие постоянные ошибки загрузки при `ML_EXIT_ON_LOAD_FAILURE=true` завершают процесс для перезапуска supervisor.
|
||||
|
||||
### Семантический подбор
|
||||
|
||||
Поиск читает заранее рассчитанные векторы и не вызывает модель в HTTP-запросе.
|
||||
|
||||
1. Дождитесь готовности ML, задайте `SEMANTIC_MATCHING_ENABLED=true`, общий токен и `ML_SERVICE_URL` (по умолчанию `http://ml:8000`), повторите `make -C deploy up`.
|
||||
2. С `DATABASE_URL` стенда выполните `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:maintainer'`. Эта политика требует обе модели; вариант `semantic` использует одну Giga.
|
||||
3. Поставьте существующие данные в обработку: `make -C backend semantic-backfill ARGS='all --run initial'`. Повтор с той же меткой идемпотентен; для новой волны используйте другую метку.
|
||||
|
||||
После новой политики переоткройте и аттестуйте демонстрационные категории. При недоступных или несовместимых векторах поиск использует нейтральное `Sem=0.5` и флаг `ml_unavailable`. Проверки репозиториев GitHub включаются отдельно через `GITHUB_REPOSITORY_CHECKS_ENABLED`; это не условие запуска ML.
|
||||
|
||||
## Отдельный monitoring Compose
|
||||
|
||||
```sh
|
||||
make -C observability check
|
||||
make -C deploy monitoring-up
|
||||
make -C deploy monitoring-logs
|
||||
make -C deploy monitoring-down
|
||||
```
|
||||
|
||||
По умолчанию проект подключается к сети core. После запуска демо используйте `make -C deploy monitoring-up DEMO_MODE=isolated`, чтобы подключить его к сети `lincodex-demo`. Grafana доступна только на loopback; Prometheus, Loki, Alloy и exporters остаются внутри. Дашборды охватывают Go, PostgreSQL, Redis, SeaweedFS, хост и продуктовые метрики. Kafka пока не имеет собственного scrape. React SDK телеметрии пока не подключен. Alert rules есть, доставка уведомлений требует отдельной настройки.
|
||||
|
||||
Prometheus хранит метрики 14 дней с пределом 4 GB, Loki - логи 7 дней. В labels нельзя добавлять контакты, резюме, сырые URL или идентификаторы пользователей. Alloy получает Docker API через ограниченный socket proxy; даже read-only доступ к Docker API позволяет читать чувствительную конфигурацию контейнеров. Считайте этот контур привилегированным.
|
||||
|
||||
Роль PostgreSQL exporter создается только при первом запуске пустого тома: задайте `POSTGRES_EXPORTER_USER` и `POSTGRES_EXPORTER_PASSWORD` заранее. Для существующей базы роль нужно подготовить отдельно. `ML_METRICS_TARGET` добавляет приватный target, но текущий шаблон scrape не передает bearer-токен: защищенный ML потребует также настройки авторизации Prometheus.
|
||||
|
||||
`make -C observability verify-product-metrics` запускает одноразовые core и monitoring, проверяет метрики и отсутствие тестовых персональных данных в телеметрии, затем удаляет их. Это отдельная интеграционная проверка, не часть `check`.
|
||||
|
||||
## Edge proxy, HTTPS и туннель
|
||||
|
||||
Публичный путь: браузер -> HTTPS Nginx на edge -> приватный туннель AmneziaWG -> frontend Nginx -> Go. Шаблоны и скрипты находятся в [deploy/edge](../../deploy/edge/); основной Compose сам TLS не завершает.
|
||||
|
||||
1. Подготовьте `deploy/edge/edge.env` из примера: домен, отдельный `EDGE_LISTEN_IP`, адреса и порт туннеля. Проверьте DNS, свободные listeners и отсутствие пересечения подсетей. На общем edge-хосте сохраняйте существующие сайты и маршруты.
|
||||
2. `make -C deploy edge-config` проверяет шаблоны и `nginx -t` в контейнере; `edge-render` пишет nginx-конфиги в `deploy/edge/rendered/`. Эти цели ничего не устанавливают на хост.
|
||||
3. На edge установите HTTP-конфиг для ACME, получите сертификат certbot, затем установите HTTPS-конфиг и hook [reload-nginx.sh](../../deploy/edge/certbot/reload-nginx.sh). Проверяйте `nginx -t` перед reload и продление через `certbot renew --dry-run`.
|
||||
4. Создайте ключи туннеля через `deploy/edge/scripts/awg-keys.sh` и отрисуйте соответствующую сторону через `render.sh --params`. Файлы ключей хранятся вне репозитория с доступом только root. Подготовьте AmneziaWG и необходимые systemd drop-ins на обоих хостах.
|
||||
5. На app задайте `APP_HTTP_BIND` равным адресу его туннеля, `APP_PUBLIC_URL=https://<domain>`. Firewall разрешает core-порт только edge, а frontend доверяет forwarded headers только адресу edge. Проверьте правила с обеих сторон; Docker publish не заменяет firewall.
|
||||
|
||||
Перед открытием доступа проверьте HTTPS и цепочку сертификата, HTTP-редирект, глубокую ссылку SPA, вход и CSRF, запрет `/metrics` и административных путей. Edge заменяет forwarded headers, а не доверяет присланным клиентом. Выполните `make -C deploy check-perimeter` и `make -C deploy perimeter-test`; последний поднимает одноразовые Nginx-контейнеры.
|
||||
|
||||
Для отката храните предыдущие конфиги и сертификаты, проверяйте их перед reload. Не удаляйте чужие интерфейсы, правила firewall или конфигурацию сайтов. Проверка шаблонов не подтверждает доступность публичного домена.
|
||||
|
||||
## Изолированный хост раннера и лабораторий (LXD)
|
||||
|
||||
LXD требует Linux с KVM, места для btrfs-пула и прав оператора. Сначала проверьте [acls.sh](../../deploy/labs/acls.sh) и [lxd-preseed.yaml](../../deploy/labs/lxd-preseed.yaml) под сеть хоста, затем примените ACL перед preseed. Скрипты создают отдельные мосты runner и управления лабораториями; гостям назначаются статические адреса без NAT, DHCP и DNS. Не применяйте схему поверх чужих одноименных объектов.
|
||||
|
||||
Backend не получает сокет LXD. Группа `lxd` дает права, эквивалентные root; доступ имеют только оператор и labd. Проверьте запрет доступа гостей к core, хосту, LAN и интернету на реальном хосте: конфигурация сама по себе этого не доказывает.
|
||||
|
||||
## Исполнитель кода
|
||||
|
||||
Сервис `runner/` запускает Python и Go в nsjail с cgroup v2, seccomp и лимитами. Супервизору нужны привилегии для изоляции; код кандидата выполняется непривилегированным пользователем. История прогонов находится в памяти runner и теряется при перезапуске.
|
||||
|
||||
### Локально (только разработка)
|
||||
|
||||
`make -C deploy runner-dev-up` создает токен в `runner/.dev/api-token` и поднимает отдельный привилегированный контейнер с HTTP на loopback. Остановка: `runner-dev-down`. Этот режим запрещен на core-хосте и не входит в release. Backend требует TLS и не подключается напрямую к этому HTTP-режиму.
|
||||
|
||||
### Production: VM исполнителя
|
||||
|
||||
Используйте отдельную LXD VM с собственным ядром, без каталога core, Docker socket, секретов приложения и маршрута по умолчанию. Сеть разрешает вход к API только от app-сети и стороны хоста, а исходящие соединения гостя запрещены. Обязательны TLS 1.3 и bearer-токен. nsjail требует делегированную cgroup v2 и рабочий tmpfs с `exec,nosuid,nodev`.
|
||||
|
||||
### Шаги скрипта VM
|
||||
|
||||
На подготовленном app-хосте от участника групп `docker` и `lxd`:
|
||||
|
||||
```sh
|
||||
make -C deploy runner-vm-up
|
||||
make -C runner a16-bundle
|
||||
make -C deploy runner-vm-a16 A16_BUNDLE=/path/to/a16-bundle.tar.gz
|
||||
make -C deploy runner-vm-check
|
||||
```
|
||||
|
||||
Пакет A16 можно собрать на машине с Go и перенести на app-хост. `runner-vm-up` последовательно готовит секреты, rootfs, VM и сервис. Отдельные цели: `runner-vm-secrets`, `runner-vm-rootfs`, `runner-vm-create`, `runner-vm-install`. Секреты и отчеты находятся в `RUNNER_VM_STATE_DIR`, по умолчанию `~/lincodex-runner`, вне репозитория.
|
||||
|
||||
### Проверка на хосте приложения
|
||||
|
||||
До включения практики должны пройти A16 на целевой VM и `runner-vm-check`: TLS, токен, выполнение безвредных программ, лимиты, очистка и сетевые запреты. Неудача блокирует включение практики. После изменения ядра, runtime или настроек изоляции повторите проверки. Прошлый успешный прогон на другом выпуске не заменяет их.
|
||||
|
||||
### Клиент исполнителя кода
|
||||
|
||||
Задайте в backend `CODE_RUNNER_URL` с HTTPS, `CODE_RUNNER_TOKEN`, отдельный `CODE_RUNNER_RUN_KEY` и ровно один из `CODE_RUNNER_CA_FILE`/`CODE_RUNNER_CA_PEM`. CA-файл нужно смонтировать в контейнер вручную. При необходимости задайте `CODE_RUNNER_SERVER_NAME`; проверка сертификата остается включенной. Тайм-аут запроса задает `CODE_RUNNER_REQUEST_TIMEOUT`.
|
||||
|
||||
Без URL все остальные `CODE_RUNNER_*` должны быть пустыми; практика сообщает недоступность. Неверная конфигурация останавливает запуск. `make -C backend test-code-runner-live` проверяет клиент на подготовленном TLS-исполнителе с `CODE_RUNNER_URL`, `CODE_RUNNER_TOKEN` и `CODE_RUNNER_CA_FILE` из окружения; это не заменяет A16.
|
||||
|
||||
### Очередь практики и лимиты отладочных прогонов
|
||||
|
||||
Backend уже подключает обработчик практики и очередь PostgreSQL при наличии `DATABASE_URL` и настроенного runner. Очередь допускает один активный и десять ожидающих прогонов; Redis ограничивает отладочные запросы кандидата. Настройки `PRACTICE_*` находятся в `backend/config/`, но не проброшены обычным Compose. Сбой инфраструктуры заканчивается без оценки, а не неверным ответом; очередь наблюдается через `assessment_practice_jobs`.
|
||||
|
||||
## Лаборатории и labd
|
||||
|
||||
labd работает systemd-сервисом на app-хосте и единолично управляет LXD. Используйте [юнит](../../deploy/labs/lincodex-labd.service) и [настройки](../../deploy/labs/labd.env.example): TLS, токен, разрешенные сети, файл состояния и бюджет памяти. Сохраняйте файл состояния вместе с LXD-объектами: он нужен для восстановления и удаления лабораторий.
|
||||
|
||||
Сейчас встроенный реестр шаблонов пуст, backend не подключает адаптер labd, WebSocket-консоль отвечает 501. Для рабочего сценария нужны подготовленные образы, шаблоны и интеграция. Перед включением проверяют L2-изоляцию, MAC/port filtering, cloud-init и подлинность узлов при проверке. `make -C labd test-live` создает и удаляет лабораторию на отдельном тестовом LXD с `LABD_LIVE_SOCKET` и `LABD_LIVE_SOURCE`; на production его не запускают.
|
||||
|
||||
## Манифест выпуска
|
||||
|
||||
Для воспроизводимого выпуска нужны чистое рабочее дерево и прошедшие проверки тех же образов:
|
||||
|
||||
```sh
|
||||
make -C deploy release-build
|
||||
make -C deploy release-smoke
|
||||
make -C deploy release-e2e
|
||||
make -C deploy release-manifest RELEASE_ID=demo-stage-1
|
||||
make -C deploy release-manifest-check RELEASE_ID=demo-stage-1
|
||||
make -C deploy release-up RELEASE_ID=demo-stage-1
|
||||
make -C deploy release-manifest-verify RELEASE_ID=demo-stage-1
|
||||
```
|
||||
|
||||
Манифест в `deploy/release/<id>/` фиксирует исходники, зависимости, Compose, image ID/digest и входные данные. Один ID неизменяем; новая поставка требует нового. Артефакты локальные и не коммитятся. `RELEASE_DATA_MANIFEST` добавляет версии банка, политики и seed; отсутствие принятого банка остается явным ограничением, а не готовностью продукта.
|
||||
|
||||
`release-up` требует локальных образов и соответствующих файлов, не собирает и не скачивает их. Для другого проекта используйте тот же `APP_PROJECT` и `RELEASE_VERIFY_PROJECT`. Демонстрация из выпуска: `demo-seed DEMO_MODE=isolated RELEASE_ID=<id>`. Остановка: `release-down` с тем же ID. `release-clean` удаляет только ссылки образов, не удерживаемые манифестами.
|
||||
|
||||
Манифест не делает резервные копии данных и не разворачивает edge, GPU-хост, runner или labd. До обновления сохраните данные и конфигурацию; откат образа не отменяет миграции. План восстановления PostgreSQL и объектов SeaweedFS проверяйте отдельно.
|
||||
|
||||
## Проверки
|
||||
|
||||
| Команда | Что проверяет |
|
||||
| --- | --- |
|
||||
| `make -C deploy check` | Compose и проверки инструментов без запуска стека |
|
||||
| `make -C deploy smoke` | Состояние зависимостей и сетевые границы одноразового стека |
|
||||
| `make -C frontend install`, затем `make -C deploy test-e2e` | Браузерные сценарии на одноразовом стеке |
|
||||
| `make -C deploy test-e2e-registration` | Сценарии с локальной почтовой фикстурой |
|
||||
| `make -C observability check` | Конфигурацию мониторинга и alert rules |
|
||||
|
||||
Охват тестов и требования окружения: [TESTING.md](TESTING.md). Успешный health check не подтверждает весь бизнес-сценарий.
|
||||
+89
-229
@@ -1,251 +1,111 @@
|
||||
# Разработка
|
||||
|
||||
Эта страница описывает реализованные компоненты и команды репозитория. Текущие бизнес-сценарии перечислены ниже; целевая архитектура находится в [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||
[English](../en/DEVELOPMENT.md)
|
||||
|
||||
## Стек и источники версий
|
||||
Команды ниже выполняются из корня репозитория. Устройство сервисов описано в [ARCHITECTURE.md](ARCHITECTURE.md), запуск окружения - в [DEPLOYMENT.md](DEPLOYMENT.md), проверки - в [TESTING.md](TESTING.md).
|
||||
|
||||
| Компонент | Источник выбранной версии |
|
||||
## Инструменты
|
||||
|
||||
Версии берите из файлов, которые использует сборка:
|
||||
|
||||
| Инструмент | Источник |
|
||||
| --- | --- |
|
||||
| Go | точная версия 1.26.9 в backend/go.mod, toolchain и Go build image |
|
||||
| Node.js | frontend/.node-version |
|
||||
| Frontend dependencies | актуальные stable releases в package manifests и pnpm-lock.yaml |
|
||||
| Python и uv | версии ML toolchain и uv.lock |
|
||||
| Go | `backend/go.mod`, `runner/go.mod`, `labd/go.mod` и соответствующие Dockerfile |
|
||||
| Node.js | `frontend/.node-version` |
|
||||
| pnpm и frontend | `frontend/package.json`, `frontend/pnpm-lock.yaml` |
|
||||
| Python и uv | `ml/.python-version`, `ml/pyproject.toml`, `ml/uv.lock` |
|
||||
| Go-генераторы | Директивы `tool` и зависимости в Go-модулях |
|
||||
| Контейнеры | `deploy/docker/` и Dockerfile сервисов |
|
||||
|
||||
Frontend зависимости выбираются из актуальных stable releases; сохраняйте pnpm-lock.yaml для повторяемой установки. ML зависимости фиксируются в uv.lock, Go dependencies - в backend/go.mod. При обновлении меняйте соответствующий lock/config и запускайте checks области. Образы используют заданные moving `latest` или `alpine` tags; сверяйте ссылки в Compose/Dockerfiles и не считайте их стабильными номерами версии.
|
||||
Для контейнерных проверок нужны Docker с Compose plugin. Для race detector нужен поддерживаемый C toolchain. Сохраняйте lockfiles; при обновлении зависимости проверяйте ее потребителей. Moving tags `latest` и `alpine` могут менять содержимое образа; воспроизводимый выпуск фиксирует digest.
|
||||
|
||||
## Состояние реализации
|
||||
```sh
|
||||
make install
|
||||
make help
|
||||
```
|
||||
|
||||
Реализация MVP продолжается. Значения ниже взяты из указанных файлов; при обновлении зависимости меняйте ее источник и lockfile, затем обновляйте эту таблицу на обоих языках.
|
||||
`install` ставит зависимости API, frontend и ML и скачивает Go-модули backend, runner и labd. Он не запускает сервисы и не устанавливает Docker или системные компиляторы.
|
||||
|
||||
| Компонент | Закрепленная версия | Источник |
|
||||
| --- | --- | --- |
|
||||
| Go | 1.26.9 (директива `go`; отдельной строки `toolchain` нет) | backend/go.mod; build image `golang:1.26.9-alpine` в backend/Dockerfile |
|
||||
| Node.js | 26.11.1 | frontend/.node-version |
|
||||
| pnpm | 12.9.1 | `packageManager` в frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| React, React DOM | 19.3.0 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| React Router (`react-router-dom`) | 7.18.4 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| TanStack Query (`@tanstack/react-query`) | 5.104.1 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Zod | 4.6.5 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Vite | 8.3.2 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| TypeScript | 7.0.2 (`@typescript/native`, `tsc`); API 6.0.2 (`typescript` как alias `@typescript/typescript6`) для ESLint | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Vitest | 5.0.3 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Orval | 8.40.0 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Python | 3.14.8 (`requires-python >=3.14,<3.15`) | ml/.python-version, ml/pyproject.toml |
|
||||
| uv | 0.12.22 | `[tool.uv] required-version` в ml/pyproject.toml; `setup-uv` в .github/workflows/ci.yml |
|
||||
| FastAPI | 0.142.2 | ml/pyproject.toml, ml/uv.lock |
|
||||
| Pydantic | 2.13.5 | ml/pyproject.toml, ml/uv.lock |
|
||||
| uvicorn | 0.54.0 | ml/pyproject.toml, ml/uv.lock |
|
||||
| ogen | v1.24.0 | backend/go.mod (`require` и `tool`) |
|
||||
| sqlc | v1.31.1 | backend/go.mod (`tool`) |
|
||||
| wire (`github.com/goforj/wire`) | v1.2.0 | backend/go.mod (`require` и `tool`) |
|
||||
| mockery | v3.8.0 | backend/go.mod (`tool`) |
|
||||
| golangci-lint | v2.14.0 | backend/go.mod (`tool`) |
|
||||
| goose | v3.28.0 | backend/go.mod (`require` и `tool`) |
|
||||
| chi | v5.3.2 | backend/go.mod |
|
||||
| pgx | v5.11.0 | backend/go.mod |
|
||||
| testcontainers-go | v0.44.0, включая modules/postgres | backend/go.mod |
|
||||
| franz-go (`kgo`, `kadm`) | v1.22.1, kadm v1.19.0; producer relay outbox, участники consumer group обработчиков событий и integration tests | backend/go.mod |
|
||||
## Обычный цикл
|
||||
|
||||
Что есть сейчас:
|
||||
1. Найдите источник изменения: контракт, usecase, SQL, UI или конфигурацию.
|
||||
2. Измените исходники и добавьте проверку наблюдаемого поведения.
|
||||
3. Если затронуты входы генераторов, выполните `make generate`.
|
||||
4. Запустите проверки затронутой области; для общей сверки есть `make check`.
|
||||
5. Проверьте diff, обновите документацию на обоих языках и выполните `make docs-check`.
|
||||
|
||||
- Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет.
|
||||
- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и `identity.Credentials` подключены для регистрации и подтверждения email. Generated Go client для ML контракта есть, но в bootstrap не подключен.
|
||||
- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы продуктовых уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но отправка уведомлений еще не реализована. При `resend` backend запускает worker служебной почты identity: регистрация и повторная отправка создают письма подтверждения, привязанные к токенам; worker проверяет токен и аккаунт перед отправкой и использует шлюз квот и стабильный ключ идемпотентности. Сброс пароля пока не реализован. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем).
|
||||
- OpenAPI контракты api/core/, api/ml/ и api/runner/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). SPA использует generated API client; MSW handlers служат тестовыми данными. Реализованные формы перечислены ниже, остальные маршруты пока показывают заготовки.
|
||||
- Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`).
|
||||
- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает два продуктовых обработчика - доставки писем и inbox, а продуктовые сценарии пока не создают их события; см. [Обработчики событий](#обработчики-событий).
|
||||
- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md).
|
||||
- Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию.
|
||||
|
||||
API и SPA реализуют регистрацию, подтверждение email, вход, согласия, личный профиль и анкету кандидата, профиль компании, потребности и собственные обращения в поддержку. API также создает и возобновляет попытки оценки; прием ответов и расчет результата пока не подключены. Подбор, приглашения, раскрытие контактов и отправка продуктовых уведомлений остаются в разработке. Worker отправляет служебную почту identity через Resend; SMTP не реализован. Границы каждого сценария описаны в [backend README](../../backend/README.md) и [frontend README](../../frontend/README.md).
|
||||
|
||||
`make -C deploy test-e2e` проверяет техническую оболочку на одноразовом стеке. `make -C deploy test-e2e-registration` дополнительно проверяет бизнес-сценарии с изолированным локальным почтовым приемником и синтетическими данными; он не подтверждает доставку через реальный Resend. См. [TESTING.md](TESTING.md#браузерный-e2e-набор).
|
||||
|
||||
## Установка и цикл работы
|
||||
|
||||
Frontend проверяется компилятором TypeScript 7.0.2 (`tsc`). Пакет `@typescript/native` ссылается на него через npm alias, а `typescript` ссылается на совместимый API `@typescript/typescript6` для ESLint. Это [рекомендованная Microsoft схема совместного использования](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0): текущий typescript-eslint еще не работает с API TS7. В проверку типов входят исходники, Vite config и TypeScript-файлы `codegen/`.
|
||||
|
||||
Orval создает `frontend/src/shared/api/endpoints/` и `schemas/` без дополнительного каталога `generated/`. `client.ts` и корневой `index.ts` в `shared/api/` поддерживаются вручную. Generated MSW handler проверяется вместе с generated client в Node-тесте. После Orval шаг `frontend/codegen/mock-patterns.ts` заменяет в MSW-моках `faker.helpers.fromRegExp` на `fakeFromPattern` с границами длины из контракта, а `mock-validity.test.ts` проверяет каждый мок ответа его Zod-схемой; подробнее в [frontend/README.md](../../frontend/README.md#генерация-api-клиента). Vitest пока сообщает peer warning об ожидаемом MSW 2; текущий Node-путь проверен с MSW 3, browser mode не используется.
|
||||
|
||||
Игноры находятся в `.gitignore` соответствующего компонента. Корневой файл содержит только правила для файлов самого корня. В CI pnpm устанавливается по `packageManager` из frontend/package.json; встроенный Corepack не требуется. Для локальной проверки ML с другой глобальной версией uv можно передать `UV='uv tool run --from uv==0.12.22 uv'` в Make.
|
||||
|
||||
В корне используйте make help для актуального списка. Основные targets:
|
||||
|
||||
- make install - поставить зависимости для api, frontend, ml и backend;
|
||||
- make generate - собрать оба OpenAPI bundle и обновить Go/TypeScript/Python generated output;
|
||||
- make fmt и make fmt-check - отформатировать или проверить форматирование;
|
||||
- make lint - запустить настроенные линтеры;
|
||||
- make test - unit/component/service tests для backend, frontend и ML;
|
||||
- make check - проверки api, backend, frontend, ML, deploy, observability и документации;
|
||||
- make verify - generation, drift checks, root check, api/backend проверки и технический Compose smoke;
|
||||
- make docs-check - проверить RU/EN документы, локальные ссылки, маршруты и импорты.
|
||||
|
||||
Локальный цикл для одной области описан Makefile этой области. Например, make -C backend help, make -C frontend help, make -C ml help, make -C api help, make -C deploy help, make -C observability help.
|
||||
|
||||
make check не является бизнес-E2E проверкой. make verify запускает deployment smoke с Docker и integration target backend. Для подробностей см. [TESTING.md](TESTING.md); для локального стенда см. [DEPLOY.md](DEPLOY.md).
|
||||
|
||||
У инструментов безопасности отдельный цикл установки и проверки: `make -C security install`, затем `make -C security check`. После изменения локальных правил или интеграции сканеров запускайте `make -C security test`; для сборки и сканирования образов сервисов - `make -C security images`. Эти проверки отделены от обычного корневого `make check`; требования, политика и отчеты описаны в [SECURITY.md](SECURITY.md).
|
||||
|
||||
### Сессии на локальном HTTP
|
||||
|
||||
Cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `SameSite=Strict` (см. [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf)). Локальный стек отдает обычный HTTP. Chromium и Firefox считают `http://localhost` и `http://127.0.0.1` безопасным контекстом и сохраняют там `Secure` cookie; WebKit и Safari могут ее отклонить. Для локального входа используйте Chromium или Firefox либо локальный TLS-прокси. Проект не добавляет флаг, отключающий `Secure` или префикс `__Host-`, поэтому локальная cookie не отличается от production.
|
||||
|
||||
`ConfirmEmail` требует, чтобы Origin точно совпадал с `APP_PUBLIC_URL`; отсутствующий Origin, буквальное значение `null` или другое значение дают 403 `csrf_check_failed`. Та же проверка действует для остальных небезопасных identity-операций и защищенных запросов сессии; последние также требуют привязанный к сессии CSRF-токен. Сервер не использует Host для определения разрешенного Origin.
|
||||
|
||||
## Структура
|
||||
|
||||
В каждом каталоге первого уровня, кроме `.github/`, есть краткий `README.md` на русском и его перевод `README.en.md`. В `.github/` README и его перевод необязательны. Подробные руководства находятся в `docs/ru/` и `docs/en/`; README глубже первого уровня не добавляются. `make docs-check` проверяет языковые пары, ссылки и запускает тесты самого проверяющего скрипта.
|
||||
|
||||
| Каталог | Назначение |
|
||||
| Команда | Назначение |
|
||||
| --- | --- |
|
||||
| api/core/ | Публичный OpenAPI контракт браузер-Go |
|
||||
| api/ml/ | Внутренний OpenAPI контракт Go-ML |
|
||||
| api/runner/ | Внутренний OpenAPI контракт Go и исполнителя кода |
|
||||
| scripts/ | Общее объединение схем, generated drift и docs-check |
|
||||
| backend/ | Go HTTP service, adapters, bootstrap, SQL и codegen потребителя |
|
||||
| backend/config/ | Общая конфигурация Go вне internal |
|
||||
| frontend/ | Vite SPA, Orval config и generated TypeScript |
|
||||
| ml/ | Python service, lockfile и генератор Pydantic-моделей |
|
||||
| runner/ | Go-сервис исполнителя кода: nsjail, cgroup v2, judge, ogen-сервер и тесты изоляции |
|
||||
| deploy/ | Compose, Nginx и smoke |
|
||||
| observability/ | Prometheus, Loki, Alloy и provisioning/dashboard JSON |
|
||||
| security/ | Конфигурация сканеров, установка, Make targets и локальные отчеты |
|
||||
| .agents/ | Канонические проектные инструкции и рабочие стандарты |
|
||||
| docs/ru/, docs/en/ | Пользовательские документы на русском и английском |
|
||||
| `make fmt` | Изменить форматирование исходников |
|
||||
| `make fmt-check` | Проверить формат без исправлений |
|
||||
| `make test` | Unit- и компонентные тесты сервисов |
|
||||
| `make check` | Проверки кода, документации и конфигурации |
|
||||
| `make verify` | Генерация, drift, проверки, race, интеграционные тесты и smoke |
|
||||
|
||||
Папки codegen принадлежат сервисам, которые используют сгенерированный код: backend/codegen/, frontend/codegen/ и ml/codegen/. Go client внутреннего ML API создается из backend/codegen/ogen-ml.yml и потребляется в backend/internal/adapter/secondary/ml/api/. Go client исполнителя кода создается из backend/codegen/ogen-code-runner.yml в backend/internal/adapter/secondary/code_runner/api/. Публичный generated Go handler создается из backend/codegen/ogen.yml и монтируется в chi. sqlc config находится в backend/codegen/sqlc.yml, generated SQL - в backend/internal/adapter/secondary/postgres/sqlc/. Orval читает публичный bundle через frontend/codegen/orval.config.ts. В backend/cmd/app/main.go остаются вызов bootstrap.Run() и обработка ошибки; запуск, сборка зависимостей и lifecycle находятся в backend/internal/bootstrap/app.go.
|
||||
`verify` требует Docker и не включает Playwright, security-сканеры или проверку реальных ML-моделей. Их выбирают отдельно по изменению.
|
||||
|
||||
## Локальное окружение
|
||||
|
||||
Для полного приложения используйте Compose. `.env.example` описывает переменные; секреты хранятся в локальном `.env` и не попадают в Git или примеры команд.
|
||||
|
||||
`make -C backend run` читает окружение процесса, а не файл `.env`. Адреса PostgreSQL, Redis, SeaweedFS и Kafka из Compose не обязаны быть доступны процессу на хосте. Не отключайте нужные зависимости только ради успешного старта.
|
||||
|
||||
`make -C frontend dev` запускает Vite с прокси `/api` на `127.0.0.1:8080`. Авторизация проверяет публичный Origin, поэтому `APP_PUBLIC_URL` должен соответствовать адресу браузера. Для проверки полного cookie-сценария проще использовать приложение за Nginx.
|
||||
|
||||
Почта по умолчанию отключена. Для разработки регистрации используйте изолированный почтовый E2E-стенд либо настройте Resend; SMTP-транспорт пока не реализован. Готовые синтетические аккаунты есть на отдельном demo-стенде.
|
||||
|
||||
## Контракты и генерация
|
||||
|
||||
Исходные YAML находятся рядом с соответствующим контрактом. Для общей сборки используйте make -C api bundle; он собирает схемы для api/core/, api/ml/ и api/runner/, затем bundles для каждого входа. Публичный и внутренние API не объединяются в одну спецификацию.
|
||||
Редактируйте тематические `routes/` и `components/` в `api/core/`, `api/ml/`, `api/runner/` или `api/labd/`. Общие правила HTTP собраны в [api/README.md](../../api/README.md).
|
||||
|
||||
Корневой make generate подготавливает API bundles один раз, затем запускает потребителей Go, TypeScript и Python. Merged schemas, bundles и generated clients являются отслеживаемыми derived files; меняйте исходники и пересоздавайте их генератором. После контракта перегенерируйте всех потребителей и запустите drift check. Отдельный Make target можно использовать для генерации одной части, если ее вход готов и shared contract owner согласовал его.
|
||||
|
||||
Целевое решение - OpenAPI 3.2.0, ogen для Go, Orval для TypeScript и datamodel-code-generator для Python/Pydantic v2. Проверяйте только реальные конструкции, которые использует проект, через pinned tools и runtime path. Название версии в заголовке не является подтверждением поддержки полной спецификации.
|
||||
|
||||
Python-генератор datamodel-code-generator 0.83.0 читает api/ml/openapi.bundle.yml и создает ml/src/lincodex_ml/api/models.py. Настройки хранятся в ml/codegen/pyproject.toml; это конфигурация инструмента, а зависимости остаются в ml/pyproject.toml и uv.lock. Health/readiness handlers импортируют сгенерированные модели вместо ручных копий схем. make -C ml generate сначала собирает API; при вызове из корневого make generate параметр API_PREPARED=1 использует уже собранный bundle. make -C ml check-generated сравнивает результат через --check без перезаписи файла. CI использует общий make generate, который включает Python-модели.
|
||||
|
||||
Ошибки, повторы, версии, пагинация и время следуют [соглашениям контракта](../../api/README.md#соглашения-контракта). Реализовано: любая ошибка публичного Go API и ML-сервиса - problem по RFC 9457 (`application/problem+json`) со стабильным `code`. Go-маппинг ошибок ogen находится в backend/internal/adapter/primary/http/problem/: валидация запроса дает 400, неизвестный маршрут под /api - 404, нереализованная операция - 501, остальные ошибки и panic - 500 без внутреннего текста; ошибки логируются на этой границе, panic - только типом и stack. Frontend API client бросает `ApiRequestError` для problem, сетевых сбоев (`network_error`) и некорректных 2xx-тел (`invalid_response`); отмена вызывающим пробрасывается без изменений. ML-сервис преобразует ошибки FastAPI в ml/src/lincodex_ml/api/problems.py и направляет логи uvicorn через свой JSON-формат без текста исключений. Хранение Idempotency-Key, проверки If-Match и пагинация запланированы: контракт определяет их компоненты, а реализует их первая бизнес-операция, которой они нужны.
|
||||
|
||||
## Код и слои
|
||||
|
||||
Зависимости SQL-линтера перечислены в `backend/requirements-quality.txt` рядом с `.sqlfluff`. Команда `make -C backend lint-sql` устанавливает их в локальное окружение `.venv-quality` и проверяет миграции и запросы. Для запуска Go-сервиса это окружение не требуется.
|
||||
|
||||
Go следует границам domain, usecase, port, adapter и bootstrap. HTTP adapter монтирует generated ogen handler в chi. SQL принадлежит backend/db/queries/, изменения схемы - backend/db/migrations/. sqlc output и wire_gen.go сгенерированы.
|
||||
|
||||
Общие backend параметры находятся в backend/config/. Используются go-logkit 0.6.0 через slog bridge и go-httpkit 0.7.0 для request ID и panic recovery. Журнал запросов - собственный `middleware.RequestLog`: logger из go-httpkit пишет исходный путь и каждое значение query вне своего фиксированного списка скрытия, поэтому адрес в пути или query попал бы в журналы. Собственный Prometheus middleware сохраняется: он ограничивает method labels и использует chi route patterns; go-httpkit/metrics принимает исходное имя метода как label.
|
||||
|
||||
Подключение к PostgreSQL создается через pgxpool.NewWithConfig, а generated SELECT 1 readiness query проверяет доступность БД. Pool constructor не должен ждать доступность БД при startup. go-pgkit 1.4.0 не используется: его constructor проверяет подключение и повторяет попытки до возврата pool, что связывало бы запуск сервиса с доступностью БД. Health handlers остаются явными: helper go-httpkit возвращает ok/degraded и детали проверок, а общий контракт использует ok/ready/not_ready. Не добавляйте pgkit, httpkit/metrics, JWT или WebSocket без конкретной потребности и проверки поведения закрепленной версии.
|
||||
|
||||
Redis подключен через outbound-порт кеша и `backend/internal/adapter/secondary/redis/`. Адаптер использует `go-cachekit` 0.7.0 для операций key/value поверх go-redis; детали библиотек не выходят за его границу. Bootstrap создает клиент без ожидания подключения и закрывает его при завершении; общий /readyz проверяет PostgreSQL, Redis и SeaweedFS. Используйте Get/Set/Del, положительный TTL и отличайте отсутствие ключа от ошибки Redis. Это технический адаптер, потребители продуктового кеша пока не добавлены. Настройки подключения описаны в [DEPLOY.md](DEPLOY.md).
|
||||
|
||||
S3-хранилище подключено через outbound-порт `ObjectStorage` и `backend/internal/adapter/secondary/seaweedfs/`. SeaweedFS - отдельный сервер, а AWS SDK for Go v2 - клиент Go внутри адаптера. Put/Get передают содержимое потоком; Put требует известный размер в байтах, а вызывающий код обязан закрыть тело, возвращенное Get. Таймаут Get действует до завершения чтения тела. Адаптер ограничивает время операций и отличает отсутствие объекта от ошибки сервиса. Bucket создается при запуске контейнера; Go проверяет его через HeadBucket, не создавая инфраструктуру при обработке запросов. Не добавляйте прямую выдачу приватных файлов Nginx или продуктовые upload/download endpoints без правил доступа.
|
||||
|
||||
Frontend строится как React/Vite SPA. При разработке продуктовых экранов соблюдайте FSD границы.
|
||||
|
||||
Реализованный каркас frontend: data router React Router с публичными маршрутами и отдельными оболочками кабинетов кандидата и работодателя, клиент TanStack Query поверх общего `apiRequest` того же origin, токены темной графитовой темы в CSS variables и общие примитивы состояний загрузки, пустого результата, ошибки, запрета доступа и сохранения. Шрифты JetBrains Mono, Inter и Unbounded (для словесного знака Lincodex) раздаются с нашего сервера вместе с лицензиями OFL. Вход, регистрация, подтверждение почты, поддержка и экраны кабинетов - заготовки; бизнес-экраны делаются отдельными задачами. /status - техническая страница доступности API, а не показатель готовности продукта. Vitest работает в окружении Node без DOM. Набор Playwright в `frontend/e2e/` открывает страницы в Chromium, но пока не проверяет взаимодействия, поэтому нажатия и фокус клавиатуры проверяются вручную в браузере, пока набор их не покрывает. Подробнее: [frontend/README.md](../../frontend/README.md). Generated API transport не превращается в entity model сам по себе. MSW полезен для интерфейсной разработки, но его fixture не подтверждает API реализации.
|
||||
|
||||
ML - отдельный FastAPI процесс. Сейчас он предоставляет только operational health/readiness. Readiness остается 503 без модели. Не добавляйте placeholder inference, который выглядит как рабочий результат.
|
||||
|
||||
Все комментарии и docstrings в коде пишутся на английском. Инструкции для агентов в корне и .agents также ведутся в единой английской версии; документация команды поддерживается на русском и английском.
|
||||
|
||||
### Миграции базы данных
|
||||
|
||||
Миграции - SQL-файлы goose в `backend/db/migrations/` с именами `NNNNN_description.sql` и последовательными пятизначными версиями. В каждом файле есть секция `-- +goose Up` и работающая секция `-- +goose Down`. sqlc читает этот же каталог как схему, а `make -C backend lint-sql` проверяет его линтером. `backend/db/migrations.go` встраивает файлы в бинарник, поэтому он применяет ровно ту схему, с которой собран. `make -C backend check` загружает встроенный набор без базы данных и падает на неверном имени, отсутствующей секции Down или дублирующейся версии. Примененная на стенде миграция неизменна; схема меняется новым файлом. Две ветки с одинаковой версией должны перенумеровать файл перед слиянием. Чтобы создать файл со следующим номером, выполните `go tool goose -dir db/migrations -s create <name> sql` в `backend/`.
|
||||
|
||||
goose выполняет каждую миграцию в отдельной транзакции. Команде, которая не работает внутри транзакции, например `CREATE INDEX CONCURRENTLY`, нужен отдельный файл с аннотацией `-- +goose NO TRANSACTION`. Каждое соединение миграций устанавливает `lock_timeout` в 10 секунд, чтобы DDL падал, а не ждал за длинными транзакциями и не блокировал последующие запросы к таблице, и `statement_timeout` в 4 минуты.
|
||||
|
||||
При старте bootstrap применяет ожидающие миграции после проверки конфигурации и до открытия HTTP и metrics listeners. Runner в `backend/internal/adapter/secondary/postgres/migrator.go` использует Provider API goose v3 с драйвером pgx для database/sql и сессионный advisory lock PostgreSQL, поэтому одновременно стартующие экземпляры применяют миграции по очереди. Ожидание блокировки и сами миграции ограничены пятью минутами. Ошибка миграции останавливает запуск; текст ошибки не содержит строку подключения и пароль. Без `DATABASE_URL` шаг пропускается с предупреждением, а readiness, как и раньше, остается `not_ready`.
|
||||
|
||||
`DATABASE_MIGRATE_ON_START` принимает только `true` или `false` (без учета регистра, пробелы по краям игнорируются); по умолчанию `true`. Это опция для локальной разработки, например чтобы запустить сервис с базой, которую разработчик мигрирует вручную. Compose ее не передает, а в образе backend нет отдельной команды миграций, поэтому развернутый backend всегда мигрирует при старте, и его роли БД нужны права DDL на схему приложения. Отдельная роль и job миграций с минимальными правами runtime-роли - будущая работа.
|
||||
|
||||
Для локальной базы экспортируйте `DATABASE_URL` в shell и используйте цели:
|
||||
|
||||
- `make -C backend migrate-status` показывает каждую встроенную миграцию как примененную, со временем, или ожидающую.
|
||||
- `make -C backend migrate-up` применяет ожидающие миграции.
|
||||
- `make -C backend migrate-down-one` откатывает последнюю примененную миграцию.
|
||||
|
||||
Цели запускают `backend/cmd/migrate` с тем же runner, блокировкой и таймаутами, что и старт сервиса. Makefile не содержит строк подключения; не храните учетные данные в коммитах. Интеграционные тесты применяют все миграции к контейнеру PostgreSQL из общего bootstrap; см. [TESTING.md](TESTING.md).
|
||||
|
||||
### Хранение identity
|
||||
|
||||
Миграция `00002_create_identity_tables.sql` создает `users`, `email_tokens` и `sessions`; запросы лежат в `backend/db/queries/identity.sql`. Миграция 00014 добавляет к токенам хеш пароля, сценарий и шаг онбординга конкретной регистрации. Миграция 00016 связывает регистрационную C1 с версией регистрации аккаунта и заполняет прежние записи без использования живых токенов. Порты identity используются при регистрации, повторной отправке и подтверждении email; вход и principal сессии пока не реализованы.
|
||||
|
||||
База данных никогда не получает пароль, исходный email-токен или исходный токен сессии. Репозитории принимают `domain.PasswordHash` (строку PHC Argon2id v19) и `domain.SecretTokenHash` (SHA-256 от `domain.SecretToken`). Email-адреса пока принимаются только в ASCII; поддержка IDN и SMTPUTF8 - будущая работа, для которой нужен IDNA ToASCII для домена. `SecretToken`, `PasswordHash` и `EmailAddress` скрывают значение в выводе `fmt` и `slog`; `SecretToken.Reveal` и `EmailAddress.Address` возвращают настоящие значения там, где они нужны. Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, а PostgreSQL хранит микросекунды. Взаимная блокировка или ошибка сериализации сообщается как `outbound.ErrTransactionConflict`, и вызывающий код может повторить всю операцию. Схема и принятые решения описаны в [ARCHITECTURE.md](ARCHITECTURE.md#хранение-identity).
|
||||
|
||||
Пароль попадает в backend только как `domain.Password`: `domain.NewPassword` для нового пароля (от 15 до 128 кодовых точек после NFKC) и `domain.ParseLoginPassword` при входе (от 1 до 128). Исходный ввод длиннее 512 байт или с некорректным UTF-8 отклоняется до нормализации, и все проверки длины выполняются до хеширования. Адаптер `argon2id` реализует `outbound.PasswordHasher` с m=65536 KiB, t=3, p=4, бюджетом памяти на `PASSWORD_HASH_CONCURRENCY` вычислений (от 1 до 4; без значения - меньшее из 2 и GOMAXPROCS), `ErrPasswordMismatch` для неверного пароля, `ErrPasswordHashCorrupt` для некорректного или выходящего за границы сохраненного хеша, результатом `needsRehash` для старых параметров и `VerifyDummy` для неизвестных аккаунтов. Сохраненный хеш, не прошедший разбор или границы, оборачивает и `ErrPasswordHashCorrupt`, и `domain.ErrInvalidPasswordHash`. Unit-тесты используют дешевые параметры; эталонный вектор на 64 MiB пропускается с `-short`; `go test -run '^$' -bench . ./internal/adapter/secondary/argon2id/` в `backend/` измеряет один хеш с production-параметрами. См. [ARCHITECTURE.md](ARCHITECTURE.md#хеширование-паролей).
|
||||
|
||||
### Хранилище продуктовой политики
|
||||
|
||||
Миграция `00003_create_policy_versions.sql` создает `policy_versions`, триггер, который ставит `created_at` по часам базы данных, и триггеры, отклоняющие UPDATE, DELETE и TRUNCATE; запросы лежат в `backend/db/queries/policy.sql`. `outbound.PolicyRepository` доступен через `UnitOfWork.Policies()` и вне транзакции через `postgres.PolicyStore`; `policy.Publisher` публикует версию под следующим свободным номером и выполняет начальное заполнение демонстрационной политики. Чтобы изменить значение, опубликуйте новую версию; сохраненная версия никогда не редактируется. `product` - единственное семейство политики.
|
||||
|
||||
При старте backend публикует `domain.DemoProductPolicyV1()` как версию 1 семейства `product`, если у этого семейства нет ни одной версии. Заполнение выполняется сразу после миграций при старте и только вместе с ними: нужно, чтобы `DATABASE_MIGRATE_ON_START` был равен true и был задан `DATABASE_URL`. Если миграции при старте отключены, политику никто не заполняет. Заполнение проверяет только наличие версий, никогда не меняет и не разбирает существующую версию и пишет в лог только ключ, номер, вид и ID. Демонстрационные значения - принятая начальная политика, а не калиброванные значения.
|
||||
|
||||
Запись, которая зависит от значений политики, добавляет `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)`, хранит использованную версию и читает ее обратно по ID; не пересчитывайте существующую запись через `GetEffective`. Тесты используют собственные значения и не подменяют демонстрационную политику. Поскольку `product` - единственное семейство, а таблица отклоняет TRUNCATE, интеграционные тесты дают каждому случаю отдельную базу данных. Новой структуре документа нужны новая `schema_version` и свой декодер; не меняйте golden-документ в `backend/internal/domain/policy_test.go`, чтобы принять измененную каноническую форму. См. [ARCHITECTURE.md](ARCHITECTURE.md#версии-продуктовой-политики).
|
||||
|
||||
### Банк заданий оценки
|
||||
|
||||
Миграция `00011_create_assessment_bank.sql` создает `assessment_families` (неизменяемые версии семейств) и `assessment_category_openings`; запросы лежат в `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` доступен через `UnitOfWork.AssessmentBank()` и через `postgres.AssessmentBankStore` вне транзакции; `assessment.Bank` импортирует `Bundle`, публикует версию от имени оператора (выводя из обращения опубликованную более старую), выводит ее из обращения, открывает категорию под действующей версией политики, сообщает живую доступность и генерирует вариант по seed. Чтобы изменить семейство, импортируйте новую версию; сохраненная версия не редактируется, а черновик `pending` одобряется импортом новой версии с рецензией. Новый алгоритм seed получает новое версионное имя в `domain/assessment_algorithms.go`, обязательные подстановки, тест решателя с посчитанными вручную случаями и golden-тест; зарегистрированный алгоритм не меняйте. Алгоритм с форматом ответа `choice` задает `generateChoice` вместо `generate` и возвращает правильное значение вместе с неверными значениями именованных моделей ошибок (пример - `lru_hits_choice.v1`); его тесты пересчитывают модели ошибок по условию. Семейство, варианты которого - фиксированные данные, использует табличный генератор вместо алгоритма: `seed_generator.table.rows` с `values`, `answer` и для `choice` еще `distractors`; при импорте таблица проверяется, ошибка называет индекс строки, а версия хранится со схемой хеша 2. Если ответ нужно вычислять, используйте алгоритм на Go. Схему 2 разрешает миграция `00047_allow_table_hash_scheme.sql`. Шаблоны условий - обычный текст только с подстановками `{{.name}}`. Демонстрационный пакет в `backend/testdata/assessment/` - непроверенный черновик ИИ: не заполняйте в нем рецензента, чтобы открыть категорию. См. [ARCHITECTURE.md](ARCHITECTURE.md#банк-заданий-оценки).
|
||||
|
||||
### Relay outbox
|
||||
|
||||
Relay переносит зафиксированные строки `outbox_events` в Kafka. Цикл находится в `backend/internal/worker/outboxrelay/`, а его backoff - в `backend/internal/worker/retry/`; он зависит от портов `outbound.OutboxRelayStore` и `outbound.EventPublisher` в `backend/internal/port/outbound/outbox_relay.go`. `postgres.OutboxRelayStore` выполняет транзакцию захвата запросами `LockPendingOutboxEvents` и `MarkOutboxEventsPublished` из `backend/db/queries/outbox.sql`, а `kafka.Publisher` в `backend/internal/adapter/secondary/kafka/` собирает конверт записи, создает топик и публикует через franz-go. `bootstrap.newOutboxRelay` создает relay с собственным пулом PostgreSQL не больше чем на два соединения и собственным клиентом Kafka, а приложение запускает его, пока работают HTTP-серверы. Продуктовый код relay не вызывает: usecase только добавляет события через `UnitOfWork.Outbox()` в своей бизнес-транзакции.
|
||||
|
||||
Backend, запущенный напрямую с `DATABASE_URL`, запускает relay против `KAFKA_BROKERS` (по умолчанию `localhost:9092`). Без доступного брокера он продолжает писать предупреждения о повторах, а события остаются в ожидании; если публикация не нужна, задайте `RELAY_ENABLED=false`. Выбор строк, порядок, конверт и поведение при сбоях описаны в [ARCHITECTURE.md](ARCHITECTURE.md#relay-outbox), настройки - в [DEPLOY.md](DEPLOY.md#relay-outbox), тесты - в [TESTING.md](TESTING.md#тесты-relay-outbox).
|
||||
|
||||
### Обработчики событий
|
||||
|
||||
Runtime обработчиков применяет события из Kafka к собственному состоянию сервиса, по одному разу на обработчик. Цикл находится в `backend/internal/worker/eventconsumer/`; он зависит от порта `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`) и портов `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`). `kafka.EventSource` - участник группы на franz-go, который декодирует конверт и фиксирует offsets, а `postgres.EventConsumerStore` выполняет транзакцию дедупликации запросами из `backend/db/queries/event_consumer.sql`. Backoff общий с relay и находится в `backend/internal/worker/retry/`.
|
||||
|
||||
Зарегистрированы два продуктовых обработчика: `notification.DeliveryHandler` сохраняет доставки писем (см. [Доставки писем](#доставки-писем)), а `notification.InboxHandler` сохраняет ссылки inbox (см. [Внутренние уведомления](#внутренние-уведомления)). Чтобы добавить другой обработчик, реализуйте `inbound.EventHandler` в пакете usecase модуля: верните стабильное имя в snake_case из `ConsumerName()`, принимайте в `Handles` только применяемые типы событий и пишите эффект в `Handle` только через полученный `UnitOfWork`. Для события, которое нельзя применить никогда, например с неизвестной `schema_version`, верните ошибку, оборачивающую `inbound.ErrEventRejected`; любая другая ошибка повторяется. Затем добавьте обработчик в `eventHandlers()` в `backend/internal/bootstrap/consumers.go`. Bootstrap выдает ему consumer group, соединение из пула обработчиков и жизненный цикл рядом с HTTP-серверами. Проверяйте эффект на реальном PostgreSQL через хранилище, как это делает `TestEventConsumer`.
|
||||
|
||||
Backend, запущенный напрямую с зарегистрированным обработчиком и `DATABASE_URL`, читает события из `KAFKA_BROKERS`; задайте `CONSUMER_ENABLED=false`, если это не нужно. Устройство и поведение при сбоях описаны в [ARCHITECTURE.md](ARCHITECTURE.md#обработчики-событий); настройки, метрики и порядок работы с dead letters - в [DEPLOY.md](DEPLOY.md#обработчики-событий); тесты - в [TESTING.md](TESTING.md#тесты-обработчиков-событий).
|
||||
|
||||
### Доставки писем
|
||||
|
||||
Чтобы отправить уведомление из usecase, вызовите `notification.MailRequester.RequestNotification(ctx, unit, request)` с `UnitOfWork` usecase, ID аккаунта получателя и `mailtemplate.NotificationData`; вызов возвращает ID доставки. Он сохраняет текст в `mail_requests` и добавляет событие, которое несет только ID запроса и вид, оба действия - в транзакции usecase. Затем обработчик `notification_delivery` сохраняет доставку с адресом, прочитанным из аккаунта, и сформированным содержимым и удаляет запрос; аккаунты с неподтвержденным адресом он пропускает. Никогда не кладите email, токен, текст уведомления или контакт другого человека в payload любого события и никогда не кладите токен или контакт другого человека в запрос. Письма подтверждения почты и сброса пароля содержат токен и не могут идти через событие: сценарии identity создают такие доставки через `domain.NewDelivery` и `UnitOfWork.Deliveries().Create` в транзакции, которая выпускает токен. Новая версия шаблона меняет только новые доставки; никогда не обновляйте содержимое сохраненной доставки. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем), эксплуатация - в [DEPLOY.md](DEPLOY.md#доставки-писем), тесты - в [TESTING.md](TESTING.md#тесты-доставки-писем).
|
||||
|
||||
Каждая отправка обязана пройти `notification.QuotaGate`: соберите его с настроенными аккаунтом и лимитами и окном идемпотентности транспорта (`resend.IdempotencyWindow` или ноль для SMTP); вызовите `PrepareSend` в транзакции, которая захватывает доставку, и зафиксируйте ее до вызова `MailSender.Send`; затем вызовите `SettleSend` в транзакции, которая записывает попытку, и для отказа `quota_exhausted` используйте возвращенный момент как `next_attempt_at` попытки. Для отказа по квоте транспорт заполняет `SendResult.QuotaPeriod` по собственному имени ошибки провайдера. Никогда не вызывайте транспорт без разрешения и не переключайтесь на другой транспорт или аккаунт, когда квота исчерпана. Чтобы показать аккаунту статус его писем, вызывайте `notification.DeliveryStatusReader.LatestForUser` только с ID аутентифицированного аккаунта. Правила описаны в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты).
|
||||
|
||||
### Внутренние уведомления
|
||||
|
||||
Чтобы положить уведомление в inbox получателя, добавьте событие через `unit.Outbox().Append` в собственной транзакции usecase. Тип должен быть разрешен (`domain.NotificationInboxSourceFor`), payload должен состоять ровно из `recipient_user_id` и `organization_id`, а агрегат - тот, который назван для типа (`invitation` для `invitation.delivered`). Никогда не кладите в payload текст или контакты. Обработчик `notification_inbox` сохраняет ссылку. Текст создается, когда получатель читает список, преобразователем, который вы регистрируете для своего типа источника в `notification.DefaultInboxSourceResolvers()`: `InboxSourceResolver` читает текущее состояние через `UnitOfWork`, применяет текущую видимость получателя и возвращает `ErrInboxContentUnavailable`, когда содержимое показывать нельзя. Для нового типа события добавьте пару в `domain.NotificationInboxSourceFor`, запись в `inboxProjections` в `usecase/notification/inbox_handler.go`, миграцию, расширяющую CHECK у `notification_inbox_events` (развернутую миграцию не правят), значение `NotificationKind` в контракт и отображение в `adapter/primary/http/v1/notifications.go`. Источнику письмо не нужно: почта запрашивается отдельно через `MailRequester`, а состояние inbox от нее не зависит. Путь можно проверить целиком синтетическим событием `notification.synthetic_delivered` (payload строит `notification.SyntheticNoticeEventPayload`); продуктового смысла у него нет, и обрабатывается он только при `NOTIFICATION_SYNTHETIC_ENABLED=true`. См. [Внутренние уведомления](ARCHITECTURE.md#внутренние-уведомления).
|
||||
|
||||
### Задания по сроку
|
||||
|
||||
Чтобы выполнить что-то в срок, например истечение или напоминание, запланируйте задание в собственной транзакции usecase: соберите его через `domain.NewScheduledJob` (вид, например `invitation.response_deadline`, ключ логического задания, например ID агрегата, срок по внедренным часам и payload только из идентификаторов) и вызовите `unit.ScheduledJobs().Schedule(ctx, job)`. Побеждает первое планирование вида и ключа, повтор игнорируется, поэтому для нового повторения используйте новый ключ, например `<id>:<version>`. Отменяйте через `unit.ScheduledJobs().Cancel(ctx, kind, key)` до блокировки продуктовых строк, которые трогает обработчик.
|
||||
|
||||
Затем реализуйте `inbound.JobHandler` в пакете usecase модуля: верните вид из `JobKind()` и пишите эффект в `Handle` только через полученный `UnitOfWork`, принимая решение по `job.DueAt` и текущему продуктовому состоянию, чтобы обработчик ничего не делал, если состояние уже изменилось. Обработчик может отменить собственное задание через unit, например из общего helper, который отменяет срок; тогда задание считается выполненным. Иначе менять собственное задание нельзя. Для задания, которое нельзя выполнить никогда, верните ошибку, оборачивающую `inbound.ErrJobRejected`; любая другая ошибка повторяется. Добавьте обработчик в `jobHandlers()` в `backend/internal/bootstrap/jobs.go`. Принимайте часы как `func() time.Time` и проверяйте сроки через `testutil.FakeClock` из `backend/pkg/testutil/` и `Worker.RunDue`, который один раз выполняет наступившие задания без опроса, как это делает `TestScheduledJobs`. Устройство и поведение при сбоях описаны в [ARCHITECTURE.md](ARCHITECTURE.md#задания-по-сроку); настройки, метрики и порядок работы с dead заданиями - в [DEPLOY.md](DEPLOY.md#задания-по-сроку); тесты - в [TESTING.md](TESTING.md#тесты-заданий-по-сроку).
|
||||
|
||||
## Читаемость Go-кода
|
||||
|
||||
- Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна.
|
||||
- Неочевидные лимиты, таймауты, retry settings, границы протоколов и общие значения фикстур получают именованные константы в своем пакете. Размеры вычисляются через `len`, если зависят от данных. Одинаковые числа с разным смыслом получают разные имена. Очевидные нулевые значения, индексы и понятные входы тестов остаются на месте.
|
||||
- Параметры окружения задаются через config с именованными defaults и валидацией. Значение разбирается один раз; отсутствие переменной отличается от явно заданного неверного значения.
|
||||
- Функция решает одну понятную задачу. Используйте ранние возвраты, небольшую вложенность и именованные сложные условия. Не добавляйте универсальные helpers, интерфейсы и слои без потребителя.
|
||||
- Передавайте `context.Context` первым аргументом. Владение ресурсами и зависимости должны быть явными; cleanup регистрируется сразу после создания ресурса, в том числе при частичном startup. Helper не должен скрывать goroutine или глобальное изменяемое состояние.
|
||||
- Проверяйте ошибки. Неочевидное игнорирование результата объясняйте комментарием. Не сравнивайте тексты ошибок для управления программой и не передавайте внутренние ошибки в HTTP-ответы.
|
||||
- Комментарии на английском объясняют ограничения и решения. Форматирование выполняют gofmt/goimports. Рефакторинг сохраняет поведение; тесты проверяют существенные границы и крайние случаи, а не названия констант или устройство helpers.
|
||||
|
||||
## Формат ошибок
|
||||
|
||||
Ошибки в написанном вручную Go-коде имеют формат `Component.Method - operation: %w`, если есть вложенная ошибка, и `Component.Method - reason`, если ее нет. Для обычной функции вместо метода используйте `package.Function`. Например:
|
||||
|
||||
```go
|
||||
if err != nil {
|
||||
return fmt.Errorf("EmailUseCase.Send - read ctf_name: %w", err)
|
||||
}
|
||||
```sh
|
||||
make -C api check
|
||||
make generate
|
||||
make check-generated
|
||||
```
|
||||
|
||||
Статическая ошибка без причины создается через `errors.New("EmailUseCase.Send - ctf_name is empty")`. Префикс указывает реальный метод, описание пишется на английском без точки в конце. Сохраняйте `errors.Is/As` и идентичность sentinel errors; контекст добавляйте в месте возникновения ошибки. Не добавляйте одинаковые обертки при простом возврате ошибки. Сначала очищайте ошибки внешних SDK от секретов, URL и приватных ключей объектов, затем оборачивайте безопасную причину. Generated code не изменяйте. Логируйте ошибку в месте обработки, а не на каждом уровне.
|
||||
Генерация выполняется в порядке: bundle API, Go backend, runner, labd, frontend, Python ML. `make check-generated` сравнивает результат с Git и не запускает генераторы. При намеренном изменении контракта измененный output должен войти в тот же коммит; неожиданный diff нужно разобрать.
|
||||
|
||||
## Правила изменений
|
||||
- ogen пишет Go HTTP-код в `api/` нужного адаптера.
|
||||
- sqlc пишет запросы PostgreSQL в `backend/internal/adapter/secondary/postgres/sqlc/`.
|
||||
- wire собирает зависимости в `backend/internal/bootstrap/`.
|
||||
- mockery генерирует только интерфейсы, выбранные в `backend/codegen/mockery.yml`.
|
||||
- Orval пишет клиент, query hooks, Zod-схемы и MSW в `frontend/src/shared/api/endpoints/` и `schemas/`.
|
||||
- datamodel-code-generator создает Pydantic-модели из ML-контракта.
|
||||
|
||||
- Проверяйте текущий код и назначенный ownership перед правкой общего файла.
|
||||
- Сохраняйте существующие изменения других участников.
|
||||
- Изменения OpenAPI, миграций, shared Makefile, lockfile и генерации согласуются с одним владельцем общей поверхности.
|
||||
- Generated files обновляйте только через Make targets.
|
||||
- Документируйте разницу между работающим сейчас и целевым поведением.
|
||||
- Не добавляйте локальные пути, секреты и персональные настройки разработчика.
|
||||
Не редактируйте output вручную. Конфигурация генератора находится в `codegen/` потребителя; Go-клиент ML принадлежит backend, Python-модели - ML.
|
||||
|
||||
Для задач по backend, frontend, ML, API, базе и инфраструктуре используйте маршруты в корневом [AGENTS_ROUTING.md](../../AGENTS_ROUTING.md).
|
||||
## Backend и данные
|
||||
|
||||
Предметные типы лежат непосредственно в `internal/domain/`. Usecase зависит от портов, адаптеры реализуют доступ к HTTP, базе и внешним сервисам. `internal/bootstrap/` связывает зависимости и управляет жизненным циклом; `cmd/app/main.go` вызывает его.
|
||||
|
||||
- Добавляйте бизнес-правила в domain/usecase, а преобразование HTTP - в `adapter/primary/http/v1/`.
|
||||
- Для новой инфраструктуры сначала определите нужный порт и адаптер. Сервисы не обращаются к чужим таблицам напрямую.
|
||||
- Изменяйте SQL в `db/queries/`, затем запускайте `make -C backend gen-sqlc`.
|
||||
- Изменение схемы оформляйте новой миграцией в `db/migrations/`; проверяйте ее на отдельной базе. Не переписывайте уже примененные миграции.
|
||||
- Бизнес-изменение и outbox-событие сохраняйте в одной транзакции. Обработчики должны выдерживать повторную доставку.
|
||||
- Повторяющийся код выносите в небольшой helper; значения с предметным смыслом - в именованные константы или конфигурацию.
|
||||
|
||||
Ошибки содержат место и причину: `fmt.Errorf("ProfileUseCase.Update - save profile: %w", err)`. Для ошибки без причины используйте тот же формат без `%w`. HTTP-ответ содержит безопасный problem-код; внутренние ошибки и персональные данные клиенту не передаются.
|
||||
|
||||
Отдельные команды обслуживания перечислены в `make -C backend help`. Миграции, повтор отправки почты, публикация политики и backfill меняют состояние: выбирайте нужное окружение явно.
|
||||
|
||||
## Frontend
|
||||
|
||||
Слои FSD: `app`, `pages`, `widgets`, `features`, `entities`, `shared`. Импорт идет в нижний слой через публичный API слайса; соседние слайсы не связываются внутренними импортами. Общие компоненты и стили находятся в `shared/`, API-типы берутся из генерации.
|
||||
|
||||
Серверное состояние храните в TanStack Query, черновики форм - в состоянии формы. На конфликт версии сохраняйте введенные данные и предлагайте перечитать сервер. Для асинхронных экранов нужны состояния загрузки, пустого результата, ошибки и повторного запроса.
|
||||
|
||||
Проверяйте клавиатуру, фокус, подписи полей и небольшую ширину экрана. Vitest проверяет логику, Playwright - работу интерфейса в браузере.
|
||||
|
||||
## ML и дополнительные сервисы
|
||||
|
||||
ML-команды: `make -C ml help`. Обычные проверки используют Ruff, mypy и pytest; качество модели и реальный inference проверяются отдельно. Веса и данные оценки должны иметь фиксированную версию.
|
||||
|
||||
Runner и labd - отдельные Go-модули. Unit-тесты не заменяют проверку изоляции runner или работу labd на отдельном тестовом LXD-хосте. Их окружения описаны в [runner/](../../runner/README.md) и [labd/](../../labd/README.md).
|
||||
|
||||
## Документация и Git
|
||||
|
||||
README каталога объясняет назначение, запуск и основные команды. Подробности остаются в контракте, исходниках и тематическом руководстве. Не добавляйте в документацию историю выполнения задач или список всех частных тестов.
|
||||
|
||||
Комментарии в коде пишутся по-английски. Документация поддерживается парами RU/EN. Планы и их идентификаторы остаются в локальном `PRD/`; каталог не коммитится. Коммит описывает изменение одной короткой строкой, без авторства ассистента и coauthor trailers.
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
# MVP Lincodex: пакет сдачи
|
||||
|
||||
Проверенный коммит: `c9f029471ed78ce5ec4583009abdc5a4c8c3bd97` (ветка dev, 10.10.2026).
|
||||
|
||||
Выпуск: `mvp-2026-10-10`, собран из `392d117` (тот же код и этот документ). Манифест `deploy/release/mvp-2026-10-10/manifest.json` - локальный артефакт машины, на которой собраны образы (в Git не хранится, см. [манифест выпуска](DEPLOY.md#манифест-выпуска)); ядро `verified`, smoke и браузерный набор пройдены на образах выпуска, восстановление доступно.
|
||||
|
||||
Документ описывает, что входит в минимальный выпуск, как его запустить, чем ограничена демонстрационная категория, что не реализовано и чем выпуск проверен. Подробности вынесены в руководства: [ARCHITECTURE](ARCHITECTURE.md), [DEPLOY](DEPLOY.md), [TESTING](TESTING.md), [SECURITY](SECURITY.md), [COMPANY_QUOTAS](COMPANY_QUOTAS.md) и [frontend](../../frontend/README.md). Контракт HTTP API находится в [api/](../../api/README.md). Утверждения ниже выведены из кода, контракта и этих руководств; запланированное отделено от работающего.
|
||||
|
||||
## 1. Что реализовано
|
||||
|
||||
### Регистрация и вход
|
||||
|
||||
- Регистрация кандидата и работодателя с согласием C1. Адрес подтверждается ссылкой из письма или шестизначным кодом из того же письма; после подтверждения вход возвращает пользователя на сохраненный шаг. См. [регистрацию и подтверждение](ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка).
|
||||
- Письмо уходит только при `EMAIL_PROVIDER=resend`. При `disabled` регистрация принимается, но подтвердить адрес нечем, и вход отвечает 403 `email_not_verified`. Подготовленные аккаунты демонстрационного стенда подтверждены заранее. См. [почту](DEPLOY.md#2-почта-resend-или-disabled).
|
||||
|
||||
### Кандидат
|
||||
|
||||
- Согласия C1-C5 в настройках. C3 разрешает автоматическую категоризацию; без него доступен запрос ручной оценки через обращение в поддержку.
|
||||
- Профиль заполняется вручную по шагам, без резюме и без ФСП ID. Анкета содержит специализации и самооценку. Главная страница показывает следующий шаг. См. [профиль кандидата](ARCHITECTURE.md#профиль-кандидата).
|
||||
- Проверка навыков в двух режимах (см. [оценивание](ARCHITECTURE.md#оценивание-и-подтверждение-грейда)):
|
||||
- полный тест `demo_basic` Backend Junior с Go: 25 заданий из синтетического банка, срок 72 часа, две рабочие сессии, без практики. Результат сравнивается с порогом версии политики; на демонстрационном стенде пройденный тест получает категорию с основанием `synthetic_demo`, иначе результат `not_confirmed`;
|
||||
- экспресс-тест `demo_express`: три задания; он никогда не назначает грейд, категорию, перцентиль или доказательство и не попадает в историю результатов.
|
||||
- Результаты, история и доказательства навыка доступны кандидату; заявленный грейд всегда отделен от подтвержденного. См. [доказательства](ARCHITECTURE.md#доказательства-навыков).
|
||||
|
||||
### Публикация и видимость
|
||||
|
||||
- Анонимная карточка публикуется только после явного C2 и не содержит имени, контактов и суммы зарплаты. Кандидат видит предпросмотр, строящийся из того же ответа, что и карточка для организаций.
|
||||
- Статус поиска, скрытие отдельных организаций, история изменений и история просмотров карточки и чтений контактов. Карточка показывается организациям только в группе не менее пяти. См. [видимость](ARCHITECTURE.md#видимость-кандидата).
|
||||
|
||||
### Работодатель
|
||||
|
||||
- Организации (аккаунт может владеть несколькими), профиль компании и потребность по шагам с вилкой зарплаты. Потребность хранит версии требований; поиск по версии не меняется после правки. См. [организации](ARCHITECTURE.md#организации-и-членства).
|
||||
- Поиск кандидатов по потребности или по банку с фильтрами: специализация, подтвержденный и заявленный грейд, статус подтверждения, стек, формат работы и совместимость по зарплате. Результат разделен на группы `main`, `near`, `unconfirmed`, а объяснение (компоненты оценки и флаги неизвестного) строит сервер.
|
||||
- Базовый подбор работает без ML: смысловая близость равна нейтральным 0.5 и помечена флагом `ml_unavailable`; при когорте меньше 30 добавляется `cohort_below_30`. См. [подбор и объяснение](ARCHITECTURE.md#подбор-и-объяснение).
|
||||
|
||||
### Приглашения и контакты
|
||||
|
||||
- Организация создает черновик из результата поиска, меняет условия с версиями и отправляет приглашение с вилкой зарплаты в рублях. Отправка тратит место недельной квоты; на потребность действует предел ожидающих приглашений, после отказа действует пауза пары, а неотвеченное приглашение истекает по сроку. См. [черновики](ARCHITECTURE.md#черновики-приглашений), [отправку](ARCHITECTURE.md#отправка-приглашений) и [предел и истечение](ARCHITECTURE.md#предел-ожидающих-пауза-и-истечение).
|
||||
- Доставленное приглашение попадает во входящие кандидата. Кандидат отмечает просмотр, отказывается или принимает его с согласием C4, выбрав поля контактов. См. [просмотр и отказ](ARCHITECTURE.md#просмотр-и-отказ-кандидата) и [принятие](ARCHITECTURE.md#принятие-кандидатом).
|
||||
- Принятие создает разрешение на контакты ровно для этой пары. Организация читает выбранные поля на странице приглашения, и каждое чтение заново проверяет разрешение и видимость. Отзыв C4, отзыв C2, закрытие публикации и скрытие организации закрывают чтение сразу; повторная публикация закрытое разрешение не открывает. См. [чтение и отзыв](ARCHITECTURE.md#чтение-контактов-и-отзыв).
|
||||
|
||||
### Изоляция компаний и холдинги
|
||||
|
||||
- Организационные операции отвечают на чужие идентификаторы тем же отказом, что и на случайный идентификатор. Поиск, приглашения и чтение контактов доступны только владельцу организации.
|
||||
- Организации одного аккаунта образуют холдинг: компании на уровне E0 делят общие квоты (в демонстрационной политике 10 приглашений за 7 дней и 50 уникальных просмотров карточек за 24 часа). Число организаций на аккаунт не ограничено. См. [COMPANY_QUOTAS](COMPANY_QUOTAS.md#пул-холдинга).
|
||||
|
||||
### Уведомления и почта
|
||||
|
||||
- Inbox в обоих кабинетах; единственный продуктовый источник - доставленное приглашение. Запись появляется через outbox, relay и Kafka после фиксации, а не внутри транзакции отправки. См. [внутренние уведомления](ARCHITECTURE.md#внутренние-уведомления).
|
||||
- Письмо о приглашении проходит через outbox и обработчик доставки, а отправляет его отдельный цикл уведомлений (worker в процессе backend); перед каждой отправкой он заново проверяет права получателя и оставляет резерв квоты служебной почте. Тело письма нейтрально и не содержит контактов. См. [отправку продуктовых уведомлений](ARCHITECTURE.md#отправка-продуктовых-уведомлений).
|
||||
- Обращения в поддержку в обоих кабинетах.
|
||||
|
||||
### Гарантии приватности
|
||||
|
||||
- До записи C4 и разрешения организация не получает контакты; карточки, результаты поиска, списки приглашений и уведомления не содержат email, телефона и имени.
|
||||
- Логи сервера, payload outbox, строки inbox и запросы писем не содержат значений контактов и профиля (проверяет интеграционный тест изоляции, см. раздел 5).
|
||||
- Ответы организаций не содержат PDF и сохраненных снимков поиска: таких операций нет.
|
||||
|
||||
## 2. Как запустить
|
||||
|
||||
Все команды выполняются из корня репозитория. Требуются Docker с Compose, GNU make, python3 и openssl; GPU и внешние ключи не нужны. Полная инструкция: [быстрый старт](DEPLOY.md#запуск-mvp-быстрый-старт).
|
||||
|
||||
### Рабочий стенд
|
||||
|
||||
cp .env.example .env # замените каждое replace-this-... и задайте IDENTITY_KEY_SECRET
|
||||
make -C deploy config
|
||||
make -C deploy up
|
||||
curl http://localhost:8080/api/v1/healthz
|
||||
|
||||
Открывайте http://localhost:8080 (значение `APP_PUBLIC_URL`). Для писем задайте `EMAIL_PROVIDER=resend`, `RESEND_API_KEY` и `EMAIL_FROM` в окружении сервера. Чистый стенд содержит миграции и стартовую политику; шаги оператора (нужен `DATABASE_URL`):
|
||||
|
||||
1. Опубликовать раздел подбора, без него поиск отвечает 500: `make -C backend policy-publish ARGS='matching --actor operator:<handle>'`. См. [политику подбора](DEPLOY.md#политика-подбора-на-стенде).
|
||||
2. Чтобы пройденный полный тест получал демонстрационную категорию, выставить `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`, перезапустить backend и аттестовать открытие категории командой `make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:<handle>'`. Публикация новой версии политики требует нового открытия и новой аттестации, поэтому выполняйте шаг 1 до начала попыток. См. [демонстрационные категории](DEPLOY.md#демонстрационные-категории-на-стенде).
|
||||
|
||||
Банк заданий на основном стенде не загружен, и руководство DEPLOY описывает его загрузку только в составе seed демонстрационного стенда, поэтому тест на основном стенде начать нельзя. Для показа полного пути используйте демонстрационный стенд.
|
||||
|
||||
### Демонстрационный стенд и маршрут жюри
|
||||
|
||||
make -C deploy demo-seed DEMO_MODE=isolated
|
||||
|
||||
Команда поднимает отдельный проект на http://localhost:8090, публикует политику с разделом подбора, загружает синтетический банк, аттестует категорию и создает аккаунты `candidate@`, `prepared-1@` - `prepared-6@`, `employer-alpha@` и `employer-beta@` в домене `demo.lincodex.test`; пароль берется из `deploy/demo/demo.env` или `demo.env.example`. Гид жюри открыт по адресу http://localhost:8090/demo; он восьмиминутный и есть только в сборке этого стенда. Маршрут: экспресс-тест и полный тест кандидата, подготовленные кандидаты с опубликованными карточками, потребность и поиск владельца "Альфа", приглашение, принятие с C4 и чтение контактов. См. [демонстрационный стенд](DEPLOY.md#3-демонстрационный-стенд), [маршрут](DEPLOY.md#4-маршрут-демонстрации) и [изолированный стенд](DEPLOY.md#изолированный-демонстрационный-стенд). Сброс: `make -C deploy demo-reset DEMO_MODE=isolated` (отказывает, если на стенде есть обычные аккаунты).
|
||||
|
||||
### Восстановление из манифеста выпуска
|
||||
|
||||
make -C deploy release-build
|
||||
make -C deploy release-smoke
|
||||
make -C deploy release-e2e
|
||||
make -C deploy release-manifest RELEASE_ID=<id>
|
||||
make -C deploy release-up RELEASE_ID=<id>
|
||||
make -C deploy release-manifest-verify RELEASE_ID=<id> RELEASE_VERIFY_PROJECT=<project>
|
||||
make -C deploy demo-seed DEMO_MODE=isolated RELEASE_ID=<id>
|
||||
|
||||
Манифест неизменяем: он фиксирует исходники, lockfiles, Compose-файлы и image ID образов, а `release-up` запускает их без сборки и скачивания и сверяет хеши. Манифест публикуется только для чистого дерева и после успешных smoke и E2E на этих образах. `release-manifest-verify` сравнивает запущенные контейнеры с манифестом. Демонстрационный стенд из манифеста не содержит гида `/demo`, потому что берет фронтенд основного выпуска. Банк оценки в манифесте не снимается (`product_data_status` равен `partial`). См. [манифест выпуска](DEPLOY.md#манифест-выпуска).
|
||||
|
||||
## 3. Ограничения демонстрационной категории
|
||||
|
||||
- Банк заданий небольшой и синтетический: 25 семейств для полного теста и три для экспресс-теста. Семейства проходят штатный конвейер публикации с метками автора и проверяющего, но предметной проверки содержание не проходило.
|
||||
- Пороги не откалиброваны, перцентиль не считается, а адаптивного теста нет. Результат показывает механику, а не измеренную квалификацию.
|
||||
- В API основание категории равно `synthetic_demo` и описано в контракте как демонстрационная категория, не являющаяся проверенным измерением. В интерфейсе по решению владельца продукта она показана как обычное подтверждение (подпись "Результат теста"). API и эта документация сохраняют основание.
|
||||
- Экспресс-тест не назначает грейд ни при каких настройках.
|
||||
- Тексты согласий C1-C5 публикуются миграциями как `demo`, без юридической проверки. Не регистрируйте на демонстрационном стенде реальных людей.
|
||||
|
||||
## 4. Что не реализовано
|
||||
|
||||
Следующее относится к полному продукту и не работает в этом выпуске:
|
||||
|
||||
- практика с кодом (песочница) и адаптивный тест;
|
||||
- финальный раунд торга и встречные предложения: состояние `counter` не создает ни одна операция, повышение зарплаты отвечает 501 `not_implemented`;
|
||||
- назначение интервью и напоминания;
|
||||
- отзыв приглашения организацией и отмена участия кандидатом: обе операции отвечают 501;
|
||||
- роли, кроме владельца, и назначения по потребностям: искать, приглашать и читать контакты может только владелец организации;
|
||||
- PDF-документы и сохраненные снимки выдачи поиска;
|
||||
- рекомендации категорий для потребности: ответ потребности сообщает состояние `pending` или `not_available` с пустым списком;
|
||||
- включенный ML inference: сервис ML запускается отдельно без модели, backend его не вызывает;
|
||||
- интеграция с ФСП: нет ни режима, ни fixture-провайдера, ни обращений к внешнему API;
|
||||
- транспорт SMTP: выбор `EMAIL_PROVIDER=smtp` останавливает backend при запуске;
|
||||
- интеграция с ATS;
|
||||
- сброс пароля, загрузка и разбор резюме, письма о событиях, кроме подтверждения и нового приглашения.
|
||||
|
||||
## 5. Как проверено
|
||||
|
||||
Итог приемки на проверенном коммите (10.10.2026): `make verify` прошел, включая 110 интеграционных тестов и технический smoke; `make -C deploy test-e2e-registration` - 95 passed, 1 skipped; `make -C deploy test-e2e` - 64 passed, 32 skipped; `make -C security install test check` и `make security-images` прошли без блокирующих находок (сканеры запускались в Linux-контейнере, как в CI, потому что их установщик поддерживает только Linux; исключение для CVE-2026-93687 действует до 19.10.2026). Границы каждой проверки описаны в [TESTING](TESTING.md#команды).
|
||||
|
||||
| Проверка | Что подтверждает |
|
||||
| --- | --- |
|
||||
| `make verify` | Генерацию контрактов без расхождений, форматирование, линтеры, типы, сборку, Compose, документацию, backend с race detector, интеграционные тесты на PostgreSQL, Redis, SeaweedFS и Kafka и технический smoke |
|
||||
| `make -C deploy smoke` | Запуск стека, готовность зависимостей и отказы зависимостей; бизнес-сценарий не проверяет |
|
||||
| `make -C deploy test-e2e` | Браузерный набор Playwright на одноразовом стеке с отключенной почтой, включая `mail-unavailable.spec.ts`: пользователь видит, что письмо может прийти позже, и не входит до подтверждения |
|
||||
| `make -C deploy test-e2e-registration` | Регистрацию, подтверждение ссылкой и кодом и вход через локальный Resend-совместимый inbox, а в нем `acceptance-path.spec.ts` |
|
||||
| `acceptance-path.spec.ts` | Минимальный путь на настоящем backend: пять кандидатов, полный тест с категорией `synthetic_demo`, публикация, потребность, поиск с объяснением и фильтром, приглашения, принятие с C4, чтение контактов, отказ, отзыв C2 и отсутствие дубликатов при обновлении и двойном принятии. См. [путь до контактов](TESTING.md#минимальный-путь-от-регистрации-до-раскрытых-контактов) |
|
||||
| `TestCompanyIsolationAndRevocationOverHTTP` | Изоляцию компаний и кандидатов, мгновенное закрытие после скрытия, отзыва C4 и C2 и отсутствие контактов в логе, outbox, inbox и запросах писем. См. [тесты организаций](TESTING.md#тесты-организаций) |
|
||||
| `TestInvitationNoticesSurviveRelayAndConsumerRestarts` | Ровно одно уведомление и одно письмо на получателя после перезапусков relay и потребителей и потери offset |
|
||||
| `TestHoldings`, `TestCompanyQuota` | Общий пул квот E0 внутри холдинга и отсутствие превышения при параллельных резервированиях |
|
||||
| `make -C security check`, `make -C security images` | Уязвимости зависимостей, секреты, опасные конструкции и образы; см. [SECURITY](SECURITY.md) |
|
||||
| `make -C deploy check-demo`, `make docs-check` | Охранные проверки целей демонстрационного стенда и структуру документации |
|
||||
| `make -C deploy release-smoke`, `release-e2e` | Те же smoke и браузерный набор на образах выпуска; успешный прогон дает evidence для манифеста |
|
||||
|
||||
Что проверки не доказывают: калибровку оценки, точность подбора, доставку писем через настоящий Resend, работу за HTTPS и production-нагрузку.
|
||||
+27
-35
@@ -1,62 +1,54 @@
|
||||
# Проверки безопасности
|
||||
# Безопасность
|
||||
|
||||
В репозитории есть локальные и CI-проверки известных уязвимостей зависимостей, отдельных рисков конфигурации, секретов и опасных конструкций в исходниках. Они относятся к техническому каркасу. Они не подтверждают полную безопасность и не проверяют будущие сценарии авторизации и обработки персональных данных.
|
||||
Защита данных обеспечивается серверными проверками доступа и границами сервисов. Сканеры проверяют известные уязвимости и выбранные опасные конструкции; они не заменяют проверку бизнес-сценариев или аудит.
|
||||
|
||||
## Команды
|
||||
## Проверки
|
||||
|
||||
Запускайте из корня репозитория:
|
||||
Из корня репозитория:
|
||||
|
||||
```sh
|
||||
make -C security install
|
||||
make -C security check
|
||||
make -C security test
|
||||
make -C security test check
|
||||
make -C security images
|
||||
```
|
||||
|
||||
Для установки нужны Python, uv, Go и доступ к сети. Установщик бинарных файлов Trivy/Gitleaks поддерживает Linux amd64 и arm64. Инструменты размещаются в `security/.bin/`, `.tools/` и `.cache/`; глобальные установки не изменяются. Установщик выбирает текущие стабильные версии Trivy и Gitleaks и сверяет скачанные архивы с SHA256-суммами из upstream. govulncheck устанавливается через `go install ...@latest`. Semgrep использует отдельное окружение uv tool с Python 3.13; uv размещает управляемый Python в `security/.tools/python/`. При следующей установке версии могут измениться; для воспроизведения находки сверяйтесь с выводом установки.
|
||||
|
||||
| Цель | Область проверки |
|
||||
| Инструмент | Текущая область |
|
||||
| --- | --- |
|
||||
| `filesystem` | Trivy проверяет зависимости и конфигурацию репозитория по `trivy/filesystem.yml` |
|
||||
| `secrets` | Gitleaks проверяет отслеживаемые и неигнорируемые файлы, а также всю доступную историю Git по `gitleaks/gitleaks.toml` |
|
||||
| `go` | govulncheck анализирует использование известного уязвимого Go-кода в backend |
|
||||
| `semgrep` | Локальные правила `semgrep/frontend.yml` и `semgrep/python.yml` проверяют исходники frontend и ML |
|
||||
| `rule-test` | Фикстуры Semgrep проверяют ожидаемые срабатывания и допустимые примеры локальных правил |
|
||||
| `test` | Запускает фикстуры правил Semgrep и тесты установки, входов и отчетов Gitleaks, кода ошибки govulncheck и устаревших отчетов |
|
||||
| `check` | Запускает проверки файлов, секретов, Go и Semgrep; выполняет каждую и возвращает ошибку, если хотя бы одна не прошла |
|
||||
| `images` | Собирает образы backend, frontend и ML, затем проверяет каждый точный локальный ID образа через Trivy |
|
||||
| Trivy filesystem | Зависимости, lock-файлы и конфигурация репозитория |
|
||||
| Gitleaks | Отслеживаемые и неигнорируемые файлы, полная доступная история Git |
|
||||
| govulncheck | Использование уязвимого кода в `backend/` |
|
||||
| Semgrep | Локальные правила для `frontend/src/` и `ml/src/` |
|
||||
| Trivy images | Точные локальные ID образов backend, frontend и ML |
|
||||
|
||||
Gitleaks требует полный Git checkout. Отсутствие репозитория или неполная история завершают проверку ошибкой; история не пропускается молча. Текущая проверка файлов берет отслеживаемые Git файлы и неигнорируемые незакоммиченные файлы. Отслеживаемые файлы остаются во входах, даже если Git игнорирует их; игнорируемый локальный `.env` не включается. Удаленные отслеживаемые пути и символические ссылки не входят в текущую проверку; цели ссылок не открываются и не читаются. Проверка истории по-прежнему охватывает все ссылки и находит значения, закоммиченные до игнорирования или удаления файла. Gitleaks копирует текущие входы во временную директорию с доступом только для владельца и завершает проверку ошибкой, если сканер падает или JSON-отчет отсутствует либо поврежден. Значения найденных секретов скрываются в отчетах. Кеши инструментов и результаты сборки исключаются согласно конфигурации; lock-файлы зависимостей приложения остаются входами проверок. Trivy также распознает `requirements-*.txt`, включая `backend/requirements-quality.txt` и `scripts/requirements-codegen.txt`.
|
||||
Проверки не включают отдельные Go-модули и образы runner/labd. Go-линтер backend дополнительно запускает gosec. Для образов нужен Docker; установка требует сеть, Python, uv и Go. Инструменты ставятся локально, а текущие версии сохраняются с отчетами.
|
||||
|
||||
Для проверки образов нужен Docker. Контекст сборки backend - `backend/`, frontend и ML - корень репозитория. Образы получают теги `lincodex-security-<service>:local`; перед сканированием определяется ID каждого образа. Команда не запускает контейнеры и не публикует образы. Проверка зависимостей исходников frontend остается необходимой: итоговый Nginx-образ содержит собранные ресурсы, а не дерево зависимостей разработки.
|
||||
`HIGH`/`CRITICAL` Trivy, включая находки без исправления, блокируют проверку. Находки остальных сканеров и ошибки самих инструментов тоже дают ошибку. Неполная Git-история, пропавший или поврежденный отчет не считаются успехом. Отчеты в `security/reports/` локальные и содержат скрытые значения секретов; не публикуйте их без проверки.
|
||||
|
||||
## Находки и исключения
|
||||
CI вызывает те же Make-цели. Наличие workflow не доказывает успешный запуск на текущем коде; перед выпуском нужны результаты конкретного прогона. Образы проверяются вместе с исходными lock-файлами: статическая сборка frontend сама не содержит всех зависимостей разработки.
|
||||
|
||||
Находки Trivy с уровнем `HIGH` или `CRITICAL` завершают проверку ошибкой, включая уязвимости без опубликованного исправления, если для находки нет действующего адресного исключения. Находки Gitleaks, настроенных правил Semgrep, govulncheck и ошибки самих сканеров также завершают соответствующие цели ошибкой. В конфигурации Go-линтера остается gosec; новые проверки дополняют его.
|
||||
## Исключения
|
||||
|
||||
Перед изменением зависимостей или конфигурации проверьте указанный пакет, установленную версию, затронутый путь и доступное исправление. Отчеты хранятся локально: `security/reports/` исключен из Git. govulncheck использует текстовый вывод, чтобы сохранить собственный код завершения при находках. Trivy сохраняет JSON-отчеты и печатает их таблицы в лог проверки. Ошибка сканирования, отсутствие отчета или ошибка его преобразования сохраняют блокирующий результат.
|
||||
[Trivy ignore](../../security/trivy/ignore.yml) содержит адресное исключение `CVE-2026-93687` для `braces@3.0.3` в lock-файле frontend, до 2026-10-19. Оно согласовано при отсутствии исправления; сопровождающие должны удалить его после обновления или пересмотреть до истечения срока. Это не исключение для всех версий пакета или образов.
|
||||
|
||||
В [security/trivy/ignore.yml](../../security/trivy/ignore.yml) есть одно временное исключение, согласованное владельцем проекта 2026-10-05: `CVE-2026-93687` для `pkg:npm/braces@3.0.3` в `frontend/pnpm-lock.yaml`. На момент согласования исправленной версии не было; исключение разблокирует CI зависимостей до истечения срока 2026-10-19. Ответственные - сопровождающие проекта: исключение нужно удалить после появления исправления или пересмотреть до истечения срока. Trivy автоматически учитывает дату окончания. Файл исключений применяется только к проверке файлов; скрытые из блокирующего результата находки остаются видимыми в JSON-отчете. Проверка образов не изменяется.
|
||||
[Gitleaks allowlist](../../security/gitleaks/gitleaks.toml) ограничивает исключения точными тестовыми примерами, путями и правилами. Дата ручного пересмотра - 2026-11-07; Gitleaks ее не контролирует. Новое исключение требует конкретной находки, причины, ответственного и срока. Не отключайте сканеры и не скрывайте все неисправленные уязвимости ради зеленого CI.
|
||||
|
||||
Восемь исключений Gitleaks относятся только к точным примерам API, тестовым фикстурам, фикстуре release manifest и статическому префиксу ключа Redis rate limit. Для каждого должны совпасть правило, путь в репозитории и полный текст находки. Ответственные - сопровождающие проекта. Вручную пересмотрите исключения или удалите их до 2026-11-07; Gitleaks не проверяет эту дату пересмотра. Описание работы allowlist приведено в официальной [документации Gitleaks](https://github.com/gitleaks/gitleaks#configuration).
|
||||
## Данные и сетевые границы
|
||||
|
||||
Любое следующее исключение ограничивайте конкретной находкой и входными данными, указывайте причину, ответственного и срок действия, затем отдавайте изменение на ревью. Текущая интеграция не обеспечивает автоматический контроль срока одинаково для всех инструментов; там, где его нет, проверяйте срок вручную. Не отключайте сканер целиком и не скрывайте все уязвимости без исправлений ради успешной проверки.
|
||||
- Авторизация, членство компании, согласия, публикация и разрешения на контакты проверяются на сервере при каждом доступе. Кеш, snapshot или скрытая кнопка не заменяют проверку.
|
||||
- Пароли, session tokens, одноразовые коды, контакты, тексты резюме и тела запросов не попадают в логи и labels метрик. Письмо подтверждения передает код только его адресату; ошибки API не раскрывают внутренний текст ошибок.
|
||||
- SeaweedFS остается в отдельной внутренней сети; браузер не получает S3-ключи или прямой доступ к bucket. Не все его внутренние интерфейсы проверяют S3-аутентификацию, поэтому доступ к сети строго ограничен.
|
||||
- Секреты находятся в локальном окружении или secret-файлах, не в Git. Readiness, метрики и административные интерфейсы не публикуются через Nginx.
|
||||
|
||||
## Исходящие запросы и ML
|
||||
|
||||
- GitHub. Проверка репозиториев проектов обращается только к `https://api.github.com`: адрес в профиле принимается только в форме `https://github.com/<owner>/<repo>`, владелец и имя проверяются по шаблонам GitHub и экранируются в путь, базовый origin зашит в коде (тесты подменяют его только внутри пакета), прокси из окружения не используется, TLS 1.2+, таймауты соединения и ответа, редирект допускается только на тот же origin (не больше трех), ответы ограничены 1 MiB, README - 64 KiB. Поэтому пользовательский ввод не может направить сервер на другой хост (SSRF). Проверки выключены по умолчанию (`GITHUB_REPOSITORY_CHECKS_ENABLED`), повторная проверка ограничена на кандидата (`REPOSITORY_CHECK_INTERVAL`), лимит GitHub соблюдается по заголовкам.
|
||||
- Токен. `GITHUB_TOKEN` необязателен, нужен только для чтения публичных данных и отправляется только на `api.github.com`; он не попадает в логи, ошибки, задания и базу. Журнал проверки содержит id задания, попытку, состояние и класс ошибки, но не репозиторий; ключ и payload задания несут только дайджест репозитория.
|
||||
- Данные GitHub. Описание, темы, языки и текст README - недоверенные данные: README превращается в простой текст, хранится только для публичного репозитория, используется только для ранжирования и никогда не выводится, тем более как HTML. Адрес и владелец репозитория не попадают организации ни в карточке, ни в объяснении, ни после C4.
|
||||
- ML. Все маршруты сервиса, кроме `/healthz` и `/readyz`, требуют `Authorization: Bearer <token>`: общий случайный токен не короче 32 печатных символов (`ML_SERVICE_TOKEN` у backend, `ML_SERVICE_TOKEN` или `ML_SERVICE_TOKEN_FILE` у сервиса) сравнивается за постоянное время и не попадает в логи, ответы и сообщения об ошибках; неверный или отсутствующий токен получает 401 `unauthenticated`, а запрос отклоняется до чтения тела. Без токена сервис отвечает только клиентам с loopback, а точка входа `python -m lincodex_ml.serve` отказывается слушать не-loopback адрес; backend без токена не включает семантический подбор. В Compose сервис доступен backend по сети `http://ml:8000`, порт на хосте - loopback; на GPU-хосте он слушает приватный адрес LAN без TLS, поэтому ограничьте порт адресом хоста приложения средствами хоста или сети. `/metrics` тоже требует токен. Backend передает в ML только тексты опубликованной карточки и потребности организации, без контактов и приватного профиля. Веса берутся по lock-файлам с SHA-256, удаленный код моделей не исполняется, pickle не загружается, сервис работает офлайн.
|
||||
GitHub-проверка выключена по умолчанию. Она принимает только публичные ссылки `https://github.com/<owner>/<repo>`, обращается к фиксированному `api.github.com`, ограничивает редиректы, время и объем ответа. Произвольный URL не становится сетевым назначением. README и метаданные остаются недоверенными данными, не исполняются и не отображаются как пользовательский HTML. Токен не сохраняется в заданиях и логах.
|
||||
|
||||
## CI и границы проверок
|
||||
Backend отправляет ML только разрешенную проекцию карточки и потребности, без контактов и приватного профиля. Все маршруты ML, кроме `/healthz` и `/readyz`, требуют bearer-токен; без него сервис допускает только loopback. `/metrics` защищен тем же токеном, но текущий Prometheus scrape ML еще не передает его. Между хостами доступ к порту ML нужно ограничить: токен не шифрует HTTP-трафик.
|
||||
|
||||
CI запускает `make -C security test check` для исходников и `make -C security images` для образов и включает обе проверки в обязательный общий результат. Отчеты загружаются как artifacts со сроком хранения 14 дней, в том числе при ошибке проверки. Gitleaks скрывает значения секретов, но отчеты могут раскрывать пути репозитория и сведения о зависимостях; доступ к artifacts должен это учитывать.
|
||||
|
||||
Локальные правила Semgrep покрывают ограниченный набор случаев для frontend и ML, а не полный аудит приложения. Результаты сканеров зависят от checkout, версий правил, баз уязвимостей, входов сборки и времени запуска. Наличие workflow в репозитории не подтверждает запуск в GitHub или отсутствие находок в текущих файлах. При подготовке релиза фиксируйте фактические результаты; другие границы валидации описаны в [TESTING.md](TESTING.md).
|
||||
Модельные файлы закреплены SHA-256, загружаются локально; удаленный код модели и pickle не исполняются. Ответ модели - данные, а не инструкция для команды, инструмента или изменения прав.
|
||||
|
||||
## VM исполнителя кода
|
||||
|
||||
Исполнитель запускает недоверенный код кандидатов, поэтому в production он работает только в VM LXD `lincodex-runner` (см. [DEPLOY.md](DEPLOY.md#production-vm-исполнителя)). У границы три слоя: nsjail с seccomp, пространствами имен, лимитами cgroup v2 и без сети для программы; отдельное гостевое ядро; ACL моста, который разрешает открыть TCP 8443 только сети приложения и стороне хоста и отбрасывает любое соединение, начатое гостем. В VM есть только ее собственная TLS-пара и токен API. Ключ CA и секреты базы данных, почты, хранилища и identity в нее не попадают, общих папок, сокета Docker и гостевого API (`security.devlxd=false`) у нее нет.
|
||||
В production runner размещается в отдельной VM. Внутри nsjail ограничивает программу через пространства имен, seccomp, cgroup v2 и отсутствие сети. VM не получает секреты базы, почты, хранилища или identity, общие каталоги и сокет Docker. TLS и токен защищают API; сетевые ACL ограничивают доступ к нему и исходящие соединения гостя.
|
||||
|
||||
`make -C deploy check-runner-vm` проверяет скрипт VM без LXD. На хосте приложения `make -C deploy runner-vm-check` проверяет работающую VM, а `make -C deploy runner-vm-a16` запускает в ней набор враждебных программ. Эти проверки не покрывают уязвимости ядра, QEMU, KVM, nsjail и LXD, побочные каналы и сам хост: группа `lxd` равносильна root на хосте, и ее участники могут открыть root-shell в госте через агент LXD. Токен - общий секрет без автоматической ротации: чтобы заменить его, удалите `api-token` из каталога секретов, запустите `runner-vm-secrets` и `runner-vm-install` и передайте backend новое значение. Мониторинга у VM пока нет.
|
||||
`make -C deploy check-runner-vm` проверяет конфигурацию без запуска VM. Проверки работающей VM и изоляции выполняются отдельно по [DEPLOYMENT.md](DEPLOYMENT.md) и [TESTING.md](TESTING.md). Они не доказывают отсутствие уязвимостей ядра, гипервизора или nsjail. Привилегированный dev-контейнер не является production-границей; автоматическая ротация токена и мониторинг VM пока не подключены.
|
||||
+93
-664
@@ -1,715 +1,144 @@
|
||||
# Проверки и оценка качества
|
||||
# Тестирование
|
||||
|
||||
Обычные проверки подтверждают отдельные свойства кода. Они не доказывают точность подбора, валидность грейдов, production latency или готовность продукта целиком.
|
||||
[English](../en/TESTING.md)
|
||||
|
||||
Выбирайте проверки по изменению. Unit-тест проверяет правило, интеграционный тест - реальные зависимости, браузерный E2E - действия пользователя. Команды выполняются из корня репозитория.
|
||||
|
||||
## Команды
|
||||
|
||||
Используйте Make targets из корня:
|
||||
|
||||
make test
|
||||
make check
|
||||
make verify
|
||||
make docs-check
|
||||
|
||||
make test запускает backend, frontend и ML тесты. make check также выполняет проверки API контрактов, форматирование, линтеры, типы, build, Compose, observability и docs-check. make verify последовательно генерирует контракты, проверяет generated drift, запускает root check, API toolchain/backend race и integration проверки, а затем изолированный deployment smoke. Он использует Docker.
|
||||
|
||||
Полезные узкие команды:
|
||||
|
||||
| Команда | Что проверяет |
|
||||
| --- | --- |
|
||||
| make -C api check | Объединение схем, bundles, OpenAPI lint и тесты merge script |
|
||||
| make -C backend test | Go unit suite с race detector |
|
||||
| make -C backend test-fast | Быстрый Go test без race instrumentation |
|
||||
| make -C backend test-int | Go integration tests с Testcontainers/PostgreSQL/Redis/SeaweedFS/Kafka |
|
||||
| make -C frontend check | Prettier, ESLint, Stylelint, TypeScript, Vitest, FSD boundaries и build |
|
||||
| make -C ml check | Ruff, mypy, pytest и сборку wheel |
|
||||
| make -C ml check-generated | Соответствие Pydantic-моделей ML bundle без перезаписи файлов |
|
||||
| make -C deploy config | Рендер Compose конфигураций без запуска |
|
||||
| make -C deploy check | Рендер Compose конфигураций, `check-workflows`, который падает, если job `aggregate` в workflow не зависит от всех остальных jobs или не имеет `if: always()`, и `check-release`; см. [Тесты манифеста выпуска](#тесты-манифеста-выпуска) |
|
||||
| make -C deploy smoke | Изолированный технический smoke по service health routes |
|
||||
| make -C deploy test-e2e | Браузерный набор Playwright на изолированном одноразовом стеке |
|
||||
| make -C deploy release-smoke, release-e2e | Тот же smoke и браузерный набор на образах выпуска; успешный прогон записывает evidence для манифеста выпуска |
|
||||
| make -C observability check | Проверку конфигурации и правил alerts Prometheus с их unit-тестами, Loki, Alloy и dashboard JSON |
|
||||
| make -C observability verify-product-metrics | Изолированные стенды core и monitoring: продуктовые метрики в Prometheus и Grafana, отсутствие fixture адреса в метриках и логах Loki; см. [Тесты продуктовых метрик](#тесты-продуктовых-метрик) |
|
||||
|
||||
make -C deploy test-e2e сейчас запускает технический браузерный набор, а не проверку бизнес-сценариев; см. [Браузерный E2E набор](#браузерный-e2e-набор).
|
||||
|
||||
make -C ml check-generated использует datamodel-code-generator --check: расхождение завершает проверку ошибкой, а файл моделей остается неизменным. Перед проверкой обновите bundle через make -C api bundle; для обновления Python-моделей используйте make -C ml generate. Сгенерированные модели не подтверждают наличие inference или поддержку всех возможностей OpenAPI 3.2.
|
||||
|
||||
Проверки безопасности запускаются отдельно: `make -C security check` проверяет исходники, зависимости и секреты, `make -C security test` проверяет фикстуры локальных правил Semgrep, целостность установки и обработку ошибок govulncheck, `make -C security images` собирает и сканирует образы трех сервисов. Сначала установите инструменты через `make -C security install`. Ошибка сканера означает неуспешную проверку, а не отсутствие находок. Требования к Git/Docker, блокирующие находки и отчеты CI описаны в [SECURITY.md](SECURITY.md).
|
||||
|
||||
## Что покрывает текущий каркас
|
||||
|
||||
Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, закрытому файловому слою и контролю доступа SeaweedFS (см. [Тесты закрытого файлового хранилища](#тесты-закрытого-файлового-хранилища)), тестовой обвязке Kafka (записи с ключом и заголовками и порядок внутри партиции, отказ создавать отсутствующий топик по запросу и очистка топиков), relay outbox (см. [Тесты relay outbox](#тесты-relay-outbox)), runtime обработчиков событий (см. [Тесты обработчиков событий](#тесты-обработчиков-событий)), доставкам писем (см. [Тесты доставки писем](#тесты-доставки-писем)), метрикам, API client, ML schema и доступности текущих endpoint. Регистрация и подтверждение email проверяются API integration-тестами; вход, тестирование, поиск, приглашения и работа с файлами пока не реализованы. Подтверждение записывает событие в transactional outbox, но для него нет зарегистрированного продуктового обработчика; обработчик доставки писем проверяется отдельно. Реального model inference как бизнес-результата нет.
|
||||
|
||||
TestEmailVerificationOverHTTP получает токен из Resend fixture после регистрации. Тест проверяет подтверждение candidate и employer, отсутствие сессии и cookie, неизменность состояния при неизвестном, истекшем, замененном или погашенном токене, неверном пароле и отсутствии отложенных данных. Он также проверяет привязку C1 к версии регистрации, отсутствующий, null и чужой Origin, а также лимиты, истечение срока после ожидания блокировки, откат после сбоя outbox и одно событие при параллельном подтверждении. Тест охватывает только API; внешний почтовый провайдер не вызывается. Frontend проверяет отдельный локальный браузерный поток регистрации.
|
||||
|
||||
TestEmailVerificationCodeOverHTTP (`backend/integration_test/email_code_test.go`) берет код и ссылку из одного сообщения фикстуры. Он проверяет, что код подтверждает регистрацию так же, как ссылка; что пять неверных кодов аннулируют токен, после чего правильный код и ссылка не работают; что восемь параллельных неверных кодов засчитываются ровно как пять попыток; что неверный пароль засчитывается; что истекший код не отменяет ссылку; что ссылка и код погашают один токен в любом порядке; что повторная отправка заменяет код; что регистрация, замененная другой регистрацией, не подтверждается своим кодом; что неизвестный адрес и неверный код дают один и тот же отказ; что лимит адреса отвечает 429 после десяти запросов. Тест origin отклоняет чужой Origin до запуска usecase.
|
||||
|
||||
API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub.
|
||||
|
||||
Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket, изоляцию SeaweedFS от frontend (по имени и по адресу в сети хранилища), отказ HTTP API filer, master и volume на запросы не изнутри контейнера SeaweedFS и запись в логе запуска backend о `EMAIL_PROVIDER=disabled`. В smoke-стеке relay backend подключается к Kafka, но smoke не проверяет, что он публикует события. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не отправляет писем и не проверяет доставку почты, получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения.
|
||||
|
||||
## Браузерный E2E набор
|
||||
|
||||
`make -C deploy test-e2e` запускает набор Playwright из `frontend/e2e/` в Chromium на настоящих образах frontend и backend. Нужны Docker и зависимости frontend, установленные через `make -C frontend install`; браузер на хост не ставится. `deploy/scripts/e2e.sh` делает следующее:
|
||||
|
||||
- Читает точную версию `@playwright/test` из `frontend/package.json`, проверяет, что установлена та же версия, и запускает набор в официальном образе `mcr.microsoft.com/playwright:v<version>-noble`, где `frontend/` смонтирован только для чтения.
|
||||
- Поднимает основной стек под уникальным проектом `lincodex-e2e-<random>` со свежими томами и сгенерированным одноразовым env-файлом: случайные пароли, `EMAIL_PROVIDER=disabled`, без настроек почтового транспорта. Переменные оболочки, кроме настроек Docker-клиента, в Compose не попадают. Запуск отказывается переиспользовать существующие проект, сеть или том.
|
||||
- Не публикует host-порт. Контейнер браузера разделяет сетевое пространство контейнера frontend и открывает `http://localhost:8080`, тот же loopback origin, что и `APP_PUBLIC_URL`. Конфигурация Playwright отклоняет base URL вне loopback-хоста.
|
||||
- Запускает Playwright с UID/GID хоста в rootful Docker; в rootless Docker использует container UID 0, который соответствует владельцу каталога артефактов на хосте. Runner удаляет все capabilities, исходники смонтированы только для чтения.
|
||||
- Ждет готовности backend, запускает набор без повторов и возвращает его код завершения; make сообщает о любой ошибке кодом 2.
|
||||
- При любом завершении, включая ошибку и прерывание, удаляет контейнеры, тома, сеть, локально собранные образы и env-файл. Остаются только закешированный образ Playwright и кеш сборки.
|
||||
|
||||
Все браузеры одного прогона обращаются к стенду с одного клиентского адреса: контейнер браузера разделяет сетевое пространство контейнера frontend, и app Nginx видит все запросы с loopback. Поэтому лимит на адрес для `/api/v1/` (20 запросов в секунду с burst 60, `deploy/nginx/nginx.conf` и `deploy/nginx/conf.d/app.conf`) общий для всего набора. 429 от этого лимита означает сбой стенда, а не результат проверяемого сценария; продуктивные лимиты не меняются, их по-прежнему проверяет `deploy/scripts/test_perimeter.py`. Набор укладывается в бюджет по замыслу. `frontend/playwright.config.ts` запускает один воркер. `frontend/e2e/assessment.spec.ts` делает паузу 250 мс после каждого сохраненного ответа полной попытки, потому что кандидат читает каждый пункт. Поиск по реальному банку в `frontend/e2e/match-search.spec.ts` идет первым, в собственном проекте: нефильтрованный поиск по банку возвращает десять записей на группу, поэтому кандидаты, опубликованные более ранними спецификациями, определили бы, какие записи увидит тест. На стенде воспроизведение этого лимита по access-логу дало пик примерно в две трети burst при одном воркере и около десяти запросов до порога при двух.
|
||||
|
||||
Артефакты последнего прогона лежат в `frontend/test-results/e2e/`, который игнорируется Git; путь печатается в конце. В `report/` лежит HTML-отчет (`pnpm exec playwright show-report test-results/e2e/report` из `frontend/`). Для каждого упавшего теста `results/` сохраняет `trace.zip` и снимок экрана (`pnpm exec playwright show-trace <trace.zip>` требует локального браузера; trace.playwright.dev открывает файл без него). После неуспешного прогона `stand.log` содержит логи стека. `E2E_SPEC_DIR=<dir>` запускает спецификации из другого каталога, например из временной копии, на таком же изолированном стеке.
|
||||
|
||||
## Локальный браузерный тест регистрации с почтовым fixture
|
||||
|
||||
`make -C deploy test-e2e-registration` запускает тот же одноразовый браузерный стек с дополнительным `docker-compose.e2e-mail.yml` overlay. Только этот режим собирает backend с Go build tag `e2e`: его Resend-конструктор использует фиксированный адрес `http://mail-fixture:8025/emails`, а Compose передает ему синтетический ключ. Перед Playwright runner отправляет через Compose network одно синтетическое письмо, повторяет запрос с тем же idempotency key и проверяет сообщение в аутентифицированном inbox. Сервис `mail-fixture` принимает Resend-совместимые запросы, поддерживает дедупликацию по ключу и хранит в памяти не более 64 сообщений и 256 запросов размером до 32 KiB каждый. Его inbox требует bearer-аутентификацию, отдает только письма для запрошенного `to` и доступен изнутри стека. Сеть регистрации помечена internal, fixture не подключен к сети хранилища, а опубликованных host-портов нет; запросы не могут уйти во внешний почтовый сервис. Очистка удаляет контейнеры и inbox.
|
||||
|
||||
Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-fixture:8025/__e2e/inbox` и синтетический `E2E_MAILBOX_TOKEN=local-e2e-mailbox-token`. Тест запрашивает `GET $E2E_MAILBOX_URL?to=<urlencoded email>` с `Authorization: Bearer $E2E_MAILBOX_TOKEN`; ответ содержит `messages` с полями `id`, `to`, `subject`, `text` и `html`. Registration-only tests должны пропускаться без `E2E_MAIL_FIXTURE=1`, поскольку стандартный `test-e2e` и `release-e2e` его не задают. Тесты не должны выводить содержимое письма или ссылку с одноразовым токеном. В этом режиме runner отключает трассировку Playwright. Обычный `test-e2e` по-прежнему задает `EMAIL_PROVIDER=disabled`, а `release-e2e` использует release-образы без fixture и не пишет evidence для mail-fixture образа. Режим отказывается запускаться с `LINCODEX_RELEASE_TAG`.
|
||||
|
||||
Текущий набор (`frontend/e2e/smoke.spec.ts`) проверяет, что SPA отдает `/` с `lang="ru"` и заголовком, что `/status` показывает техническую страницу с живым API, что `/api/v1/healthz` через прокси frontend возвращает 200 `{"status":"ok"}`, что неизвестный маршрут SPA показывает страницу "не найдено" и что `/api/v1/missing` возвращает 404 `application/problem+json` с кодом `not_found`. Данные ему не нужны. Бизнес-тесты используют синтетические данные в свежем стеке каждого прогона: регистрацию через публичный API и отдельно описанный тестовый fixture для scope согласий. Реальные данные не используются.
|
||||
|
||||
`frontend/e2e/mail-unavailable.spec.ts` выполняется только в обычном `test-e2e`, стенд которого задает `EMAIL_PROVIDER=disabled`, и пропускается при `E2E_MAIL_FIXTURE=1`. На настоящем backend он регистрирует кандидата (202 `accepted`) и проверяет, что шаг ждет письмо ("Запрос принят", "Письмо может прийти не сразу") и нигде не говорит, что письмо отправлено или доставлено. Подобранный код и поддельная ссылка получают 400 `verification_token_invalid`; верный пароль получает 403 `email_not_verified` с сообщением в форме; после этого `GET /api/v1/identity/sessions/current` и `GET /api/v1/me/profile` отвечают 401, а `/candidate` показывает страницу входа. Строку доставки браузер не видит: то, что она остается `pending` без попыток, пока транспорт выключен, проверяет подтест `EMAIL_PROVIDER=disabled` в `TestServiceMailSending`.
|
||||
|
||||
Обычный технический набор не проверяет сценарии кандидата и работодателя, кроме неподтвержденной регистрации в `mail-unavailable.spec.ts`, успешный вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium и программы чтения с экрана. Его проверки заглушками основного пути (состояния, фокус и переполнение) описаны в разделе [Состояния и доступность основного пути](#состояния-и-доступность-основного-пути). CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-<n>` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate.
|
||||
|
||||
Режим регистрации дополнительно запускает `frontend/e2e/auth-registration.spec.ts`: регистрацию кандидата и работодателя с видимым C1, реальную локальную повторную отправку с получением нового письма, замену ссылки подтверждения в той же вкладке, повтор после неверного пароля, подтверждение без автоматического входа, вход и восстановление серверного шага после обновления. Проверяются фокус клавиатуры и отсутствие переполнения на 360, 768 и 1280 px. Отображение просроченной ссылки использует управляемый problem-ответ; реальное истечение токена проверяют backend integration tests. Только изолированный overlay задает `VERIFICATION_MAIL_MIN_INTERVAL=1s`; обычная среда и выпуск сохраняют свой настроенный интервал. Для auth-тестов отключены трассы, снимки при ошибках и видео; явные снимки для проверки показывают состояния без токенов и синтетические адреса. Внешняя почта и рабочий edge-путь не проверялись.
|
||||
|
||||
С появлением шага кода тот же набор проверяет подтверждение каждой регистрации кандидата и работодателя шестизначным кодом из письма: сначала неверный код, затем перезагрузка страницы, на которой пароль запрашивается снова, и проверка, что браузерное хранилище не содержит пароль. Отдельный тест оставляет ссылку запасным путем: истекшая ссылка ведет на шаг кода, который отправляет новое письмо, и ссылка из этого письма подтверждает регистрацию.
|
||||
|
||||
В этом же режиме runner перед браузером запускает `/consent-fixture` из тестового backend-образа. Команда доступна только с Go build tag `e2e`, требует `E2E_CONSENT_FIXTURE=1` и через домен и транзакционные порты создает синтетического подтвержденного кандидата, C1/C2 и два C4 для разных компаний. Совпадение тестового адреса с существующим аккаунтом останавливает запуск. Обычный и release-образы не содержат команду и не включают этот флаг. Сценарий `frontend/e2e/consent-management.spec.ts` использует обычный вход и реальные API согласий: отдельную выдачу C3, отзыв C2 и одного C4, сохранение другого scope, перезагрузку и C1 request со статусом из ответа. Отказ сервера для проверки UI задается управляемым 403; успешные изменения идут в PostgreSQL. Синтетические invitation IDs в fixture не доказывают реализацию принятия приглашений. Трассы и автоматические снимки отключены; явный снимок показывает только синтетические данные.
|
||||
|
||||
Та же команда создает второго синтетического кандидата для `frontend/e2e/privacy-visibility.spec.ts`: действующие C1 и C2, один C4 для первой из двух новых компаний и три записанных чтения карточки (просмотр карточки и чтение контактов первой компанией, просмотр карточки второй). Чтения вставлены через порт приватности, потому что путь чтения организацией требует результатов поиска, которых еще нет; они не доказывают этот путь. На настоящем backend набор подтверждает статус поиска без публикации, публикует после явного шага C2, сверяет предпросмотр владельца с ответом API, скрывает одну компанию и возвращает ее, отзывает C2 и проверяет объяснение закрытия, снова выдает C2 без открытия карточки и публикует заново только с клавиатуры; в режиме с почтовой фикстурой свежезарегистрированный кандидат с двумя заявленными специализациями и без теста публикуется и видит "Грейд не подтвержден" для каждой. Группа с подменой API показывает подтвержденный Backend рядом с неподтвержденными специализациями, подписи основы и калибровки доказательств, пустые истории, неудачное сохранение с сохранением черновика и отозванный C2. Ни один тест не читает карточку как работодатель, поэтому немедленная потеря доступа скрытого работодателя в браузере не проверяется.
|
||||
|
||||
`frontend/e2e/profile-edit.spec.ts` проходит шаги ручного профиля на 360 px после реальной регистрации (переход "Далее" с фокусом на заголовке, блокировка шага без подтверждения пересечения, "Назад" без потери данных), подтверждает пересечение периодов, сохраняет и перечитывает данные. Второй контекст меняет версию через API; первое окно сохраняет черновик при 412 и заменяет его только явным действием. Проверяются заморозка полей во время PUT, фокус, отсутствие переполнения на 360/768/1280 px и отбрасывание позднего ответа после смены аккаунта. Шаг согласий не считается завершенным сохранением профиля.
|
||||
|
||||
`frontend/e2e/candidate-home.spec.ts` состоит из двух частей. В режиме с почтовой фикстурой кандидат проходит регистрацию, профиль только с именем (без привязки ФСП ID), анкету и повторный вход: главная ведет к профилю, затем к анкете, затем к тесту, показывает заявленный уровень отдельно от пустой подтвержденной категории и совпадает с ответом `GET /me/assessment-availability` после обновления страницы. Сохраненный шаг при этом остается "Согласия": сервер переводит его дальше только из соответствующего шага. Вторая часть работает и в обычном `test-e2e`: она подменяет ответы API (`page.route`) и проверяет только отображение состояний главной - категория и ссылки на результат и приватность, открытая карточка и статус поиска, отсутствие категории и пустая история, неудачная попытка, ошибка чтения с повтором, отказ в доступе, сбой чтения приватности, истекшая сессия. Она не доказывает поведение backend и не заменяет проверку присвоения категории на реальном стенде, которую эта спецификация не выполняет. Скриншоты для просмотра (360 и 1280 px) содержат только синтетические данные.
|
||||
|
||||
`frontend/e2e/company-management.spec.ts` создает компанию, повторяет запрос после потери ответа с тем же ключом и телом, изменяет профиль и сравнивает предпросмотр с API. Управляемые ответы проверяют восстановление после CSRF-ошибки, конфликт версии и задержанный ответ. Реальный отзыв выполняет отдельный `company-fixture`: Go build tag `e2e`, явный флаг, случайный bearer token на каждый прогон, без опубликованного порта и только во внутренней сети. Утилита проверяет два синтетических подтвержденных employer-аккаунта, добавляет владельца-преемника и отзывает исходного владельца в одной транзакции, сохраняя ограничение обязательного владельца. Браузер с прежней cookie проверяет отказ реального API и исчезновение компании из своей директории. Контрольный endpoint отсутствует в обычном backend и release-образе; его URL и токен передаются только тестовому процессу через `E2E_COMPANY_FIXTURE_URL` и `E2E_COMPANY_FIXTURE_TOKEN`.
|
||||
|
||||
## Состояния и доступность основного пути
|
||||
|
||||
`frontend/e2e/minimal-path-a11y.spec.ts` проверяет состояния, путь с клавиатуры и привязку ошибок на экранах входа, начала проверки знаний, профиля кандидата, входящих приглашений и отдельного приглашения кандидата. Отказы создаются перехватом запросов, поэтому на стенде не нужны данные: ответы HTTP 500 и 403, обрыв соединения, пустые и запрещенные ответы. Каждый экран с заглушками проверяется при 360, 768 и 1280 px на горизонтальное переполнение; проверка с настоящим backend покрывает 360 и 768 px. Каждый элемент, до которого доходит Tab, должен соответствовать `:focus-visible` и рисовать контур фокуса. Часть с перехватом запускается и в `make -C deploy test-e2e`, и в `make -C deploy test-e2e-registration`. Один тест с настоящим backend запускается только в режиме регистрации, потому что ему нужны почтовый и анкетный fixture.
|
||||
|
||||
Остальные экраны основного пути покрыты существующими спецификациями: поиск кандидатов и список совпадений работодателя (`match-search.spec.ts`: неуспешный поиск с повтором, отказ в поиске, пустой результат, подтвержденный и заявленный грейд текстом, достижение элементов с клавиатуры при каждой ширине), составление приглашения (`invitation-compose.spec.ts`: ошибки, привязанные к полям, потерянный ответ на отправку с повтором под тем же ключом, переполнение при 360, 768 и 1280 px), регистрация и подтверждение (`auth-registration.spec.ts`), профиль и анкета (`profile-edit.spec.ts`, `questionnaire.spec.ts`).
|
||||
|
||||
Чек-лист основного пути. Каждый пункт проверяет спецификация, указанная в скобках; результат - итог последнего прогона этой спецификации.
|
||||
|
||||
- Вход [`minimal-path-a11y.spec.ts`]: Tab доходит до обоих полей и кнопки отправки с видимым контуром при 360, 768 и 1280 px. Пустая отправка помечает оба поля `aria-invalid` и связывает каждое поле с его текстом через `aria-describedby`. Неуспешный ответ сохраняет введенную почту и оставляет фокус в форме. Пока ответ ожидается, поле пароля остается в фокусе и только для чтения; оно не отключается, потому что отключенное поле теряет фокус.
|
||||
- Профиль кандидата [`minimal-path-a11y.spec.ts`]: текст загрузки, пока профиль загружается; сообщение с кнопкой повтора после неуспешной загрузки; без повтора после отказа в доступе.
|
||||
- Начало пробной проверки кандидата [`minimal-path-a11y.spec.ts`]: сообщение с кнопкой повтора после неуспешного чтения доступности; кандидат без специализации видит пустое состояние со ссылкой на анкету.
|
||||
- Входящие приглашения кандидата [`minimal-path-a11y.spec.ts`]: текст загрузки; ошибка сервера или обрыв соединения дают сообщение с кнопкой повтора, которая работает с клавиатуры; пустое состояние; без повтора после отказа в доступе; каждая карточка называет компанию, роль и состояние текстом.
|
||||
- Приглашение кандидата [`minimal-path-a11y.spec.ts`]: сообщение с кнопкой повтора после неуспешной загрузки; неуспешный отказ сохраняет выбранную причину и комментарий и переводит фокус на сообщение; состояние "отклонено" показано текстом.
|
||||
- Проверка на телефоне с настоящим backend [`minimal-path-a11y.spec.ts`, режим регистрации]: неотправленный числовой ответ переживает перезагрузку при 360 px, а сохраненная копия удаляется, когда ответ принят.
|
||||
- Список совпадений работодателя и составление приглашения: см. спецификации выше; страница составления дополнительно проверяется при 768 px.
|
||||
- Эти проверки не покрывают: вывод для программ чтения с экрана, контраст контура фокуса и масштаб выше 200 процентов. В этом проходе они вручную не проверялись.
|
||||
|
||||
Неотправленный ответ хранится в `sessionStorage` той же вкладки браузера под ключом, который называет попытку и задание. На сервер он не отправляется. Перезагрузка восстанавливает его, только если значение подходит заданию; сохраненное значение больше 64 KiB не сохраняется; заблокированное или переполненное хранилище оставляет ответ только в форме. Принятый ответ удаляет сохраненную копию. Ответы, принятые сервером, после перезагрузки берутся с сервера.
|
||||
|
||||
## Тесты манифеста выпуска
|
||||
|
||||
`make -C deploy check-release` запускает `deploy/scripts/test_release_manifest.py` на стандартной библиотеке Python и без Docker. Тест падает, если go.mod, значение `GO_IMAGE` по умолчанию и `GOTOOLCHAIN=local` в backend/Dockerfile или backend/Dockerfile.demo-seed перестают закреплять Go 1.26.9 или если Dockerfile сервиса использует базовый образ не через закрепляемый build-аргумент `*_IMAGE`, в том числе внешний образ в `COPY --from` или `RUN --mount=from`. На подставных данных образов, Compose и контейнеров он проверяет, что:
|
||||
|
||||
- манифест не копирует значения окружения, labels и локальные пути, а две генерации различаются только `generated_at`;
|
||||
- evidence засчитывается только для того же тега, коммита и отпечатка рабочего дерева, а evidence и записи сборки с неверной структурой не используются;
|
||||
- компонент получает `verified` только при evidence для его точного image ID, ML, monitoring и отсутствующие компоненты никогда не проверены, а выпуск остается непроверенным без smoke и E2E на текущих образах, на грязном дереве, при скачанном core-образе без registry digest, отсутствующем lockfile или Dockerfile, другой версии Go в бинарнике или другой версии Node в образе сборки;
|
||||
- `release-build` не пишет запись сборки, если коммит или рабочее дерево изменились во время сборки;
|
||||
- отпечаток рабочего дерева временного Git-репозитория не зависит от настроек diff и переводов строк, учитывает неотслеживаемые файлы, пропускает игнорируемые и не меняет настоящий индекс;
|
||||
- поиск секретов находит блоки ключей, токены, учетные данные в URL, локальные пути, имена пользователя и хоста и значения переменных, похожих на секреты, в том числе как подстроки и в base64, не печатая их;
|
||||
- сравнение с запущенными контейнерами сообщает о другом digest, незапущенном и неизвестном сервисе;
|
||||
- образ demo seed собирается с закрепленными базовыми образами под своим профилем, записывается, но никогда не считается проверенным, и удерживается по image ID; его отсутствие блокирует только восстановление демонстрационного стенда, другая версия Go в его бинарнике оставляет выпуск непроверенным, а demo override закрепляет core-сервисы и seed за точными image ID и digest и отказывает при отсутствующем образе, измененном демонстрационном overlay или манифесте без записи восстановления стенда;
|
||||
- запись `seed` хеширует исходники demo seed без тестов, и ее версия меняется вместе с ними, но не с тестовым файлом.
|
||||
|
||||
Тест не собирает образы и не запускает контейнеры. Полный путь: `release-build`, `release-smoke` и `release-e2e`, `release-manifest`, `release-up`, `release-manifest-verify` и `release-manifest-check`; см. [DEPLOY.md](DEPLOY.md#манифест-выпуска).
|
||||
|
||||
## Bootstrap интеграционных тестов
|
||||
|
||||
Общий helper находится в `backend/integration_test/bootstrap_test.go`. Вызов `env := bootstrap(t)` поднимает PostgreSQL, Redis и SeaweedFS, дожидается готовности адаптеров и возвращает окружение с конфигурацией и клиентами. Для проверки одного адаптера используйте `bootstrap(t, postgresService)`, `bootstrap(t, redisService)` или `bootstrap(t, seaweedfsService)`. Можно передать несколько сервисов.
|
||||
|
||||
Вызывайте bootstrap один раз в родительском тесте и используйте окружение в его подтестах. Каждый вызов создает отдельные контейнеры с динамическими портами; для SeaweedFS также создается отдельный volume. Очистка зарегистрирована через `t.Cleanup`, включая частично запущенное окружение. Сценарии остановки Redis и пересоздания SeaweedFS управляют ресурсами через helpers этого окружения и не затрагивают другие тесты. При отсутствии Docker тесты завершаются ошибкой. Если `DOCKER_HOST` недоступен, Testcontainers пробует также Docker context и стандартные сокеты, поэтому одного неверного `DOCKER_HOST` недостаточно, чтобы смоделировать отсутствие Docker.
|
||||
|
||||
Bootstrap делает максимум три попытки запуска контейнера всего и только при точной ошибке настройки сети rootless Docker для host-порта, оканчивающейся на `bind: address already in use` (`EADDRINUSE`). Перед повтором он завершает частичный контейнер, возвращенный неудачным запуском; ошибка очистки прекращает повторы. Прочие ошибки запуска или готовности, а также ошибки проверок самого теста не повторяются. Повтор касается только подготовки тестов и не меняет настройки Docker или сети хоста.
|
||||
|
||||
Bootstrap поднимает инфраструктуру и клиенты. Если выбран PostgreSQL, он применяет все встроенные миграции тем же runner, что и старт сервиса. `postgres_helpers_test.go` добавляет `env.newPool` для пула к этой базе, `env.createIsolatedDatabase` для отдельной базы в том же контейнере, когда тест меняет всю схему (например up, down и повторный up), `env.newPoolWithMaxConns` для тестов конкурентности, которым нужно одно соединение на транзакцию, и `truncateTables` для сброса общих таблиц между последовательными подтестами. Тесты получают транзакцию из unit of work только через `postgres.TransactionForIntegrationTest`, который компилируется только с build tag `integration`. Тестовые агрегаты живут в собственной схеме, которую создает тест, а не в продуктовых миграциях. HTTP-сервер приложения, ML и продуктовые фикстуры пока не входят в него. Проверка полного окружения использует общий readiness PostgreSQL, Redis и SeaweedFS.
|
||||
|
||||
Kafka не входит в `bootstrap(t)` и запускается только для тестов, которые выбирают `bootstrap(t, kafkaService)`. Используется тот же образ `apache/kafka:latest`, что и в Compose, с теми же настройками KRaft, включая `KAFKA_AUTO_CREATE_TOPICS_ENABLE=false`. Клиентский listener объявляется на динамическом порту хоста, трафик между брокерами и контроллером остается на loopback контейнера, а данные и объявленные в образе volume размещаются в tmpfs, поэтому тестовый брокер не оставляет volume. Bootstrap заполняет `env.Config.KafkaBrokers` и создает `env.KafkaAdmin` на основе `kadm` из franz-go.
|
||||
|
||||
Helpers находятся в `kafka_helpers_test.go`. `env.createKafkaTopic(ctx, t, partitions)` создает топик с уникальным случайным именем и до создания регистрирует его удаление в `t.Cleanup`, поэтому топик удаляется и после падения теста. Брокер не создает топики по запросу: тест сам создает каждый нужный ему топик. `env.newKafkaClient(t, options...)` возвращает клиент `kgo`, который закрывается по завершении `t`. У `produceKafkaRecords` и `env.consumeKafkaRecords` ограниченные таймауты; consumer читает партиции с начала без consumer group, поэтому смещения группы не остаются. Контейнер останавливается и удаляется в cleanup теста, который вызвал bootstrap, в том числе после падения. `env.pauseKafka(ctx, t)` замораживает брокер через `docker pause` и возвращает функцию, которая его возобновляет; cleanup тоже возобновляет брокер. Приостановленный брокер сохраняет порт и принимает соединения, но не отвечает, что моделирует зависший брокер. Остановленный и снова запущенный контейнер получил бы новый порт на хосте, за которым не следуют ни объявленный listener, ни клиенты, а его топики в tmpfs пропали бы.
|
||||
|
||||
## Тесты закрытого файлового хранилища
|
||||
|
||||
Unit-тесты в `backend/internal/usecase/files/` используют хранилище в памяти, которое, как HTTP-хранилище объектов, фиксирует объект, как только получило заявленное число байтов. Они покрывают проверку политики, формат ключа и отказ для ключей другого namespace или сформированных клиентом, очистку имени файла, лимит заявленного размера, источник длиннее или короче заявленного (хранилище не получает полное тело, ключ удаляется), очистку после отмены контекста вызывающим и после потерянного ответа, сообщение об ошибке очистки, SHA-256, сохраненное тело, которое отличается от своего размера, идемпотентное удаление, закрытие ответа при каждом отказе `Open` и уникальность и корректность объявленных namespace. Тесты адаптера в `backend/internal/adapter/secondary/seaweedfs/` проверяют, что загрузка и скачивание дольше `SEAWEEDFS_TIMEOUT` завершаются, а зависшие заголовки ответа и недоступный endpoint по-прежнему дают ошибку в пределах этого ограничения.
|
||||
|
||||
Bootstrap SeaweedFS использует тот же entrypoint и флаги, что и Compose, и дополнительно публикует порты filer, master и volume, чтобы тесты могли их проверить. Сеть хранилища Compose он не моделирует; эту границу проверяет smoke. `TestPrivateFileStoreAgainstSeaweedFS` в `backend/integration_test/files_store_test.go` использует `bootstrap(t, seaweedfsService)` и реальный адаптер:
|
||||
|
||||
- записывает и читает синтетический объект и пустой объект, проверяя содержимое, размер, тип и digest;
|
||||
- отправляет неподписанные запросы и ожидает 403 от S3 для чтения объекта (в том числе с query, похожим на presigned), перечисления bucket, загрузки и удаления, а также 401 от filer для чтения объекта, перечисления и загрузки и от master для назначения volume и удаления collection; после этого объект по-прежнему читается;
|
||||
- получает file ID внутри контейнера и ожидает 401 от volume на чтение без токена и на запись с подписанным токеном, который вернул master;
|
||||
- проверяет, что неверный secret не открывает, не загружает и не удаляет файлы и не выдается за отсутствие объекта;
|
||||
- открывает, частично читает и закрывает объект больше раз, чем допускает лимит соединений адаптера, с долгим timeout хранилища, поэтому незакрытое тело ответа заблокировало бы цикл;
|
||||
- отклоняет загрузки больше лимита, длиннее или короче заявленного размера и перечисляет namespace отдельным подписанным клиентом, чтобы показать отсутствие частичных объектов;
|
||||
- удаляет объект дважды и затем получает `files.ErrNotFound`.
|
||||
|
||||
Проверки идут с хоста через опубликованные порты, поэтому запросы приходят не изнутри контейнера SeaweedFS, как от другого участника сети хранилища. gRPC- и admin-порты не проверяются; оставшийся риск описан в [ARCHITECTURE.md](ARCHITECTURE.md#закрытое-файловое-хранилище).
|
||||
|
||||
## Тесты relay outbox
|
||||
|
||||
Unit-тесты (`make -C backend test`) покрывают конверт записи, ключ и заголовки, а также ошибку для некорректного payload без его цитирования (`internal/adapter/secondary/kafka/`), публикацию и создание топика, которые завершаются ошибкой в пределах таймаута публикации плюс 2 секунды запаса на планирование, когда брокер недоступен (тесты проверяют затраченное время), преобразование неизвестного топика в `ErrEventDestinationMissing`, сравнение существующего топика с настроенной раскладкой, общее расписание backoff с jitter и без него (`internal/worker/retry/`), проходы relay, которые отмечают только подтвержденные события, повторы после неудачных `Prepare` и проходов, отсутствие backoff после прохода, который опубликовал часть пачки, пока ядовитое событие стоит первым в каждой пачке, повторный `Prepare` после отсутствующего назначения, не больше одного чтения размера очереди за интервал, проход в работе, который завершается после отмены, проход, отмененный таймаутом остановки, остановку во время backoff (`internal/worker/outboxrelay/`), настройки relay и топика, включая фактор репликации и `min.insync.replicas` по умолчанию брокера (`config/`), ошибки базы только с SQLSTATE и таймауты, которые округлились бы до отсутствия ограничения (`internal/adapter/secondary/postgres/`), счетчик relay и gauge-метрики очереди и приложение, которое запускает relay вместе с серверами и останавливает его вместе с ними (`internal/bootstrap/`).
|
||||
|
||||
`TestOutboxRelay` в `backend/integration_test/outbox_relay_test.go` использует `bootstrap(t, postgresService, kafkaService)`, пишет события через transactor с тестовым агрегатом и последовательно выполняет случаи, у каждого свой топик:
|
||||
|
||||
- Зафиксированное событие публикуется в документированном конверте с ключом и заголовками, и заполняется `published_at`.
|
||||
- Сбой Kafka: при приостановленном брокере бизнес-транзакция все равно фиксируется, проход relay завершается ошибкой в пределах таймаута публикации, оба события остаются в ожидании, бизнес-строки не тронуты. После возобновления брокера relay публикует оба события, и потребитель получает их с их `event_id`.
|
||||
- Сбой между публикацией и отметкой: обертка publisher действительно публикует, а затем отменяет проход, как при убитом процессе; строка остается в ожидании, новый relay публикует ее снова, и в топике две записи с одним `event_id`.
|
||||
- Конкурирующий захват: пока один захват держит самые ранние события двух агрегатов, второй захват через пул с `lock_timeout` 500 ms получает только третий агрегат, не ожидая блокировок и без версии 2 первого агрегата; следующий проход получает версию 2.
|
||||
- Два relay работают, пока 12 параллельных writer фиксируют по 8 версий своего агрегата. Публикуются все события, каждый агрегат остается в одной партиции, а первая доставка каждой версии идет в порядке `aggregate_version`. Обертка publisher добавляет 10 ms к каждой публикации, чтобы проходы relay пересекались; тест пишет в лог, сколько событий опубликовал каждый relay.
|
||||
- Остановка при приостановленном брокере и таймауте публикации 30 секунд: relay останавливается не раньше таймаута остановки в 1 секунду и не позже 5 секунд после него, поэтому проход мог завершить только таймаут остановки; его событие остается в ожидании, и ни одно соединение не остается занятым.
|
||||
- Таймаут простоя: захват, callback публикации которого 2 секунды игнорирует свой контекст, при `idle_in_transaction_session_timeout` 300 ms завершается ошибкой SQLSTATE 25P03; событие остается в ожидании, и ни одно соединение не остается занятым.
|
||||
- `Backlog` возвращает ноль для пустого outbox и два ожидающих события с положительным возрастом после двух записей.
|
||||
- `Prepare` создает топик с настроенным числом партиций, фактором репликации брокера по умолчанию и `min.insync.replicas` на уровне топика и повторно принимает существующий топик.
|
||||
|
||||
Набор работает с одним брокером и одним PostgreSQL. Он не измеряет пропускную способность и задержку, и не покрывает переключение брокеров и репликацию. Обработчики событий описаны в разделе [Тесты обработчиков событий](#тесты-обработчиков-событий).
|
||||
|
||||
## Тесты обработчиков событий
|
||||
|
||||
Unit-тесты (`make -C backend test`) покрывают runtime обработчиков с поддельными источником, хранилищем и обработчиком (`internal/worker/eventconsumer/`): записи `applied`, `duplicate` и `ignored`, зафиксированные в порядке получения; сбои хранилища, которые повторяются сверх лимита попыток без dead letter, а offset фиксируется только после успеха хранилища; обработчик, который все время падает, повторяется ровно `MaxAttempts` раз не чаще минимального backoff, а затем уходит в dead letters с ID и типом события, размером значения и SHA-256, пока следующая запись применяется; `ErrEventRejected` и panic, которые уходят в dead letters после одной попытки без цитирования значения panic; невалидную запись, которая уходит в dead letters без вызова обработчика, причем commit ждет, пока две неудачные записи dead letter не пройдут; остановку, которая бросает зависший обработчик после grace без фиксации его и всего после него; запись, которая завершается в пределах grace и фиксируется, тогда как следующая не начинается; отсутствие повторов и dead letters во время остановки; backoff после неудачных чтений; commit, который PostgreSQL отвергает после того, как обработчик проглотил ошибку, считается попыткой и заканчивается `retries_exhausted`; конфликт сериализации при commit повторяется как попытка; panic в `Handles` уходит в dead letters без цитирования значения; начало пачки фиксируется сразу после dead letter, до начала следующей записи; счетчики сбоев `poll` и `commit`; очистку причины. Тесты адаптера PostgreSQL проверяют классификацию отвергнутого, конфликтного и сетевого сбоя commit и то, что ошибки обработчика сохраняют идентичность без сообщения PostgreSQL. Они же покрывают декодирование конверта и его согласованность с producer, каждое отвергнутое правило конверта без цитирования значения и учет commit участника группы, включая отказ для завершенных записей, которые не являются для каждой партиции началом последнего чтения без пропусков (`internal/adapter/secondary/kafka/`), настройки обработчиков и бюджет ребалансировки, включая описанное в документации значение по умолчанию 42,5 секунды (`config/`), счетчики обработчиков (`internal/adapter/secondary/prometheus/`), а в `internal/bootstrap/` - случаи пропуска, один обработчик на handler, отказ для повторяющихся и недопустимых имен, зарегистрированный обработчик доставки, значения меток, совпадающие с подготовленными метриками, и приложение, которое запускает обработчик вместе с серверами и возвращается только после того, как он перестал читать.
|
||||
|
||||
`TestEventConsumer` в `backend/integration_test/event_consumer_test.go` использует `bootstrap(t, postgresService, kafkaService)`. Его обработчик существует только в тесте: он пишет одну строку на примененное событие в `consumer_test.effects`, таблицу без уникального ключа, которую создает тест, поэтому второй эффект остался бы виден. Последовательные случаи, каждый со своими топиком и группой:
|
||||
|
||||
- Один ID события доставлен трижды, дважды в партицию 0 и один раз в партицию 1, рядом с другим событием: группа фиксирует обе партиции, у каждого события ровно одна строка эффекта и один маркер, а счетчики показывают 2 `applied` и 2 `duplicate`.
|
||||
- Два обработчика соревнуются за одно событие без Kafka: каждый читает одну и ту же запись из источника в памяти. Первый держит незафиксированный маркер внутри обработчика, пока тест не увидит в `pg_stat_activity`, что вставка маркера второго ждет блокировку; затем первый фиксируется. Итог: один эффект, `applied` у первого и `duplicate` у второго, причем второй не вызывает обработчик.
|
||||
- Та же гонка, в которой обработчик первого падает после того, как второй начал ждать: первый откатывается, второй применяет событие, а повтор первого находит маркер. Одна строка эффекта.
|
||||
- Перезапуск до commit: обработчик пишет эффект и блокируется дольше grace остановки в 300 ms, как процесс, убитый до commit. После остановки нет ни строки эффекта, ни маркера, ни зафиксированного offset группы. Новый обработчик в той же группе получает запись, применяет ее один раз и фиксирует offset 1.
|
||||
- Падение после commit в базе, но до commit offset: эффект и маркер фиксируются напрямую, затем запись читается. Она становится `duplicate`, обработчик не вызывается, offset фиксируется.
|
||||
- Невалидная запись, за которой в той же партиции идет валидная: одна строка dead letter с offset 0, ID события из заголовка, классом `invalid_record`, нулем попыток, размером значения и SHA-256 и причиной, которая не цитирует значение; валидное событие применяется; фиксируется offset 2; счетчик `dead_lettered` равен 1; за 500 ms новых dead letters не появляется.
|
||||
- Обработчик, который всегда падает на одном событии, с 3 попытками и backoff 200 ms: ровно 3 попытки не чаще чем через 100 ms и в пределах 5 секунд, dead letter `retries_exhausted` с ID и типом события и ошибкой обработчика, ни одной строки эффекта этого события, потому что каждая попытка откатилась, следующее событие применяется, фиксируется offset 2, счетчик сбоев обработчика равен 3, и за 500 ms новых попыток нет.
|
||||
- Жесткое падение до commit: обработчик пишет эффект, читает PID своего backend и завершает его через `pg_terminate_backend`, как это сделали бы упавший процесс или оборванное соединение. Backend исчезает из `pg_stat_activity`, не остается ни строки эффекта, ни маркера, ни зафиксированного offset, а новый участник группы применяет событие один раз.
|
||||
- Обработчик, который выполняет `SELECT 1 / 0`, игнорирует ошибку и возвращает nil: PostgreSQL отвергает каждый commit, обработчик насчитывает 3 попытки обработчика и ни одного сбоя хранилища, пишет dead letter `retries_exhausted`, фиксирует offset 1 и не оставляет ни эффекта, ни маркера.
|
||||
- Повторная запись dead letter: одна и та же запись, записанная дважды, оставляет одну строку со вторым исходом; другое значение на той же позиции получает свою строку.
|
||||
- Передача партиции между двумя участниками одной группы: commit первого участника всегда падает, и он держит запись, пока присоединяется второй; тест ждет состояния группы `PreparingRebalance`, отпускает запись и ждет, пока группа не станет стабильной с одной партицией у каждого участника. У каждого из четырех событий ровно один эффект, первый участник обработал оба события первого раунда до ребалансировки, второй не получил ничего из первого раунда переданной партиции (ее позиция зафиксирована при отзыве, единственным оставшимся путем commit) и не насчитал дубликатов, первый участник после потери партиции не пытался ни фиксировать, ни обрабатывать ее записи, а после выхода первого участника offsets группы равны 2 в обеих партициях, то есть переданная партиция не перемотана назад.
|
||||
- Событие, добавленное в outbox через transactor, опубликованное relay и прочитанное обработчиком: декодированное событие совпадает со строкой outbox, значит producer и consumer одинаково понимают конверт.
|
||||
|
||||
`TestPostgresMigrations` дополнительно проверяет, что миграция 00005 создает и удаляет обе таблицы обработчиков. Набор использует один брокер, один PostgreSQL и тестовые обработчики. Он не измеряет пропускную способность, не покрывает ребалансировку под нагрузкой или с более чем двумя участниками, переключение брокеров, исключение участника после rebalance timeout и не проверяет доставку alerts; у продуктового обработчика свои [тесты доставки писем](#тесты-доставки-писем).
|
||||
|
||||
## Тесты доставки писем
|
||||
|
||||
Unit-тесты (`make -C backend test`) покрывают модель доставки и путь ее создания:
|
||||
|
||||
- `internal/domain/`: content hash учитывает версию, тему, обе части и границы между частями; содержимое, которое не отправит ни один транспорт или которое относится к другому виду, отклоняется; измененное сохраненное тело не проходит проверку целостности; новая доставка начинается в `pending` со сроком в момент создания, версией 1, ключом `delivery/<id>` и необязательным исходным событием; каждый исход попытки, примененный к `pending`, `waiting_quota` и `unknown`, дает описанный статус, номер попытки, версию, время и ID провайдера, в том числе `waiting_quota` без известного сброса, а `accepted` и `rejected` отклоняют любую следующую попытку; несогласованные результаты попытки отклоняются; `WaitForQuota` переводит `pending` и `waiting_quota` в ожидание с известным или неизвестным сбросом без попытки, отклоняет `unknown`, конечные доставки и время раньше последнего изменения, а следующая попытка не может быть раньше него; `Rebind` до первой попытки меняет только аккаунт провайдера и версию, а после нее отклоняется; сохраненные строки, нарушающие инвариант, отклоняются; запрос письма принимает только вид уведомления и текст, который можно сохранить; вывод `fmt` и `slog` доставки, ее содержимого и запроса письма никогда не показывает адрес, тему, тело, текст запроса или токен.
|
||||
- `internal/usecase/notification/`: запрос сохраняет текст под ID агрегата события, а payload события содержит только `mail_request_id` и `kind`; некорректные запросы ничего не записывают; обработчик сохраняет одну доставку под ID запроса с исходным событием, адресом аккаунта, сформированным содержимым, настроенным аккаунтом провайдера и временем часов и удаляет запрос; то же событие повторно не находит запрос; существующая доставка под ID запроса принимается для того же получателя и вида и отклоняется в остальных случаях; сломанные события (другая версия схемы или агрегат, некорректный payload, данные после объекта, ID запроса, не равный ID агрегата, вид письма с токеном) и текст, который отклоняет шаблон, отклоняются без цитирования payload; исчезнувший запрос, исчезнувший аккаунт и неподтвержденный адрес пропускаются со строкой лога, которая называет только ID доставки и события; ошибки хранилища, включая аккаунт, удаленный между чтением и вставкой, остаются повторяемыми и сохраняют запрос; ни одна ошибка и строка лога не содержит адрес, тему или тело.
|
||||
- `internal/adapter/secondary/postgres/`: ошибки ограничений доставок и запросов писем переводятся в свои sentinel (`deliveries_content_immutable` и `delivery_attempts_immutable` - в `ErrDeliveryContentImmutable`, `deliveries_provider_pinned` - в `ErrDeliveryProviderPinned`, внешние ключи на пользователей - в `ErrUserNotFound`), а любая другая ошибка PostgreSQL, например нарушение CHECK, сохраняет только SQLSTATE и имя ограничения без message и detail.
|
||||
- `internal/usecase/notification/mailtemplate/`: результат рендеринга переводится в сохраняемое содержимое с тем же видом, версией, частями и hash.
|
||||
- `config/` и `internal/bootstrap/`: `EMAIL_ACCOUNT` по умолчанию равен `default`, принимает метки до 64 символов и отклоняет пустые, со смешанным регистром, похожие на ключ и слишком длинные значения, не повторяя их; bootstrap регистрирует ровно обработчики `notification_delivery` и `notification_inbox` и отклоняет некорректную метку аккаунта.
|
||||
|
||||
`TestMailDelivery` в `backend/integration_test/delivery_test.go` использует `bootstrap(t, postgresService, kafkaService)` и настоящие usecase запроса, обработчик, relay, runtime обработчиков и хранилища. Последовательные случаи:
|
||||
|
||||
- Одно событие обрабатывается дважды: запрос для подтвержденного аккаунта записывается в бизнес-транзакции, relay публикует его событие, строка снова помечается неопубликованной, как после сбоя до фиксации `published_at`, и relay публикует ее второй раз с тем же ID события. Обработчик фиксирует offset 2 и считает одну запись `applied` и одну `duplicate`; в базе ровно одна доставка: адресована аккаунту, сформирована версией `notification.v1`, закреплена за настроенным аккаунтом провайдера, называет событие своим источником и находится в `pending` без попыток, а запросов писем не остается.
|
||||
- Изменение шаблона после создания: первый запрос сохраняется с `notification.v2`. Обработчик с тестовым renderer, изображающим более позднюю версию `notification.v3`, сохраняет второй запрос с новой версией, а повтор первого запроса под другим именем обработчика находит запрос уже обработанным и ничего не сохраняет. Первая доставка, прочитанная через новый пул, сохраняет тему, части и hash `notification.v2`, а прямой `UPDATE` ее тела завершается ошибкой `deliveries_content_immutable`.
|
||||
- Сохранение после перезапуска: один пул записывает попытку `unknown` с кодом провайдера и подсказкой ожидания с долями миллисекунды, проигрывает повторную запись той же попытки с `ErrDeliveryVersionConflict`, записывает попытку `accepted` с ID письма у провайдера и закрывается. Новый пул и хранилище читают доставку как `accepted` с этим ID, двумя попытками и версией 3, а обе строки попыток - ровно в записанном виде, подсказку ожидания до наносекунды; следующая попытка отклоняется, а `UPDATE` попытки завершается ошибкой `delivery_attempts_immutable`.
|
||||
- Перенос и ожидание квоты: доставка без попыток переносится на другой аккаунт провайдера и переводится в `waiting_quota` с неизвестным сбросом, повторная запись по устаревшей версии получает конфликт версии, строк попыток нет; после попытки `Rebind` отклоняется domain, а прямой `UPDATE` аккаунта провайдера завершается ошибкой `deliveries_provider_pinned`.
|
||||
- Уведомление на неподтвержденный адрес не сохраняет доставку, удаляет свой запрос и записывает в лог ID доставки.
|
||||
- Запрос, аккаунт которого удален, теряет строку запроса вместе с аккаунтом; затем обработчик не сохраняет доставку и записывает в лог ID доставки.
|
||||
- Очистка неподтвержденных аккаунтов пропускает аккаунт, строку доставки которого держит другая транзакция, удаляет его после снятия блокировки, и вместе с ним удаляются его ожидающий запрос и доставка, созданная прямо через репозиторий, как будут создаваться письма с токеном.
|
||||
|
||||
Каждый случай проверяет, что собранные логи обработчика и runtime не содержат ни адреса, ни темы, ни тела, а события запросов проверяются на отсутствие адреса и текста запроса. `TestPostgresMigrations` дополнительно проверяет, что миграция 00006 создает и удаляет три свои таблицы и обе trigger-функции, а `TestIdentityRepositories` выполняет запрос очистки с блокировкой запросов писем и доставок. `TestMailDelivery` не отправляет почту и проверяет обработчик продуктовых уведомлений. `TestEmailVerificationOverHTTP` проверяет письмо подтверждения и подтверждение адреса через Resend fixture, но не обращается к внешнему провайдеру. Для сброса пароля нет теста доставки, потому что этот сценарий пока не реализован.
|
||||
|
||||
## Тесты квот почты
|
||||
|
||||
Unit-тесты (`make -C backend test`) проверяют правила квот без базы:
|
||||
|
||||
- `internal/domain/`: окна суток и месяца для момента времени - календарные периоды UTC независимо от его часового пояса: полночь UTC относится к новым суткам, а наносекунда до нее - к старым, местное время после местной полуночи может еще относиться к предыдущим UTC-суткам, сброс суток 28 февраля обычного года и 29 февраля високосного приходится на 1 марта, а декабрь сбрасывается в январь следующего года; лимиты отклоняют ноль, отрицательные значения и суточный лимит больше месячного.
|
||||
- `config/` и `internal/bootstrap/`: `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` по умолчанию равны 100 и 3000 для `resend` и `disabled`; `smtp` без любого из них не запускается и принимает явно заданные значения; сниженное значение принимается как настроено для любого провайдера; пустое значение считается незаданным; ноль, отрицательные, нецелые значения, значения вне диапазона и суточный лимит больше месячного отклоняются без вывода секретов; bootstrap не запускается с нулевой квотой.
|
||||
- `internal/adapter/secondary/mail/resend/`: 429 `daily_quota_exceeded` дает `QuotaPeriod` `day` с ожиданием до полуночи, а `monthly_quota_exceeded` дает `month` без ожидания.
|
||||
- `internal/usecase/notification/`, со счетчиком и журналом в памяти и поддельными часами:
|
||||
- `QuotaGate.PrepareSend` допускает отправки до суточного лимита, а следующую переводит в `waiting_quota` до 00:00 UTC и не считает ее; после полуночи допускает ее. При заполненном месяце (с 31 декабря на 1 января) и при заполнении обоих окон ждет начала месяца.
|
||||
- Доставку, которую последним изменил экземпляр с часами на 5 мс впереди, уже после полуночи, откладывает с этим временем изменения и без ошибки.
|
||||
- Применяет сниженный лимит к `smtp` так же, как к любому транспорту; отклоняет доставку, закрепленную за аккаунтом без квоты, и ничего для нее не резервирует.
|
||||
- Возвращает доставку `unknown` без изменений с моментом сброса и отклоняет конечную доставку.
|
||||
- Повтор в пределах 24 часов повторно использует открытое резервирование, даже когда сутки иначе заполнены; отказ этого повтора резервирование сохраняет; после окна повтор считается заново. Шлюз `smtp`, у которого нет дедупликации провайдера, считает каждый повтор.
|
||||
- `SettleSend` оставляет резервирование для `accepted` и `unknown` и возвращает его при ошибке `Send` и любом исходе `rejected`. Повторный расчет возвращает резервирование один раз.
|
||||
- Ответ о суточной квоте отмечает сутки и возвращает полночь, о месячной - отмечает месяц и возвращает его конец. Ответ без окна откладывает только доставку по подсказке или без времени, а окно, которое провайдер назвал заполненным, возврат не открывает.
|
||||
- Отмечается окно, текущее на момент расчета: суточный отказ 31 октября отмечает только сутки и оставляет ноябрь открытым; резервирование в 23:59:59, рассчитанное через 5 мс после полуночи, отмечает новые сутки; подсказка, вычисленная по часам провайдера на 5 мс впереди, все равно дает ровно полночь.
|
||||
- `ReportQuotaUsage` пишет расход и лимиты и предупреждает о других метках аккаунта.
|
||||
- `DeliveryStatusReader.LatestForUser` возвращает вид, статус и время изменения, а `WaitingUntil` только для `waiting_quota`. Он спрашивает только про указанный аккаунт, без доставки ничего не возвращает и отклоняет нулевой аккаунт и неизвестный вид.
|
||||
- Журналы не содержат адреса, темы или тела.
|
||||
|
||||
`TestMailQuota` в `backend/integration_test/mail_quota_test.go` использует `bootstrap(t, postgresService)`, настоящие transactor, хранилище доставок и репозиторий квот и поддельные часы. Каждый случай начинается с пустых таблиц:
|
||||
|
||||
- Конкурентность: 12 отправителей, каждый со своим соединением и транзакцией, одновременно вызывают `PrepareSend`. На окнах без строк (создание строк тоже конкурирует) при суточном лимите 10 разрешение получают ровно 10; после 7 последовательных отправок из следующих 12 разрешение получают ровно 3. Каждая остальная доставка сохраняется в `waiting_quota` с `next_attempt_at` на ближайшие 00:00 UTC, а оба счетчика заканчивают на 10. Без блокировки строк случай падает: допускаются все 12.
|
||||
- Полночь и граница месяца: при лимитах 2 в сутки и 3 в месяц с 30 октября 22:00 UTC третья отправка ждет до 31 октября 00:00 UTC, за секунду до этого все еще ждет, а в полночь проходит; четвертая ждет 1 ноября, потому что месяц заполнен, и тогда проходит. Строки суток и месяца содержат 2, 1, 1 и 3, 1.
|
||||
- Сниженный лимит и SMTP: шлюзы собираются из `config.LoadFromEnv`. После 4 отправок через Resend с лимитом по умолчанию лимит, сниженный до 3, откладывает следующую отправку до полуночи. `smtp` без настроек квот не загружается; с 2 и 2 он допускает две отправки через relay и откладывает третью до начала месяца, а доставка Resend под шлюзом `smtp` завершается ошибкой `ErrQuotaNotConfigured` и не меняет счетчиков.
|
||||
- Уточнение по провайдеру: отказ `temporary` возвращает свое резервирование. Отказ `daily_quota_exceeded` при локальном счете 1 из 100 сохраняет доставку в `waiting_quota` до полуночи с одной попыткой, поднимает строку суток до 100 с `provider_exhausted_at`, после чего шлюз сам откладывает следующую доставку. После полуночи отказ `monthly_quota_exceeded` поднимает строку месяца до 3000 и откладывает доставки до 1 ноября.
|
||||
- Удаление аккаунта: три принятые отправки дают 3 из 3; удаление аккаунта каскадно удаляет его доставки и попытки, счетчики сохраняют 3, а доставка другому аккаунту в тот же день ждет до полуночи.
|
||||
- Порядок блокировок, детерминированно: строка месяца лежит в heap раньше строки суток, а запись идет в сессиях с `enable_indexscan=off`, поэтому сканирование следует порядку heap, как в воспроизведенной взаимоблокировке. Третья транзакция держит строку суток; резервирование и возврат встают за ней в очередь в обоих порядках, затем блокировка снимается. Ни один не получает ошибку взаимоблокировки, а расход сходится. Если убрать упорядоченную блокировку из `Settle`, случай падает с SQLSTATE 40P01.
|
||||
- Порядок блокировок, ограниченная нагрузка: 60 раундов, в каждом одновременно стартуют возврат вторых суток, возврат первых суток с отметкой вторых через полночь и два резервирования вторых суток в сессиях с порядком heap. Ни один раунд не возвращает ошибку.
|
||||
- Журнал: ошибка транспорта, рассчитанная дважды, возвращается один раз. Резервирование неизвестной попытки повторно используется повтором через час и не используется после 24-часового окна. В журнале остаются 2 открытые строки, 1 возвращенная и 2 с исходом.
|
||||
- Статус для пользователя: аккаунт без писем ничего не получает; после одного допущенного и одного отложенного уведомления он видит `waiting_quota` до полуночи; другой аккаунт и другой вид ничего не получают.
|
||||
- Отчет при запуске: при расходе под меткой `old-label` и под настроенной меткой отчет через `postgres.MailQuotaStore` пишет расход настроенного аккаунта и предупреждает об `old-label`.
|
||||
- База отклоняет неизвестный вид периода, месяц, который начинается не с первого числа, отрицательный расход, неверную метку аккаунта, резервирование, у которого сутки вне его месяца, и неизвестный исход.
|
||||
|
||||
`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор квот не вызывает транспорт; worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend`, покрыт тестами отправки служебной почты ниже.
|
||||
|
||||
## Тесты отправки служебной почты
|
||||
|
||||
Модульные тесты (`make -C backend test`) покрывают:
|
||||
|
||||
- `domain`: `Delivery.CheckServiceMail` называет первое нарушенное правило (нет токена, назначение, владелец, использован, отозван, истек ровно в свой срок, регистрация сдвинулась, адрес подтвержден, адрес изменен) и оставляет актуальное письмо подтверждения или сброса отправляемым; `Delivery.Cancel` работает из `pending` и `waiting_quota`, отклоняет `unknown` и конечные статусы, не оставляет попытки и переживает восстановление; уведомление не может нести ID токена; названия статусов не содержат утверждения о доставке человеку.
|
||||
- `usecase/notification`: `ServiceMailSender` против хранилищ в памяти с правилом версии и lease хранилища PostgreSQL, квоты шлюза в памяти и транспорта по сценарию. Каждый результат транспорта дает правильное состояние доставки, срок и эффект на квоту (принято, постоянный отказ и отказ запроса, временный отказ после первой паузы, более длинная подсказка провайдера, ответ провайдера о дневной квоте до полуночи UTC, ответ о квоте без сброса, unknown, транспорт, ответивший без исхода, нет транспорта, прерванный вызов, неверное сообщение); каждая причина отмены достигается без вызова транспорта и резервирования; заполненная локальная квота откладывает доставку без вызова и отправляет ее при сбросе; результат, который не удалось сохранить, сохраняет lease, повторяется три раза, а затем его подхватывает замена с тем же ключом без двойного подсчета; попытка, потерянная за пределами окна идемпотентности или у транспорта без дедупликации, записывается как unknown и не повторяется; доставка, чей хеш содержимого не совпадает, отменяется как `content_invalid` и сообщается без вызова транспорта; строка, которая сбоит по собственной вине (нечитаемая по причине, отличной от несовпадения хеша, нарушенное правило домена при чтении состояния), считается, отодвигается расписанием повторов, чтобы доставка за ней отправилась, и после трех сбоев отменяется как `processing_failed`; временные ошибки (тайм-аут, отмена, deadlock, сеть, EOF, отсутствие настройки квоты) возвращаются worker и никогда не считаются и не отменяют строку, сколько бы ни повторялись; ошибка `Send` без ответа отодвигает строку без счета; приостановленный счет отодвигает строки без счета; успешный проход очищает счетчик; сбой не записывается для строки, которую держит другой worker; окно идемпотентности считается от первого запроса при повторных потерях worker и с часовым запасом; отзыв между захватом и вызовом учитывается; результат отбрасывается, если lease потерян во время вызова; вызов ограничен lease за вычетом бюджета расчета; jitter ограничен и подменяем; письма, сохраненные, пока транспорта не было, переносятся на настроенный аккаунт, а доставка другого аккаунта остается нетронутой; журнал никогда не содержит адрес, токен или ссылку. `ServiceMailer` сохраняет доставку, привязанную к токену, с ID токена, токеном во fragment ссылки и без `?token=`, безвредно повторяется и отклоняет токен не того назначения до рендеринга. `RetryPolicy` удваивает паузу до максимума и учитывает более длинную подсказку.
|
||||
- `worker/mailsender`: отмененные доставки считаются по причине; предохранитель приостанавливает счет сбоев, когда подряд падают три разные строки, и возобновляет после успеха, а повторный сбой одной строки его не включает; сбойная строка заставляет цикл ждать по backoff; gauge равен true только пока работает цикл, холостой проход ждет интервал опроса, за обработанной доставкой сразу идет следующий проход, а отсутствие транспорта, прерванный вызов и сбой базы вызывают паузу вместо вращения вхолостую.
|
||||
- `adapter/secondary/postgres`: только классы SQLSTATE 22 и 23 совпадают с `ErrRowFault`; deadlock, serialization, соединение, ресурсы, остановка и внутренние ошибки - нет.
|
||||
- `adapter/secondary/prometheus`: у `lincodex_mail_sender_cancelled_total` каждая причина существует с нулем, а произвольный label отклоняется; `lincodex_mail_sender_running` существует со значением 0 и следует за `SetMailSenderRunning`; каждый статус доставки, включая `cancelled`, существует с нулем.
|
||||
- `adapter/secondary/mail/resend`: loopback-конструктор принимает только http URL на loopback-хосте, поэтому ключ и письма развертывания нельзя направить через него на другой хост; `resendfixture` отвечает как Resend (принимает, повторяет исходное сообщение для повторного ключа и тела, отклоняет другое тело под тем же ключом, проигрывает заданные ошибки).
|
||||
- `bootstrap`: нет worker без транспорта или базы; цикл запускается и останавливается вместе с приложением, а gauge следует за ним.
|
||||
- `observability/prometheus/tests`: `LincodexMailDeliveriesOverdue` молчит без gauge, пока он равен 0 и для очереди из одних уведомлений (возраст 0), и срабатывает, пока какой-либо экземпляр сообщает 1; `LincodexMailCancelledBroken` срабатывает на `content_invalid` и `processing_failed` и молчит для причин от действий пользователя (`make -C observability check`).
|
||||
|
||||
`TestServiceMailSending` в `backend/integration_test/mail_sender_test.go` использует `bootstrap(t, postgresService)`, настоящие транзакционный слой, хранилища, шлюз квот и usecase отправки, настоящий транспорт Resend, направленный на локальную имитацию, и фиктивные часы. Подтесты делят базу и начинают с пустых таблиц:
|
||||
|
||||
- Служебное письмо для синтетического аккаунта без записи согласия любого назначения ставится вместе с токеном в одной транзакции и принимается имитацией: один вызов провайдера с ключом `delivery/<id>`, адресом и ссылкой с токеном во fragment; доставка `accepted` с ID сообщения провайдера, одной принятой попыткой, одним посчитанным получателем и без оставшегося lease, аккаунт видит статус `accepted`, а второй проход ничего не делает. Журнал не содержит ни адреса, ни токена.
|
||||
- Письмо сброса пароля для синтетического аккаунта без C2 принимается имитацией: один вызов с ключом `delivery/<id>`, адресом и ссылкой `/reset-password` с токеном во fragment; журнал не содержит адреса и токена.
|
||||
- Письмо подтверждения уходит, даже если C2 выдан и отозван, пока письмо ждет worker: проверка читает только токен и аккаунт, а имитация получает ровно один вызов.
|
||||
- Worker, который держит доставку, не пускает к ней другого: имитация отвечает медленно, проход второго worker холостой, пока запрос первого в пути, и имитация получает ровно один вызов, а база - одну попытку.
|
||||
- Четыре worker одновременно разбирают очередь из восьми доставок: восемь вызовов провайдера под восемью разными ключами, ни один не повторен, восемь принятых доставок по одной попытке, восемь посчитанных получателей.
|
||||
- Worker, остановившийся после отправки (база отказывает при сохранении ответа), заменяется после истечения его lease: два вызова под одним ключом, второй - повтор, одно сообщение у провайдера, одна попытка, открытое резервирование использовано повторно, поэтому получатель считается один раз. За пределами 24-часового окна замена записывает попытку unknown и не вызывает провайдера.
|
||||
- Доставка с хешем содержимого, испорченным ручной правкой, отменяется как `content_invalid` на версии 2 без вызова провайдера, а следующая за ней доставка отправляется в следующем проходе.
|
||||
- Строка, которая сбоит по своей причине (тема с переводом строки нарушает правила домена, поэтому строку нельзя восстановить, хотя хеш цел), считается и отодвигается на минуту, пока доставка за ней отправляется, сбоит снова в каждый срок и отменяется как `processing_failed` на третьем сбое с очищенными телами; ошибка транспорта без ответа отодвигает строку на минуту без счета, с возвращенным резервированием и доставкой в `pending`.
|
||||
- Сбой, записанный worker, чей захват откатился, не трогает строку, которую держит другой worker, а несчитаемый сбой оставляет `failure_count` равным 0.
|
||||
- Три потерянных подряд worker не скрывают возраст первого запроса: доставка становится `unknown`, когда `first_send_started_at` старше 24 часов, и провайдер в четвертый раз не вызывается.
|
||||
- Lease - несколько секунд по часам базы; чужой worker не может записать попытку или заблокировать строку; `RecordClaimedAttempt` проходит для владельца.
|
||||
- При 5000 просроченных строк уведомлений план захвата использует `deliveries_due_idx` и не использует последовательное сканирование (`EXPLAIN`).
|
||||
- Очередь из одних уведомлений не создает возраст самой ранней ожидающей доставки; служебное письмо создает.
|
||||
- Тела письма с токеном очищаются, когда оно принято или отменено, и токен больше не встречается ни в одной строке; ожидающее письмо вручную очистить нельзя; очищенная строка не может получить тело обратно или потерять метку; аккаунт по-прежнему видит свой статус.
|
||||
- Токен, отозванный повторной отправкой, уже использованный токен, истекший токен, повторно зарегистрированный аккаунт, уже подтвержденный адрес, измененный адрес и токен другого назначения завершают доставку как `cancelled` с соответствующей причиной, без попытки, без lease, без следующей попытки, без резервирования и без вызова провайдера; аккаунт видит `cancelled`; следующий проход холостой. Удаленный аккаунт уносит свою доставку.
|
||||
- Письмо подтверждения, отозванное до отправки, отменяется как `token_revoked` без вызова провайдера и без попытки; аккаунт провайдера доставки не меняется, тело очищается, а журнал не содержит адреса, токена, ссылки и ID аккаунта.
|
||||
- Ответы провайдера: 503 `service_unavailable` оставляет доставку в `pending` со сроком через минуту, проход до срока холостой, повтор в срок использует тот же ключ и принимается; 500 дает `unknown` без следующей попытки и без повтора через сутки; 403 `validation_error` дает `rejected`.
|
||||
- Квота: локальный лимит один в сутки переводит вторую доставку в `waiting_quota` до полуночи UTC без вызова провайдера, аккаунт видит ожидание и его конец, а доставка отправляется при сбросе; ответ провайдера `daily_quota_exceeded` откладывает доставку до следующей полуночи.
|
||||
- Служебный worker никогда не берет продуктовое уведомление; его отправляет полоса уведомлений (`TestProductNoticeIsSentOnceByItsOwnWorker`).
|
||||
- `EMAIL_PROVIDER=disabled`: с транспортом disabled проход сообщает, что канал недоступен, доставка остается нетронутой на версии 1, lease и резервирование освобождены, до имитации ничего не доходит, цикл с ним делает не больше четырех проходов меньше чем за секунду, а gauge равен 1, пока он работает, и 0 после; с транспортом то же письмо переносится на настроенный аккаунт и принимается.
|
||||
- Схема отклоняет отмененную доставку без причины, причину у другого статуса, половину lease, lease у конечной доставки, уведомление, привязанное к токену, смену привязки токена и удаление токена, на который ссылается доставка; удаление аккаунта убирает оба.
|
||||
|
||||
`TestDeliverySendingMigration` откатывает и заново применяет миграцию 00012 поверх отмененной и очищенной доставки сброса пароля: прежняя схема хранит ее как `rejected` с заглушкой в теле, удаляет токены сброса и новые столбцы, а миграция применяется снова. `TestPostgresMigrations` покрывает общий путь вверх, вниз и снова вверх.
|
||||
|
||||
`make -C backend lint` также запрещает импорт `resendfixture` и вызов `resend.NewLoopbackSender` вне файлов `_test.go` (depguard и forbidigo в `backend/.golangci.yml`).
|
||||
|
||||
Ни одна проверка не вызывает настоящий API Resend: единственный провайдер - имитация, поэтому эти тесты доказывают протокол, на котором говорит транспорт, и правила доставки, но не поведение Resend, доставляемость и реальную квоту аккаунта.
|
||||
|
||||
## Тесты продуктовых уведомлений
|
||||
|
||||
Unit-тесты (`make -C backend test`) покрывают:
|
||||
|
||||
- `domain`: `Delivery.CheckInvitationNotice` решает в описанном порядке (нет получателя или адрес не подтвержден, адрес изменился, приглашение отсутствует или принадлежит другой организации, на приглашение ответили, оно истекло или прошло срок ответа, организация скрыта, публикация отозвана, уведомление без субъекта), и решает первое нарушенное правило, поэтому неподтвержденный адрес важнее скрытой организации; `MailSubject` принимает только известные виды с полными ID и не печатает идентификаторов; субъект может быть только у уведомления; `MailQuotaLimits.WithReserve` сохраняет долю каждого окна и отказывает в резерве, который не оставляет места; три причины прав разбираются и есть в наборе метрик с нулем.
|
||||
- `config`: резерв служебной почты по умолчанию равен пятой части каждого лимита квоты (20 и 600 на тарифе Resend Free), явный ноль сохраняется, а резерв отрицательный или достигающий своего лимита отклоняется с сообщением, которое называет настройку.
|
||||
- `adapter/secondary/prometheus`: `lincodex_notification_sender_running` есть со значением 0, следует за `SetNotificationSenderRunning` и не сдвигает gauge служебного цикла; причины прав есть со значением 0 в `lincodex_mail_sender_cancelled_total`.
|
||||
- `bootstrap`: нет worker уведомлений без транспорта или базы данных, а цикл уведомлений запускается и останавливается вместе с приложением, и его gauge следует за ним.
|
||||
- `observability/prometheus/tests`: `LincodexMailCancelledBroken` молчит на `rights_revoked`, `recipient_ineligible` и `source_closed` (`make -C observability check`).
|
||||
|
||||
`TestProductNotice*` в `backend/integration_test/product_notification_test.go` используют `bootstrap(t, postgresService)`, изолированную базу с настоящей отправкой приглашения и настоящим notifier, обработчик `DeliveryHandler`, запущенный над сохраненным запросом, настоящий отправитель уведомлений с фикстурой Resend в качестве транспорта и фальшивые часы. Каждая верхнеуровневая функция работает в своей изолированной базе, поэтому счетчики квоты не смешиваются; подтесты правил прав делят одну базу:
|
||||
|
||||
- `TestProductNoticeIsSentOnceByItsOwnWorker`: уведомление о доставленном приглашении отправляет полоса уведомлений один раз, с нейтральным текстом, который не называет ни организацию, ни кандидата и ведет во входящие; служебный worker ничего не берет (пустой проход, без вызова провайдера); второй проход пуст; в логах нет ни адреса, ни ID кандидата, ни handle карточки.
|
||||
- `TestProductNoticeRightsAreCheckedBeforeEverySend`: кандидат, который скрыл организацию между отправкой и worker, письма не получает, уведомление отменяется как `rights_revoked` без вызова провайдера, тела очищаются, следующий проход пуст, адреса в логах нет; адрес, который больше не подтвержден, отменяется как `recipient_ineligible`; уведомление без субъекта отменяется как `source_closed` с очищенным телом; приглашение, прошедшее срок ответа, отменяется как `rights_revoked`. Подтест со сроком сдвигает часы, поэтому идет последним.
|
||||
- `TestProductNoticeReserveLeavesServiceQuotaToServiceMail`: при дневном лимите 10 и резерве 8 полоса уведомлений отправляет два уведомления и паркует третье в `waiting_quota` до следующей полуночи UTC, без вызова провайдера и без цикла впустую; затем письмо подтверждения уходит под полным лимитом, и за день учтены три получателя.
|
||||
- `TestProductNoticeQueueIsDrainedOnceByConcurrentWorkers`: четыре отправителя одновременно разбирают шесть уведомлений; провайдер получает шесть вызовов, и каждое уведомление принято после одной попытки.
|
||||
- `TestProductNoticeClaimReadsItsOwnDueIndex`: при 5000 строках служебной почты план захвата уведомлений использует `deliveries_product_due_idx` и не делает последовательного чтения (`EXPLAIN`).
|
||||
|
||||
Эти тесты доказывают правила прав и механику полосы на локальной фикстуре. Они не решают продуктовые вопросы из раздела [Отправка продуктовых уведомлений](ARCHITECTURE.md#отправка-продуктовых-уведомлений), например, должна ли отозванная публикация отменять ожидающее уведомление.
|
||||
|
||||
`TestInvitationNoticesSurviveRelayAndConsumerRestarts` в `backend/integration_test/notification_restart_test.go` использует `bootstrap(t, postgresService, kafkaService)` с той же фикстурой и проводит две настоящие отправки приглашений через outbox, relay, топик Kafka с одной партицией и потребители `notification_inbox` и `notification_delivery`, собранные так же, как в bootstrap. Relay публикует все четыре события и погибает до фиксации отметки; потребители их применяют. Затем перезапущенный relay публикует те же event ID повторно, и перезапущенные потребители в тех же группах считают каждую повторную запись дубликатом; потребители в новых группах, как после потери offset, тоже перечитывают весь топик как дубликаты. После каждого этапа у каждого получателя ровно одна строка в `notification_inbox_events` и одна доставка уведомления, dead letter нет; после этого полоса уведомлений отправляет каждому получателю одно письмо.
|
||||
|
||||
## Тесты заданий по сроку
|
||||
|
||||
Unit-тесты (`make -C backend test`) проверяют runtime заданий с хранилищем в памяти, которое повторяет правила захвата, проверки lease и освобождения хранилища PostgreSQL, и с fake clock из `backend/pkg/testutil/` (`internal/worker/jobrunner/`): выполняются только наступившие задания зарегистрированных видов в порядке срока, а задание со сроком через два дня выполняется ровно тогда, когда часы его достигают; неудачное задание повторяется после backoff по часам, не захватывается раньше и после последней попытки становится dead с записью в журнал уровня error и метриками; `ErrJobRejected` и panic завершают задание после одной попытки, а значение panic не попадает в журнал; обработчик, переживший свой lease, падает как `timeout`; задание, которое другой worker захватил до начала, пропускается без вызова обработчика; задание с истекшим lease последней начатой попытки становится dead без выполнения; медленное первое задание пачки не тратит единственную попытку следующего и не убивает его, а другой worker выполняет задание, которое занятый worker захватил, но не начал, на той же попытке; сбой базы данных вне обработчика освобождает задание и остаток пачки без учета попыток; неудачные захваты ждут backoff, а не крутятся в цикле; при остановке задание в работе завершается внутри grace, задание, которое его переживает, отменяется и освобождается без эффекта и без учтенной попытки, а захваченные, но не начатые задания освобождаются; panic во время остановки все равно делает задание dead; backlog всех видов попадает в метрики. Остальные unit-тесты покрывают правила задания (`internal/domain/`: вид, ключ, плоский payload, лимит размера, срок в UTC с точностью до микросекунд), настройки (`config/`), счетчики и gauges (`internal/adapter/secondary/prometheus/`), `FakeClock` (`pkg/testutil/`), а в `internal/bootstrap/` - случаи без запуска с их строками журнала, пустой реестр видов, повторный вид и приложение, которое запускает worker против недоступной базы и все равно останавливается.
|
||||
|
||||
`TestScheduledJobs` в `backend/integration_test/scheduled_jobs_test.go` использует `bootstrap(t, postgresService)`. Его обработчик существует только в тесте: он пишет одну строку в `job_test.effects`, таблицу без уникального ключа, в транзакции, которая завершает задание, поэтому второй эффект остался бы виден. У каждого имитируемого процесса свой пул, хранилище и worker; создание нового означает перезапуск. Все решения о сроках и lease принимаются по одному `FakeClock`. Последовательные случаи:
|
||||
|
||||
- Задания на разные даты: два задания запланированы через `UnitOfWork.ScheduledJobs()` на завтра и через три дня, а повторное планирование игнорируется и не сдвигает срок. В начале ничего не выполняется; после перезапуска и одного дня выполняется первое задание; после еще одного перезапуска второе не выполняется за микросекунду до срока и выполняется в свой срок; через месяц снова ничего не выполняется. Эффектов по одному на задание, в порядке сроков.
|
||||
- Два worker с собственными пулами одновременно крутят свои циклы над 40 наступившими заданиями: все задания выполнены, эффектов ровно 40 для 40 разных заданий.
|
||||
- Обработчик, переживший lease по часам, по-прежнему держит блокировку строки задания, поэтому захват другого worker пропускает задание; затем первый worker завершает его с одним эффектом.
|
||||
- Истекший lease: worker A захватывает и запускает задание и останавливается внутри него. Worker B не может захватить его за микросекунду до истечения lease и выполняет его в момент истечения, с двумя учтенными попытками и записанным `lease_expired`. Поздний запуск worker A отклоняется, его поздний `Run` возвращает `ErrJobLeaseLost` без вызова обработчика, а поздняя запись сбоя и освобождение отклоняются; эффект остается один.
|
||||
- Начатая попытка задания с лимитом в одну попытку, lease которой истек: следующий захват делает задание dead с одной попыткой и `lease_expired` без вызова обработчика.
|
||||
- Захват, который так и не начался, с лимитом в одну попытку: после истечения lease другой worker выполняет задание на той же попытке без класса ошибки.
|
||||
- Медленное первое задание пачки работает дольше lease захвата: следующее задание с лимитом в одну попытку освобождается с сохраненной попыткой и выполняется в следующем проходе. С двумя worker, пока медленное задание держит свою строку, другой worker захватывает только ожидающее задание и выполняет его на единственной попытке; занятый worker затем считает его `lease_lost`.
|
||||
- Обработчик, который отменяет собственное задание через unit: его эффект фиксируется, задание остается `cancelled`, а следующее задание прохода выполняется. Обработчик, который меняет собственное задание иначе, переводит его в dead с `completion_conflict` и не оставляет эффекта.
|
||||
- Корректная остановка: обработчик пишет эффект и переживает grace в 200 ms. После остановки эффект откачен, задание в `pending` без попыток и без lease, а новый процесс сразу выполняет его, не дожидаясь lease.
|
||||
- Неудачное задание с собственным лимитом в две попытки: первая попытка сдвигает на backoff только `available_at` и сохраняет `due_at`, задание не захватывается до окончания backoff, вторая попытка делает его dead, обработчик оба раза видел исходный срок, эффектов нет, backlog показывает одно dead задание, а счетчики - один `retry` и один `dead`.
|
||||
- Отмена: отмененное задание никогда не захватывается, повторная отмена и новое планирование того же ключа ничего не делают, наступивших заданий нет.
|
||||
- Отмена во время выполнения: пока обработчик держит задание, отмена в другой транзакции видна в `pg_stat_activity` как ожидание блокировки строки; после фиксации обработчика задание выполнено, а отмена возвращает false.
|
||||
|
||||
`TestPostgresMigrations` также проверяет, что миграция 00008 создает и удаляет `scheduled_jobs`. Набор использует один PostgreSQL и тестовый вид задания. Он не измеряет пропускную способность, не покрывает расхождение часов между экземплярами, переключение базы данных и продуктовый обработчик и не проверяет доставку alerts.
|
||||
|
||||
## Тесты продуктовых метрик
|
||||
|
||||
Unit-тесты (`make -C backend test`) покрывают продуктовые метрики. В `internal/adapter/primary/http/` запросы через настоящий router и настоящий collector получают шаблон маршрута своей операции (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) и никогда не получают параметр пути, адрес в пути или query string; неизвестные пути и методы сохраняют `/api/v1/*`, `/api/*` или `unmatched`; ответы problem считаются по коду (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), а обычный 404 вне `/api` - нет; в выдаче нет значений, похожих на email или UUID; каждый код problem контракта сохраняет свой label. Тест журнала запросов отправляет адрес и UUID в путях и query через тот же router и проверяет, что JSON-журнал называет только шаблоны маршрутов, статусы, коды problem и число параметров query, пропускает `/healthz` и `/readyz` и не содержит ни одного из значений. `internal/adapter/primary/http/middleware/` проверяет middleware журнала и метрик на простом router chi: общий маршрут и код problem, отсутствие problem для ответа, который в итоге успешен, уровень error для 5xx, неизвестный метод в журнале как `OTHER` и collector без учета problem. В `internal/adapter/secondary/prometheus/`: задержка по классу статуса, каждая пара вида и статуса доставки с нулем и сбросом, когда статус опустел, gauges квот без label аккаунта, hook сохранения ответов, который превращает неизвестные значения в `other` и не создает серий до первого вызова, и проверка всей выдачи после вызова каждого hook с fixture email и UUID. `internal/worker/deliverymetrics/` покрывает просрочку самой ранней доставки в `pending` (ноль, пока срок не наступил), текущие окна квоты, неудачное чтение, которое не отменяет второе, и жизненный цикл цикла чтения; `internal/bootstrap/` - пропуск без базы, квоты только для активного транспорта и приложение, которое запускает sampler против недоступной базы и все равно останавливается. `pkg/testutil/` проверяет сам поиск идентификаторов.
|
||||
|
||||
`TestDeliveryStatistics` в `backend/integration_test/delivery_statistics_test.go` проверяет запрос sqlc `GetDeliveryStatistics` на PostgreSQL: пустая таблица, затем доставки трех видов во всех пяти статусах, выставленных в рамках ограничений таблицы, дают точные числа по виду и статусу, а самый ранний срок берется только из доставок, которые еще в `pending`.
|
||||
|
||||
`make -C observability check` проверяет правила alerts через `promtool check config` и запускает `promtool test rules` для `observability/prometheus/tests/lincodex_rules_test.yml`: каждый alert срабатывает в положительном случае (backend недоступен, доля 5xx, отставание outbox, dead letter, застрявший обработчик, мертвые и опаздывающие задания, неизвестный исход доставки, учтенный один раз для двух экземпляров, просроченные доставки, устаревшие gauges почты, исчерпанная квота по счету и по отказу провайдера), а ограничения молчат: тихий трафик только из ошибочных запросов, просроченные доставки без `lincodex_mail_sender_running`, sampler, который продолжает успешно читать, и месячное окно с запасом.
|
||||
|
||||
`make -C observability verify-product-metrics` - сквозная проверка, описанная в [DEPLOY.md](DEPLOY.md#отдельный-monitoring-compose). Ей нужны Docker и свободные host ports 18085 и 13085; она собирает образы core и идет несколько минут. Она отправляет fixture адрес в query через Nginx и в пути напрямую в backend и вызывает по нему нарушение уникальности в PostgreSQL. Она доказывает, что метрики доходят до Prometheus, а запросы продуктового dashboard выполняются в Grafana, что PostgreSQL пишет ошибки кратко и что fixture адреса нет в выдаче метрик, во всех сериях и значениях labels, в federate и в логах Loki сервисов core в этом прогоне. Она не проверяет доставку alerts, production retention, нагрузку и целевую задержку и не отправляет почту.
|
||||
|
||||
## Шардирование интеграционных тестов
|
||||
|
||||
`make -C backend test-int` запускает полный набор через `backend/scripts/run-integration-suite.py`. Runner автоматически обнаруживает все верхнеуровневые `Test*` в `./integration_test/...`, сортирует их по пакету и имени, затем распределяет по шардам по кругу. Каждый тест попадает ровно в один шард вместе со всеми своими подтестами. Изменение набора тестов может изменить распределение; балансировка по длительности пока не используется.
|
||||
| Область | Команда | Требования |
|
||||
| --- | --- | --- |
|
||||
| Backend, быстрые тесты | `make -C backend test-fast` | Go |
|
||||
| Backend, race | `make -C backend test` | Go и C toolchain |
|
||||
| Backend, интеграционные | `make -C backend test-int` | Go, Python 3, Docker |
|
||||
| Frontend | `make -C frontend check` | Node.js, pnpm, установленные зависимости |
|
||||
| ML API | `make -C ml verify` | Python, uv, установленные зависимости |
|
||||
| Контракты | `make -C api check` | Установленные API-инструменты |
|
||||
| Генераторы OpenAPI 3.2 | `make -C api check-toolchain` | Go, frontend и ML toolchains |
|
||||
| Технический smoke | `make -C deploy smoke` | Docker Compose |
|
||||
| Браузерный E2E | `make -C deploy test-e2e` | Docker Compose, frontend dependencies |
|
||||
| E2E с почтой | `make -C deploy test-e2e-registration` | Те же зависимости |
|
||||
| Документация | `make docs-check` | Python 3 |
|
||||
|
||||
`make test` запускает тесты сервисов. `make check` добавляет форматирование, lint, типы, сборки и проверки конфигурации. `make verify` также генерирует код, проверяет drift, OpenAPI toolchain, backend race, интеграционные тесты и smoke.
|
||||
|
||||
Playwright, security-сканеры, реальные ML-модели и runner sandbox запускаются отдельно. Прошедший `verify` не заменяет их.
|
||||
|
||||
## Backend: unit и race
|
||||
|
||||
Тесты рядом с кодом проверяют domain/usecase и адаптеры без внешней инфраструктуры. Для портов используйте настроенные mockery-моки или небольшие fake-реализации с нужным поведением.
|
||||
|
||||
```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
|
||||
make -C backend mocks
|
||||
make -C backend test-fast
|
||||
make -C backend test-race
|
||||
```
|
||||
|
||||
Индексы начинаются с 1. Обе переменные задаются вместе; неверные параметры, пустой набор, лишние шарды и ошибки обнаружения завершают команду ошибкой. `test-int-list` компилирует тестовый пакет и выводит выбранные тесты без запуска контейнеров. `make -C backend test-scripts` проверяет для каждого числа шардов, что каждый тест выполняется ровно в одном шарде, что список шарда совпадает с тестами, которые шард запускает, выбор родительских тестов и передачу ошибок runner. Он входит в `make -C backend check`.
|
||||
При изменении сценария проверяйте успешный путь, предметный отказ и сбой зависимости. Для конкурентных операций нужны проверки версии, повторов и отмены. Сравнивайте результат и сохраненные эффекты, а не внутренний порядок вызовов без причины.
|
||||
|
||||
CI запускает отдельную matrix из двух integration jobs с `GOFLAGS=-race` и `fail-fast: false`. Результат всех шардов обязателен для aggregate и deployment smoke. `GOFLAGS='-race -shuffle=on' make -C backend test-int` позволяет локально проверить гонки и независимость порядка. Шарды используют свои контейнеры; общие БД и брокер между runner не создаются, поэтому тест Kafka проходит в любом шарде, куда он попал. CI берет `TEST_SHARD_TOTAL` из размера matrix (`strategy.job-total`), поэтому, когда длительность suite оправдывает дополнительные runner, достаточно добавить индекс шарда в matrix; индекс больше общего числа шардов завершает job ошибкой. Таймаут `go test` делит бюджет всего набора в 30 минут между шардами, но не меньше 10 минут на шард: локальный запуск без шардов получает 30 минут, каждый из двух шардов CI - по 15.
|
||||
## Интеграционные тесты
|
||||
|
||||
## Тесты журнала согласий
|
||||
Тесты находятся в `backend/integration_test/` под build tag `integration`. Они используют Testcontainers с настоящими PostgreSQL, Redis, SeaweedFS и, при явном выборе, Kafka.
|
||||
|
||||
Unit-тесты (`make -C backend test`) проверяют правила журнала без базы:
|
||||
```sh
|
||||
make -C backend test-int-compile
|
||||
make -C backend test-int-list
|
||||
make -C backend test-int
|
||||
```
|
||||
|
||||
- `internal/domain/` (`consent_test.go`): целями считаются только `c1`-`c5`, и только C4 привязано к организации; версия текста следует шаблону контракта из 1-64 символов; хэш текста обязан иметь 32 байта и не быть нулевым; отклоняются сохраненный текст, который больше не совпадает со своим хэшем, текст C4 без плейсхолдера `{organization}` и другой текст с ним; показанный текст C4 дает разный хэш для разных организаций и отличается от хэша шаблона, а пустое, окруженное пробелами или многострочное название организации отклоняется. `NewConsentGrant` отклоняет C4, пустую или неверную версию, отсутствие хэша, субъекта или времени и источник, который цель не допускает; `NewContactConsentGrant` требует текст C4, организацию с допустимым названием, набор полей, приглашение и положительную версию условий и хэширует текст в том виде, в каком он показан с этим названием. Выдачи и отзывы не выводят в печать и логи субъекта, организацию, название или поля. Набор полей каноничен при любом порядке входа и отклоняет пустой, повторный, неизвестный набор и больше четырех полей. `RestoreConsentRecord` отклоняет то же, что отклоняет база, а запись в выводе и логах показывает только ID, цель и состояние.
|
||||
- `internal/adapter/secondary/postgres/` (`consents_test.go`): ошибки ограничений журнала превращаются в sentinel-ошибки по SQLSTATE и имени ограничения без деталей строки, ограничивающий ключ согласий в очистке превращается в `ErrTransactionConflict`, неверный вход отклоняется до запросов, каждый сгенерированный тип строки приводится к одной структуре записи, а сохраняемый набор полей идет в порядке, который принимает база.
|
||||
- `internal/usecase/consent/` (`service_test.go`, с in-memory репозиторием текстов, журналом, transactor и управляемыми часами): выдача C1, C2, C3 и C5 записывает актуальную версию и хэш текста, источник своей точки входа (`GrantAtRegistration` фиксирует C1 и `registration`, `GrantInSettings` фиксирует `consent_settings`) и время внедренных часов, но не любое другое время; выдача со старой, неизвестной или запланированной версией завершается `ErrStaleConsentText`, называет актуальную версию и не доходит до журнала; выдача версии один, публикация версии два и повтор версии один дают устаревшую версию и одну запись; `CheckTextVersion` возвращает актуальный текст, завершается устаревшей версией для старой, неизвестной и запланированной версии, отклоняет неизвестную цель и неверную версию и никогда не обращается к журналу; C4 на общем пути завершается `ErrScopedConsentRequired` до чтения любого репозитория; неверная или пустая версия, неизвестная цель и нулевой субъект отклоняются; повтор возвращает существующую запись с `Created` false и ее первым временем, а в журнале остается одна запись; ошибки репозиториев (нет опубликованного текста, неизвестный субъект) сохраняют свой sentinel, а отсутствие текста не выдается за устаревшую версию; у субъекта, не давшего C3, остальные цели имеют собственные записи, а записи C3 нет; `GrantContact` записывает scope, источник `invitation_acceptance` и хэш показанного текста, возвращает существующую запись при повторе, сообщает, что приглашение занято другим субъектом, и отклоняет устаревшую версию C4, название с пробелами по краям и отсутствие полей, организации, приглашения, субъекта или версии условий; `GrantInSettingsInNewTransaction` повторяет конфликт транзакции после паузы, останавливается после трех попыток, не повторяет другую ошибку и отмененный контекст и откатывает устаревшую выдачу; `NewService` паникует при нулевом transactor или часах.
|
||||
- `internal/adapter/primary/http/` (`router_test.go`): `ListMyConsents` с сессией после валидации отвечает 501, а на неизвестное состояние, limit больше 100 и неверный cursor - 400 с указателем на параметр запроса; при `DenyAllSecurity` отвечает 401 с cookie, без нее и с параметром `subject_id`; DTO не содержат хэша, субъекта или контактов, параметры - только состояние и страница, а пример контракта декодируется и проходит валидацию.
|
||||
- `frontend/src/shared/api/consent-contract.test.ts`: сгенерированные Zod-схемы принимают запись C4 со scope и отозванную запись без scope, отклоняют неизвестную цель, состояние или источник, пустую или неверную версию, пустой или слишком большой набор полей, неизвестный вид контакта и версию условий меньше 1, требуют каждое nullable-поле и отбрасывают хэш или субъекта; операция принимает только состояние и параметры страницы.
|
||||
`test-int-compile` компилирует тесты без контейнеров; `test-int-list` показывает выбранные верхнеуровневые тесты. Ни одна из этих команд не подтверждает успешное выполнение сценариев. Для `test-int` нужен работающий Docker; его отсутствие считается ошибкой.
|
||||
|
||||
`TestConsentLedger` в `backend/integration_test/consent_ledger_test.go` использует `bootstrap(t, postgresService)` с примененными миграциями, публикует второй текст C1 так, как это сделала бы миграция, и очищает журнал между случаями:
|
||||
### Общий bootstrap
|
||||
|
||||
- Миграция публикует по одному демо-тексту на цель с совпадающим хэшем; актуальный текст C1 зависит от времени; неизвестная версия и версия другой цели не находятся.
|
||||
- Версии и цели: C1 при регистрации, C2 и новая версия C1 дают три строки; старая строка C1 остается побайтно прежней и показывается как `superseded`, актуальным C1 становится новая версия, повторная выдача старой версии возвращает существующую строку без новой, а отзыв C2 не меняет C1.
|
||||
- Отзыв ставится один раз: повторный отзыв ничего не находит и сохраняет первое время, актуального C3 больше нет, а новая выдача - новая строка рядом с отозванной. Отзыв C1 закрывает и его строку `superseded`.
|
||||
- C4: домен отклоняет общую выдачу и scoped-выдачу без организации и полей; выдача сохраняет организацию, канонический набор полей, приглашение и версию условий с хэшем показанного текста, а не шаблона; повтор возвращает ту же строку; согласие по приглашению другого субъекта дает `ErrConsentInvitationTaken`; отзыв C4 для организации A не затрагивает организацию B, а отозванное согласие по приглашению не возвращается.
|
||||
- Проверки repository: неизвестный субъект, пустая или неверная версия, пустой хэш, придуманная версия, версия другой цели, хэш другого текста и выдача до публикации отклоняются и ничего не сохраняют. Другой субъект не видит и не отзывает согласие владельца.
|
||||
- Ограничения базы через прямой SQL: пустая версия, пустой или короткий хэш, C4 без scope или с пустым, повторным или неизвестным полем, C2 со scope или из регистрации, отзыв без источника и хэш другого текста отклоняются с именем ограничения; изменение выданной строки, отзыв с одновременным сдвигом выдачи, повторная отметка отзыва, изменение или удаление опубликованного текста и удаление аккаунта с историей согласий отклоняются.
|
||||
- Модель чтения: страницы по три записи возвращают ровно четыре записи владельца от новых к старым и никогда не возвращают записи другого субъекта; фильтр состояния возвращает активные и отозванные записи.
|
||||
- Бизнес-транзакция: выдача C4 откатывается вместе с упавшим принятием, ошибка запроса после выдачи откатывает всю транзакцию, а зафиксированное принятие видно после фиксации и в своей транзакции до нее.
|
||||
- Очистка неподтвержденных аккаунтов удаляет устаревший аккаунт вместе со строкой C1 и сохраняет подтвержденный аккаунт и его запись.
|
||||
- Снимок C4: строки, чей хэш относится к другому названию организации, к названию, отличному от сохраненного, или к шаблону, отклоняются (`consent_records_c4_text_hash`), C4 без названия и C1 с названием отклоняются (`consent_records_c4_scope`); после переименования два принятия сохраняют свои названия, и хэш каждого по-прежнему доказывает текст, показанный с его снимком.
|
||||
- Отзыв со временем на час раньше выдачи записывается временем выдачи.
|
||||
- Удаление строки согласия подтвержденного аккаунта отклоняется (`consent_records_retained`); строку неподтвержденного аккаунта удалить можно.
|
||||
- Повторная регистрация: `UpdateRegistration` и новая выдача C1 в одной транзакции оставляют только новое C1; устаревшая повторная регистрация и попытка для подтвержденного аккаунта ничего не меняют и не удаляют.
|
||||
- Восемь одновременных выдач одной версии на своих соединениях сохраняют одну запись, и все возвращают ее, причем `created` ровно у одной.
|
||||
- Двадцать раундов гонки выдачи и отзыва не дают ошибок, кроме `ErrTransactionConflict`, и никогда не оставляют больше одной неотозванной записи версии.
|
||||
- Когда заблокирована только строка согласия устаревшего аккаунта, очистка в сессии с lock timeout 200 ms пропускает аккаунт без ожидания и удаляет его после снятия блокировки.
|
||||
В `bootstrap_test.go` функция `bootstrap(t)` поднимает PostgreSQL, Redis и SeaweedFS, применяет миграции и возвращает настройки и клиенты. Для узкой проверки выбирайте сервисы: `bootstrap(t, postgresService)` или `bootstrap(t, postgresService, kafkaService)`.
|
||||
|
||||
`TestConsentGrants` в `backend/integration_test/consent_usecase_test.go` запускает usecase на базе bootstrap с фиксированными часами приложения, вторым текстом C1 и текстом C5, запланированным после часов:
|
||||
Каждый вызов владеет своими контейнерами и динамическими портами. Ресурсы освобождаются через `t.Cleanup`, в том числе при ошибке запуска. Вызывайте bootstrap в родительском тесте и переиспользуйте окружение в его подтестах; данные соседних тестов должны быть изолированы.
|
||||
|
||||
- Регистрация: `UserRepository.Create` и `GrantAtRegistration` для C1 выполняются в одной транзакции `Transactor` без сессии (таблица сессий остается пустой) и фиксируют один аккаунт и одно C1 со временем приложения и актуальной версией текста. C2 и C5 следуют отдельными операциями, у каждой своя активная запись; C3 не дано, записи C3 нет, пока остальные действуют; C3, выданное позже и отозванное, оставляет C1, C2 и C5 активными.
|
||||
- Атомарность: транзакция, упавшая после записи аккаунта и C1, не оставляет ни того, ни другого, а выдача для субъекта без аккаунта завершается `ErrUserNotFound` и ничего не записывает.
|
||||
- Идемпотентность и версии: повтор в собственной транзакции и в бизнес-транзакции возвращает первую запись и ее время и не добавляет строк, а бизнес-транзакция не прерывается. Устаревшая версия C1, запланированная версия C5 и неизвестная версия C3 завершаются ошибкой устаревшей версии с названием актуальной и ничего не записывают; актуальная версия C1 проходит, а устаревшая остается отклоненной. Выдача после отзыва - новая строка. Восемь одновременных повторов создают ровно одну строку.
|
||||
- Повторная публикация: после выдачи версии один C3 и публикации версии два повтор версии один считается устаревшим, называет версию два и оставляет одну строку и первую запись как текущее C3.
|
||||
- Повторная регистрация: `UpdateRegistration` и затем `GrantAtRegistration` в одной транзакции возвращают `created` true с новой записью и оставляют ровно одно C1. Обратный порядок показан как риск: выдача находит C1 прежнего регистранта и возвращает его с `created` false, затем обновление удаляет его, и аккаунт остается без C1.
|
||||
- C4: общий путь отклоняет его и ничего не записывает; `GrantContact` в транзакции сохраняет организацию, название, поля, приглашение и источник `invitation_acceptance`; повтор возвращает ту же запись, устаревшая версия C4 отклоняется, а C4 не создает C2.
|
||||
- Перезапуск: после закрытия pool новый pool, хранилище и usecase перечисляют те же четыре записи по порядку с их состояниями, отметкой и источником отзыва и исходными временами выдачи, а повторная выдача через новый экземпляр ничего не записывает.
|
||||
Общие helpers создают пулы, отдельные базы и Kafka-топики. Используйте их вместо копирования настройки контейнеров. HTTP-сервер и предметные фикстуры подключайте для конкретного сценария.
|
||||
|
||||
`TestRegistrationConsentMigration` применяет миграцию 00016 в изолированной базе, проверяет привязку старой C1, отсутствие привязки у согласий из настроек, вставку C1 через старую форму записи, отказ для переданной несовпадающей версии, защиту версии от изменения при отзыве и повторный down/up. Отдельный случай проверяет, что устаревшая регистрационная C1 останавливает миграцию без частичных изменений. `TestPostgresMigrations` продолжает проверять миграцию 00009. Интеграционные тесты регистрации и подтверждения email проверяют вызов consent service в API потоке; `TestConsentGrants` проверяет usecase отдельно от HTTP. Отзыв и принятие приглашения с C4 пока не покрыты как бизнес-потоки. Гонка очистки с SQLSTATE 23001 покрыта только unit-тестом преобразования, потому что ее окно нельзя воспроизвести детерминированно.
|
||||
Для SQL проверяйте реальные транзакции, ограничения и миграции. Для outbox и событий - повторную доставку и восстановление после сбоя. Для доступа к данным - разрешенный запрос, другой аккаунт/организацию и отзыв разрешения.
|
||||
|
||||
## Тесты организаций
|
||||
`TestCompanyQuota`, `TestHoldings` и тест миграции холдингов проверяют реальные квоты PostgreSQL: границы окон, повторы, общий пул E0, конкуренцию, изменение политики и защищенный откат. HTTP-набор отдельно проверяет отправку приглашений, изоляцию компаний и немедленное закрытие контактов после отзыва доступа.
|
||||
|
||||
Модульные тесты (`make -C backend test`) проверяют правила организаций без базы данных:
|
||||
### Шарды
|
||||
|
||||
- `internal/domain/` (`organization_test.go`, `membership_test.go`): профиль принимает только название и полную карточку; каждое правило называет поле, которое его нарушает, указателем JSON Pointer (`/name`, `/contacts/website`, `/representatives/1/name`), не цитируя значение: пустое, с пробелами по краям, многострочное, слишком длинное или не UTF-8 название, описание или сфера с переводом строки или управляющим символом, сайт не по `https`, с учетными данными, портом, IP-адресом, числовым или шестнадцатеричным хостом или без точки, email без точки в домене, телефон вне E.164, имя Telegram без `@` и одиннадцать представителей. CRLF в описании сохраняется как LF. `NewOrganization` начинает с версии 1, UUIDv7 и уровня `e0` на основании `confirmed_email`, как бы ни выглядел профиль; `ApplyProfile` сохраняет идентификатор, версию и проверку и никогда не двигает время обновления назад; уровень сочетается только со своими основаниями; `e0`-`e2` сопоставляются ступеням квот политики, а у `e3` ступени нет; сохраненная строка, измененная вне приложения, не восстанавливается. Карточка содержит только профиль и уровень. Представитель скрыт в выводе `fmt` и `slog`, в том числе внутри объемлющей структуры, а организация логирует только идентификатор, версию и уровень. Компанией управляет только владелец, доступ дает только `active` членство, четыре роли и четыре состояния совпадают со значениями контракта, а `NewMembership` отказывает на nil-идентификатор, неизвестную роль и нулевое время.
|
||||
- `internal/adapter/secondary/postgres/` (`organizations_test.go`): ошибки ограничений организаций сопоставляются своим sentinel по SQLSTATE и имени ограничения без строки с ошибкой, в которой лежат имена представителей; остальные ошибки хранят только SQLSTATE и ограничение; взаимная блокировка сопоставляется `ErrTransactionConflict`; некорректный ввод отвергается до любого оператора; управляющие роли, передаваемые в SQL, берутся из доменного правила.
|
||||
- `internal/adapter/primary/http/` (`organization_test.go`): при наличии сессии операции отвечают 501 после валидации и 400 с указателем на каждое правило схемы (название длиннее 200 символов или с переводом строки, отсутствующий `expected_version`, контакты без одного поля, сайт по http или с учетными данными, телефон вне E.164, имя Telegram без `@`, одиннадцать представителей, представитель с контактом, null в `name`, `contacts` или `representatives`, лимит больше 100, идентификатор не UUID); представители карточки кандидата могут отсутствовать, быть null или пустыми, а карточка без контактов отвергается. Каждое из одиннадцати полей, которые несли бы право или уровень доверия (`role`, `owner_id`, `verification_level`, `verification`, `verification_basis`, `members`, `membership`, `candidate_card`, `id`, `version`, `created_at`), отвергается по отдельности при создании и обновлении с указателем на все тело. Под `DenyAllSecurity` все четыре операции отвечают 401 с cookie и без и с параметром `user_id`. DTO запросов содержат ровно поля профиля и не содержат поля роли, владельца, участника или проверки, в карточке нет членства, роли, основания и времени, список принимает только страницу, в `OrganizationUpdate` отсутствующий список отличается от пустого, каждый документированный пример декодируется и проходит валидацию, а в bundle запросы - закрытые объекты, обе записи требуют схему CSRF, создание требует Idempotency-Key, обновление объявляет 412, и нет операции, которая задает уровень или роль.
|
||||
- `frontend/src/shared/api/organization-contract.test.ts`: сгенерированные схемы Zod принимают только название и полную карточку для создания и обновления, требуют `expected_version`, допускают null только для `description` и `sphere`, отвергают те же пределы, что и контракт, отбрасывают роль или уровень проверки, добавленные клиентом, перечисляют четыре уровня, роли и состояния и, на уровне типов, не дают запросам полей роли, владельца, участника, проверки или идентичности, карточке - членства и основания, а членству - аккаунта.
|
||||
`backend/scripts/run-integration-suite.py` обнаруживает тесты и распределяет их по отсортированному списку. Верхнеуровневый тест со всеми подтестами остается в одном шарде. Индексы начинаются с 1; обе переменные обязательны вместе.
|
||||
|
||||
`TestOrganizationsAndMemberships` в `backend/integration_test/organizations_test.go` использует `bootstrap(t, postgresService)` с мигрированной схемой и между случаями очищает таблицы организаций вместе с `users`:
|
||||
```sh
|
||||
TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 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
|
||||
make -C backend test-scripts
|
||||
```
|
||||
|
||||
- Хранение: организация сохраняется с владельцем и читается с профилем, представителями по порядку, версией 1, уровнем `e0` и активным членством владельца; незаданные поля равны NULL.
|
||||
- Уникальность членства: повторное членство того же аккаунта в той же организации, в каждой из четырех ролей и после выхода участника, завершается `ErrMembershipExists` с именем `memberships_user_id_organization_id_key`, прямая вставка завершается SQLSTATE 23505, и остается одна строка; другой аккаунт или другая организация - другая пара.
|
||||
- Атомарное создание: неизвестный аккаунт владельца откатывает организацию, представителей и членство; последующий сбой той же транзакции тоже; членство владельца, которое является рекрутером, относится к другой организации или нулевое, отвергается до любой записи.
|
||||
- Владелец при фиксации: транзакция, вставляющая только организацию, только с рекрутером, только с приостановленным владельцем или с владельцем, которого она переводит в `removed` до фиксации, падает при фиксации с SQLSTATE 23514 на `organizations_owner_required` и ничего не оставляет; организация и активный владелец, вставленные в одной транзакции, фиксируются.
|
||||
- Список в своей области: организации одного аккаунта включают те, где он рекрутер, и исключают те, где его членство приостановлено, завершено выходом или удалено, и все организации другого аккаунта; страницы по две следуют одному порядку без пропуска и повтора; членства, созданные в один момент, упорядочиваются по идентификатору организации; некорректные запросы, в том числе позиция без идентификатора организации, отвергаются; организация без представителей читается с пустым списком.
|
||||
- Доступ: аккаунт без членства, неизвестный аккаунт, неизвестная организация и участник в состоянии `suspended`, `removed` или `left` получают `ErrOrganizationNotFound`, восстановленный участник снова читает, а `Memberships().Get` возвращает сохраненное состояние в любом состоянии.
|
||||
- Обновление: владелец заменяет профиль, список представителей и контакты, версия растет до 2, время обновления меняется, очищенные поля становятся NULL, а уровень проверки, который процесс выставил в `e1`, остается `e1` после следующего обновления профиля. Рекрутер получает `ErrOrganizationManagerRequired`, приостановленный владелец, посторонний и неизвестный аккаунт получают `ErrOrganizationNotFound` даже с устаревшей версией, устаревшая версия получает `ErrOrganizationVersionConflict`, и ничто из этого не меняет сохраненную организацию.
|
||||
- Отзыв во время обновления: транзакция, отзывающая второго владельца, остается открытой, обновление этого владельца встает в очередь за блокировкой его членства (видно в `pg_stat_activity`), а когда отзыв фиксируется, обновление возвращает `ErrOrganizationNotFound` и ничего не пишет. Без `FOR SHARE` на членстве исполнителя тест падает.
|
||||
- Конкуренция: восемь обновлений от одной версии на своих соединениях дают ровно один успех и семь конфликтов, а сохраненные название и представитель принадлежат одному победителю.
|
||||
- Ограничения через прямой SQL: пустое, с пробелами по краям, многострочное или слишком длинное название, неизвестный уровень, основание другого уровня, версия ноль, описание с пробелом на конце или управляющим символом, сфера с переводом строки, сайт по http или с учетными данными, email с пробелом, телефон без `+`, имя Telegram без `@`, обновление раньше создания, пары уровня и основания для `e1`, `e2` и `e3` (верные принимаются, неверные отвергаются), составной внешний ключ на `(organization_id, id)` членств (принимается для организации самого участника, отвергается для чужой), неизвестная роль (включая `manager`), неизвестное состояние (включая `invited`), одиннадцатый представитель и должность с пробелом по краю отвергаются по имени ограничения; в таблице организаций нет столбца роли, владельца, участника или пользователя.
|
||||
- Удаление: аккаунт с членством и организацию с участником удалить нельзя (SQLSTATE 23001); когда членства удалены, организация забирает представителей с собой.
|
||||
Без переменных выполняется весь набор. CI использует два шарда. `test-scripts` проверяет покрытие распределения, выбор тестов и передачу кода ошибки. Распределение детерминированное, но не учитывает длительность отдельных тестов.
|
||||
|
||||
`TestPostgresMigrations` откатывает миграцию 00010 вместе с остальными, проверяет, что три ее таблицы и функция исчезают, а таблицы identity остаются, и проверяет их снова после второго применения. Тесты, очищающие `users`, называют `usersDependentTables` (таблицы identity, доставок, согласий и организаций) - единственный список, который нужно расширять, когда миграция добавляет таблицу со ссылкой на users. Этот набор хранения не покрывает usecase и HTTP; отдельные проверки ниже используют реальную сессию и CSRF. Атомарность чтения организации с представителями одним оператором тестом не доказана, потому что окно между двумя операторами нельзя воспроизвести детерминированно.
|
||||
## Frontend
|
||||
|
||||
`TestOrganizationCreationAndOwnerEditingOverHTTP` и `TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` проверяют создание и изменение организации, идемпотентный повтор, свою постраничную директорию, owner-only действия, чужие организации и прекращенное членство через настоящий HTTP и PostgreSQL. Отзыв второго владельца закрывает профиль и tenant-операции для той же cookie, не закрывая доступ другого владельца. Проверки middleware перечисляют все tenant operations контракта.
|
||||
Vitest работает в Node и проверяет логику, преобразования данных и компоненты в доступном ему окружении. Браузерные spec-файлы из `frontend/e2e/` исключены из этого запуска.
|
||||
|
||||
`TestCompanyIsolationAndRevocationOverHTTP` (`backend/integration_test/company_isolation_http_test.go`) проверяет изоляцию компаний и отзыв на минимальном пути через настоящий HTTP и PostgreSQL. Компания A проходит потребность, поиск, карточку с доказательствами, приглашение, принятое с C4, чтение контактов и уведомление. Затем компания B и вторая компания того же владельца A в том же холдинге вызывают каждую операцию в контексте организации с действующей сессией: по пути A и по своему пути с идентификаторами из ответов A. Каждый вызов должен отвечать документированным отказом, таким же, как для случайного идентификатора, а объекты A должны остаться без изменений. Ту же проверку получает кандидат с приглашением и уведомлением другого кандидата. Тест также проверяет, что скрытие организации, отзыв C4 и отзыв C2 закрывают следующее же чтение через handle прежней выдачи, страницу приглашения и чтение контактов. Новое C2 или новая публикация не должны возвращать разрешение, закрытое отзывом C4. MVP не должен отдавать PDF, snapshot выдачи или сохраненный результат поиска, а лог сервера, payload outbox, строки входящих уведомлений и сохраненные запросы писем не должны содержать контактов, имени и значений профиля. Kafka, браузер и роли, кроме владельца, он не покрывает.
|
||||
```sh
|
||||
make -C frontend test
|
||||
make -C frontend typecheck
|
||||
make -C frontend check
|
||||
```
|
||||
|
||||
## Тесты профиля кандидата
|
||||
`check` включает форматирование, ESLint, Stylelint, типы, Vitest, границы FSD и production build. MSW и подмена ответов API проверяют frontend-поведение; они не доказывают серверную авторизацию или сохранение данных.
|
||||
|
||||
Модульные тесты (`make -C backend test`) проверяют правила профиля без базы данных:
|
||||
## Браузерный E2E-набор
|
||||
|
||||
- `internal/domain/candidate_test.go`: ручные значения получают источник `manual`, уровень доверия 0 и время сохранения; поле, посланное как null, удаляется, а список заменяется; предложение импорта остается неподтвержденным при `extracted` с тем же значением, подтверждается при `confirmed` с сохранением источника и цитаты, становится ручным при другом значении, а `extracted` для значения, которого нет среди предложений, и возврат подтвержденного значения в предложение отклоняются с указателем `/stack/1/status`; таблица значений называет поле, которое нарушило правило (телефон вне E.164, Telegram без `@`, имя с пробелами, зарплата не кратна 1000, неизвестные специализация и грейд, повтор тега без учета регистра, повтор специализации роли, месяц не в формате `YYYY-MM`, период, который кончается раньше начала или лежит в будущем, слишком много элементов); ошибка не содержит присланного значения; тело без изменений не меняет профиль и время подтверждения; строки хранилища (`StoredClaims`) восстанавливаются в то же содержимое в любом порядке, а строка с неизвестным видом, уровнем доверия выше 0, цитатой у ручного значения, значением чужого типа, лишним ключом `confirmed_grade`, пропуском в списке или повтором отклоняется; типы профиля не имеют полей подтвержденного грейда, категории или уровня доверия; значения скрыты в выводе `fmt` и `slog`.
|
||||
- `internal/adapter/primary/http/candidate_profile_contract_test.go`: по бандлу контракта операции следуют соглашениям (сессия и CSRF для сохранения, версия в теле, нет Idempotency-Key и If-Match, 412 вместо 409, `no-store`); запрос не несет подтвержденную категорию, источник, уровень доверия и время подтверждения, а все схемы профиля закрывают объекты; каждое заявление несет `status` и `source`, а `trust_level` ограничен нулем; имя использует `ContactFullName`; **ни одна схема вне семейства профиля, ни одна операция организации не достигает схемы профиля по ссылкам, и профиль не ссылается на схемы организации, приглашения или потребности**; через сгенерированный сервер схема отклоняет присланную клиентом категорию, источник и неизвестные поля до реализации, а допустимый профиль отвечает 501, при отклоненной сессии - 401.
|
||||
- `frontend/src/shared/api/profile-contract.test.ts`: сгенерированные схемы Zod принимают полный профиль и профиль без единого значения (то есть без файла и ФСП), требуют `expected_version`, отклоняют каждый нарушенный формат и лишние элементы списков, не пропускают в разобранное тело подтвержденный грейд, категорию и источник, требуют у каждого заявления источник с уровнем доверия 0, а типы запросов не имеют этих полей; сгенерированные файлы организации, приглашения и потребности не содержат ключей профиля, и наоборот.
|
||||
```sh
|
||||
make -C frontend install
|
||||
make -C deploy test-e2e
|
||||
make -C deploy test-e2e-registration
|
||||
```
|
||||
|
||||
`TestCandidateProfileStorage` в `backend/integration_test/candidate_profile_test.go` использует `bootstrap(t, postgresService)` с мигрированной схемой; `candidateProfileTables` входят в `usersDependentTables`, поэтому остальные тесты очищают их вместе с `users`:
|
||||
Обе команды создают одноразовый Compose-проект с собственными секретами и volumes. Браузер обращается к приложению через Nginx. Скрипт убирает тестовые контейнеры и volumes при завершении; результаты остаются в `frontend/test-results/e2e/`.
|
||||
|
||||
- Сохранение без файла, ML и ФСП: профиль только с именем, а также строка профиля без единого заявления сохраняются и читаются, а полный профиль возвращается с тем же содержимым и источником через `StoredClaims` и `RestoreCandidateProfile`; сохраненное предложение импорта читается с цитатой, версией извлечения и уровнем 0.
|
||||
- Схема: столбцы двух таблиц равны ожидаемому списку (без файла, ФСП, подтвержденного грейда и категории), а единственные внешние ключи ведут на аккаунт и на строку профиля.
|
||||
- Ограничения через прямой SQL: каждое правило отказывает строке с собственным ограничением (уровень доверия выше 0, неизвестные вид, статус и источник, одиночное поле с позицией, список за пределом, подтверждение без времени, ручное значение с цитатой, импорт без версии извлечения, неверные значения тега, телефона, Telegram, переезда, зарплаты, роли с ключом `confirmed_grade` и опыта); повтор тега, навыка и специализации роли, профиль без аккаунта, версия 0 и заявление без профиля тоже отклоняются, а такая же корректная строка принимается.
|
||||
- Удаление аккаунта удаляет профиль и заявления; два аккаунта хранят профили независимо.
|
||||
- Версия: проигравшее второе первое сохранение и устаревшая версия не возвращают строку, восемь продвижений от одной версии и восемь параллельных первых сохранений на своих соединениях дают ровно один успех, а продвижение с более ранним временем приложения сохраняет время обновления и не нарушает CHECK. Чтение идет одним запросом `ReadCandidateProfile`.
|
||||
Обычный `test-e2e` использует отключенную почту. Он выполняет технические и доступные UI-сценарии; тесты, которым нужны почта и специальные фикстуры, пропускаются. `test-e2e-registration` включает локальный Resend-совместимый приемник и синтетические данные для регистрации и бизнес-сценариев. Он не отправляет письма через реальный Resend.
|
||||
|
||||
`TestCandidateProfileMigrationRollsBack` откатывает миграцию 00013 на изолированной базе, проверяет, что обе таблицы исчезают, а `users` остается.
|
||||
В наборе есть два вида проверок:
|
||||
|
||||
`TestCandidateProfileOverHTTP` проверяет собственный профиль через сессию и CSRF: пустой GET, полное сохранение и перезапуск API, конкретные ошибки дат и пересечений, подтверждение параллельной работы, 412, отсутствие записи истории при no-op, недоступность чужого профиля и отказ employer. История, данные и условный переход шага находятся в одной транзакции; ошибки вставки истории и перехода шага откатывают сохранение. Изменение самооценки не создает подтвержденную категорию.
|
||||
- С настоящим backend: регистрация, профиль, анкета, организации, потребности, поиск, приглашения и минимальный путь в `acceptance-path.spec.ts`. Нужные фикстуры включаются почтовым стендом.
|
||||
- С подменой API через `page.route`: состояния экранов, ошибки, конфликты, часть сценариев оценки и доступности интерфейса. Эти тесты подтверждают поведение браузера в заданном состоянии.
|
||||
|
||||
## Тесты анкеты кандидата
|
||||
Playwright запускает Chromium с одним worker и без повторов. Поиск по реальному банку идет первым, чтобы записи других spec не меняли выдачу. Конфигурация принимает только loopback-адрес стенда.
|
||||
|
||||
`TestCandidateQuestionnaireOverHTTP` использует настоящие сессии, CSRF и PostgreSQL. Он проверяет пустую анкету версии 0, сохранение и перезапуск обработчика, изоляцию аккаунтов, отказ работодателю, отклонение неизвестных полей подтвержденного грейда, разные конкурентные записи с ответами 200/412, одинаковые конкурентные записи с ответами 200 и одним повышением версии, условный переход onboarding, откат, парность полей опыта и закрытие каталога после смены политики или отзыва семейства. Самооценка не создает подтвержденную категорию. Канонический API использует 412 для конфликта версий; прежняя формулировка задачи упоминает 409.
|
||||
При ошибке смотрите HTML-отчет, trace и скриншот. Перечисляйте passed, failed и skipped: зеленый запуск с пропущенным нужным сценарием не закрывает его приемку. Не направляйте E2E на общий или production-стенд.
|
||||
|
||||
Изолированный почтовый overlay задает `IDENTITY_CLIENT_HOURLY_LIMIT=200`, поскольку все браузерные сценарии используют один адрес прокси. Обычная и релизная конфигурации сохраняют 30, лимиты отдельного email не меняются.
|
||||
### Приемка демонстрационного пути
|
||||
|
||||
`questionnaire.spec.ts` использует локальный почтовый fixture и явно опубликованный синтетический банк Backend/Junior с Go и Python. Тестовая команда `questionnaire-fixture` принимает только неизмененную начальную демо-политику, явно публикует `DemoProductPolicyV2`, затем публикует необходимое число проверенных семейств перед привязкой каталога. Это также включает разделы политики поддержки и оценивания для браузерных тестов. Команда отказывается работать поверх существующего backend-банка или другой действующей либо запланированной политики и отсутствует в обычном и релизном образах. Обычный запуск по-прежнему создает только V1. Браузерный сценарий проходит шаги анкеты (проверка шага, фокус на заголовке, "Назад" и "Изменить" без потери ответов) и проверяет сохранность, специализацию DS/ML с пометкой о разработке, клавиатуру и верстку на 360/768/1280 px, а также конфликт между двумя настоящими сессиями. Без изолированных fixtures сценарий пропускается.
|
||||
Перед показом выполните `make docs-check`, `make -C deploy check`, smoke и почтовый E2E-набор. В `acceptance-path.spec.ts` должны пройти полный тест с категорией `synthetic_demo`, публикация, поиск с объяснением, приглашение, C4 и раскрытие контактов; повторное принятие не должно создавать дубликаты, а отзыв доступа должен закрывать чтение. Пропуск этого spec не считается приемкой.
|
||||
|
||||
`assessment.spec.ts` использует тот же изолированный fixture. Он сохраняет оба языка и явно выбирает Python, затем проходит полную попытку клавиатурой на 360 px и ожидает завершения и результата от сервера. Отдельно проверяются express-режим с продолжением незавершенного запуска после перезагрузки (409 на новое начало, затем 201 по сохраненному ключу), отправка ответа без сети, повтор после некорректного успешного ответа, обновление страницы и продолжение сохраненной попытки. Явные снимки покрывают 360 и 1280 px. Синтетические проверки подтверждают работу приложения, но не калибровку оценки.
|
||||
Сверьте результат с запускаемым коммитом или образами. Локальная почтовая фикстура не доказывает доставку настоящим Resend, локальный Nginx - работу внешнего HTTPS, а синтетический банк - точность грейда. Для выпуска повторите smoke и E2E на закрепленных образах по [DEPLOYMENT.md](DEPLOYMENT.md).
|
||||
|
||||
## Минимальный путь от регистрации до раскрытых контактов
|
||||
## ML и модели
|
||||
|
||||
В режиме регистрации overlay `docker-compose.e2e-mail.yml` выставляет тестовому backend `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` и передает Playwright `E2E_DEMO_CATEGORIES=1`. После `questionnaire-fixture` runner аттестует открытую категорию Backend Junior операторской командой `/assessment-category-attest` из тестового backend-образа, поэтому пройденный полный тест на этом стенде получает некалиброванную категорию `synthetic_demo`, как на демонстрационном стенде. Обычный и релизный наборы сохраняют значение по умолчанию `false`, а `make -C deploy check-e2e-mail` проверяет обе настройки.
|
||||
`make -C ml verify` проверяет формат, Ruff, mypy, pytest, сборку, контракт и актуальность Pydantic-моделей. Обычные тесты отделены от медленных проверок реальных весов.
|
||||
|
||||
`frontend/e2e/acceptance-path.spec.ts` проходит минимальный путь на настоящем backend без ФСП ID. Пять кандидатов регистрируются по ссылке из полученного письма, заполняют профиль и анкету, дают C3, решают каждое задание полного теста по его условию и после явного C2 публикуют одинаковую карточку, потому что карточка показывается только в группе из пяти. Затем spec проверяет:
|
||||
```sh
|
||||
make -C ml model-fetch
|
||||
make -C ml test-model
|
||||
```
|
||||
|
||||
- результат `confirmed` с решением о категории `assigned`, `demo_basic_pass_mark`, `synthetic_demo`; перезагрузка посреди попытки возвращает ту же попытку без второго ответа, а история результатов хранит одну запись после перезагрузки и шага назад и вперед по истории браузера;
|
||||
- потребность, поиск по ее версии требований с пятью подтвержденными записями и объяснением от сервера, фильтр по заявленному грейду senior, который убирает все пять карточек и оставляет только чужие карточки с этим грейдом, и неизменный результат первой версии требований после правки потребности;
|
||||
- три приглашения, привязанные к первой версии требований и доставленные по одному разу; ни результат поиска, ни список приглашений, ни уведомления организации не содержат email, телефон или имя;
|
||||
- принятие в браузере только с email, после которого перезагрузка и шаг по истории не добавляют записей, для организации есть одна запись C4, а организация читает только email;
|
||||
- два одновременных принятия одного приглашения с разными ключами: оба отвечают 200 с одинаковым телом, одна запись C4 и один grant;
|
||||
- отказ без доступа и отказ 409 `state_conflict` в новом приглашении для той же пары;
|
||||
- вторую компанию, которая получает 404 или ошибку поля, но не данные, для потребности, поиска по этой потребности, карточек, приглашений и контактов первой;
|
||||
- отзыв C2, который сразу закрывает чтение контактов и карточки прежнего результата (оставшиеся четыре карточки оказываются меньше группы из пяти и тоже скрываются), и новые C2 и публикацию, которые открывают карточки, но не grant принятого приглашения.
|
||||
`model-fetch` скачивает закрепленные файлы Giga и Qwen3 embeddings и сверяет SHA-256; нужен доступ к источнику весов и место на диске. `test-model` сравнивает реальные модели с исследовательскими векторами; для GPU задайте `ML_TEST_DEVICE=cuda`. Это проверка воспроизводимости inference, а не доказательство качества подбора на реальных кандидатах.
|
||||
|
||||
Spec не проверяет запланированные переходы без операции (отзыв приглашения компанией, отмену участия кандидатом, встречное предложение, интервью, закрытый финал), лимит 20 приглашений на потребность и истечение срока (их покрывают интеграционные тесты backend), рекомендации категорий для потребности, которые остаются `pending`, и PDF. Трассировка и снимки выключены, данные синтетические.
|
||||
## Runner и лаборатории
|
||||
|
||||
## Тесты видимости кандидата
|
||||
`make -C runner check` и `make -C labd check` проверяют Go-модули. Их unit-тесты не требуют работающей песочницы или LXD.
|
||||
|
||||
Модульные тесты (`make -C backend test`) проверяют правила видимости без базы:
|
||||
Проверки реального runner, его изоляции и лабораторий запускаются отдельно на предназначенном для тестов окружении. Условия и команды находятся в [runner/](../../runner/README.md) и [labd/](../../labd/README.md). Результат на локальном dev-контейнере не подтверждает изоляцию развернутого runner.
|
||||
|
||||
- `internal/domain/visibility_test.go`: набор полей карточки канонический, закрытый и отклоняет полное имя, любой контакт и зарплату; запрос публикации требует поле для публикации и не допускает его при закрытии; новый профиль закрыт и не публиковался; публикации нужна действующая C2, а согласие она не называет; порядок проверок (будущая версия, неизмененное состояние при устаревшей версии, устаревшее изменение, нет согласия); отозванная C2 закрывает карточку, а новая ее не открывает; статус поиска истекает через срок политики до непубличного статуса без записи, подтверждается заново явно и берет срок из версии политики; сохраненные строки, нарушающие инвариант, отклоняются; типы пишут в журнал только идентификаторы.
|
||||
- `internal/adapter/primary/http/candidate_privacy_contract_test.go`: по бандлу контракта операции следуют соглашениям (схема CSRF ровно для изменений, версия в теле, нет Idempotency-Key и If-Match, одинаковый 404 для скрытия, 204 без 404 для снятия); публикация и статус поиска не несут согласия и не достигают схем друг друга; **анонимная карточка и предпросмотр не достигают схем профиля, контакта, согласия, приглашения или организации и не имеют свойства, называющего или идентифицирующего человека**, а путь организации не достигает настроек; через сгенерированный сервер схема отклоняет контакт как поле карточки, идентификатор согласия и время от клиента до реализации, валидный запрос отвечает 501, а отказанная сессия - 401.
|
||||
- `frontend/src/shared/api/privacy-contract.test.ts`: сгенерированные схемы Zod читают нового кандидата как закрытого и не ищущего с версией 0, отклоняют поле карточки, которое является именем, контактом или зарплатой, убирают согласие, время и срок из разобранных запросов, не пускают контакты в карточку, а в сгенерированных файлах организации, приглашения, потребности, профиля и согласий нет ключей настроек.
|
||||
## Контракты, инфраструктура и безопасность
|
||||
|
||||
`TestCandidatePrivacyStorage` в `backend/integration_test/candidate_privacy_test.go` использует `bootstrap(t, postgresService)`; `candidatePrivacyTables` входят в `usersDependentTables`:
|
||||
После изменения API выполните `make generate`, проверьте потребителей и `make check-generated`. Для намеренного обновления output ожидаемый diff должен быть проверен и сохранен вместе с источником.
|
||||
|
||||
- У нового профиля нет состояния публикации: после сохранения профиля все четыре таблицы пусты, а чтения не возвращают строки. Скрытая организация уникальна для кандидата и принадлежит ему; неизвестную организацию отклоняет ссылка; снятие удаляет один раз; 1001-ю запись отклоняет триггер.
|
||||
- Публикация: внешний ключ принимает только запись C2 того же аккаунта; отзыв в журнале закрывает карточку без записи; новая выдача C2 ничего не публикует; устаревшее обновление не возвращает строку; ограничения отклоняют контакт как поле, неверный порядок и неверную форму состояния.
|
||||
- Статус поиска: в фикстуре статус задается, подтверждается и снимается, а сырые строки журнала согласий, публикации и скрытых организаций остаются равными; `looking` хранит подтверждение под версией политики со сроком политики; истечение не меняет строк; ограничения отклоняют `looking` без подтверждения; в таблице нет столбца согласия, а внешний ключ ведет только на аккаунты.
|
||||
- Закрытие поверх отозванной C2 нормализует сохраненную строку и записывает закрытие; организация читает публикацию только через действующее представление и не читает, если скрыта (тот же ответ без строки, что и для неопубликованного профиля); отзыв, гоняющийся с публикацией, удерживаемой под `LockCurrentC2Record`, ждет ее и закрывает карточку после, либо не находит что блокировать; восемь параллельных скрытий при 999 записях пропускают ровно одно; очистка неподтвержденных аккаунтов удаляет записи скрытия и историю неподтвержденного аккаунта и не трогает подтвержденный. `backend/db/privacy_queries_test.go` падает, когда запрос, кроме трех запросов настроек, называет `candidate_publications`, а `TestCardTextLooksLikeContact` фиксирует отбрасывание свободного текста, похожего на контакт.
|
||||
- История: только добавление (UPDATE отклоняется, DELETE отклоняется, пока аккаунт подтвержден), только идентификаторы, форма каждого вида проверена, страницы продолжаются по позиции, опубликованные поля и запись C2 хранятся со временем. Ни в одной таблице видимости нет столбца для значения профиля, имени, контакта или файла.
|
||||
`make -C deploy check` проверяет конфигурацию и вспомогательные скрипты. `smoke` проверяет готовность инфраструктуры и HTTP-маршруты, `perimeter-test` - правила Nginx на одноразовых контейнерах. Они не заменяют бизнес-сценарий. `make -C observability check` проверяет конфигурацию мониторинга.
|
||||
|
||||
## Тесты банка заданий
|
||||
`make security` запускает проверки зависимостей, кода и секретов; `make security-images` собирает и сканирует образы. Установка инструментов и отчеты описаны в [security/](../../security/README.md).
|
||||
|
||||
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go` и `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) проверяют без базы: отклоняется некорректное содержимое семейства (правила рецензии, неизвестный алгоритм, границы параметров, несоответствие формата ответа, форма рубрики, символы формата Unicode); шаблоны условий принимают только текст и подстановки `{{.name}}`, а бомба из вложенных `define`, бомба ширины `printf`, `range` по числу и рекурсивный `block` отклоняются быстрее секунды и не запускаются; шаблон без подстановок, от которых зависит ответ, отклоняется; размер готового условия ограничен; измененный сохраненный документ не проходит проверку хеша; каждый отказ в публикации называет причину; один seed дает один вариант, а рубрика одинакова для всех seed; golden-тесты фиксируют точное условие и эталонный ответ для заданного seed у каждого из четырех алгоритмов и хеш содержимого схемы 1 для заданного входа; строка проверяется схемой хеша, с которой она сохранена (тест регистрирует вторую схему, а хеш одной схемы под именем другой и неизвестная схема отклоняются); шаблон, чье условие достигает границы размера только для одного пробного seed, отклоняется при импорте, потому что наибольшие значения параметров подставляются для восьми seed; разделители строки и абзаца отклоняются как символы формата; четыре решателя совпадают с посчитанными вручную случаями; покрытие для открытия равно `max_scored_items` плюс `seed_items` политики; демонстрационный пакет читается как черновик ИИ с рецензией `pending` и без рецензента. `assessment_choice_test.go` проверяет формат с выбором без базы: один seed дает одинаковые варианты, ID и порядок, а по 400 seed правильный вариант встречается на каждой позиции; каждый отвлекающий вариант `lru_hits_choice.v1` пересчитывается по условию как результат именованной модели ошибки (а добор соседними значениями используется, только если модели дали меньше трех различных значений), варианты не повторяют текст, модели кэша совпадают с посчитанными вручную случаями, а модель LRU равна решателю `lru_hits.v1`, golden-тест фиксирует варианты, их ID и ключ одного seed; правильный вариант, неверный вариант, вариант чужого задания, два варианта, числовой ответ на задание с выбором и ответ с выбором на целочисленное задание оцениваются или отклоняются, как описано, проекция для кандидата содержит только непрозрачные ID и тексты, а поврежденный ключ или повторяющийся вариант замороженного варианта отклоняются. `assessment_table_test.go` проверяет табличные семейства: строки выбираются по seed, ответ - записанный, выбор для фиксированных seed зафиксирован, каждая из 39 ошибок формата (нет столбца, повтор строки, неверный ответ, повторяющийся отвлекающий вариант, слишком большое условие, вызов или конвейер в шаблоне, алгоритм рядом с таблицей и другие) отклоняется с индексом строки, хеш схемы 2 Line truncated
|
||||
## Отчет о проверке
|
||||
|
||||
`TestAssessmentBank` в `backend/integration_test/assessment_bank_test.go` использует `bootstrap(t, postgresService)` и дает каждому случаю свою мигрированную базу:
|
||||
Указывайте команду, проверенный коммит или diff, результат и существенные ограничения. Для сбоя сохраняйте воспроизводимый сценарий без секретов. Для качества оценки, подбора и производительности нужны отдельные данные, методика и измерения.
|
||||
|
||||
- Две версии одного семейства импортируются, версия 1 читается с исходным ключом, а у версии 2 ключ другой; повторный импорт ничего не меняет, та же версия с другим содержимым и пропущенный номер версии отклоняются с причиной, а сырой SQL не может изменить ключ, версию или рецензию, удалить или очистить таблицу (SQLSTATE 23000 на `assessment_families_immutable`).
|
||||
- Один seed дает одинаковые условие и эталонный ответ из сохраненной версии, а другой seed сохраняет рубрику каждого демонстрационного семейства.
|
||||
- Демонстрационный пакет импортируется черновиками; публикация каждого семейства отклоняется с `reviewer_missing`, таблица отклоняет публикацию без одобренной рецензии, а открытие `backend` отклоняется с `coverage_insufficient` и не сохраняет открытия.
|
||||
- Открытие без ссылки на политику, с неизвестной ссылкой или с версией политики, которая сейчас не действует, отклоняется с подходящей причиной.
|
||||
- Тестовый пакет с одобренной рецензией рецензента, который не является автором (фикстура правил загрузчика, а не демонстрационное содержимое), публикуется по одному семейству; категория открывается, только когда опубликованных семейств становится не меньше `max_scored_items` плюс `seed_items` политики; открытие хранит версию политики, оператора и числа, требуемое число, выведенное базой, равно числу из домена, а открытие не редактируется. Вывод из обращения одного семейства после этого заставляет чтение доступности отказывать с `coverage_insufficient`. Опубликованную версию нельзя опубликовать снова, можно один раз вывести из обращения, а назад она не идет.
|
||||
- Публикация более поздней версии семейства выводит из обращения опубликованную более старую и записывает обоих операторов; публикация более старой версии при опубликованной более новой отклоняется; таблица допускает одну опубликованную версию на семейство и отклоняет перезапись записанного публикатора.
|
||||
- Транзакция, держащая блокировку категории, заставляет открытие ждать до срока, а после освобождения блокировки открытие проходит.
|
||||
- Более старый одобренный черновик нельзя опубликовать, когда существует более новая версия, в том числе выведенная из обращения. Проверки действующей политики используют часы базы данных, без сдвига часов в тесте.
|
||||
- Пакет с табличным семейством и семейством с выбором импортируется: таблицы со схемой хеша 2, алгоритм со схемой 1; повторный импорт сообщает их как неизмененные, а сохраненные строки дважды дают одинаковые варианты; прямая правка сохраненной таблицы отклоняется как правка сохраненной версии.
|
||||
- `TestAssessmentChoiceAndTableFamiliesAreServedAndGradedOverHTTP` в `backend/integration_test/assessment_choice_http_test.go` проходит настоящую попытку по банку из алгоритма с выбором, целочисленной таблицы и таблицы с выбором: каждое задание, которое получает кандидат, содержит только разрешенные поля (для выбора - ID и тексты вариантов в сохраненном порядке, без поля ключа, seed или отвлекающего варианта), вариант чужого задания и два варианта отклоняются с 400, неверный выбор не дает баллов, а верный дает их по ключу, результат совпадает с ожидаемым числом баллов, и каждый ответ оставил наблюдение сигналов.
|
||||
- Сырые строки политики, в документе которых нет границ оцениваемых заданий, они заданы текстом, слишком большим, дробным или отрицательным числом или нет seed-заданий, отклоняются триггером открытия отказом по порогам, а не ошибкой приведения типа; сохраненная схема хеша вне списка CHECK отклоняется, а саму схему изменить нельзя.
|
||||
- В обход usecase таблица отклоняет открытие с заниженным требованием, открытие ниже покрытия, открытие под неизвестной версией политики и название с переопределением направления текста.
|
||||
- Семейства выводятся страницами по две после курсора, каждое один раз и по порядку.
|
||||
|
||||
`TestPostgresMigrations` откатывает миграцию 00011 вместе с остальными и проверяет, что две ее таблицы и пять функций исчезают, а таблица политик остается. Набор доказывает только правила хранилища и загрузчика: он не проверяет содержимое демонстрационного пакета, сложность задач и какие-либо грейды, не доказывает сериализацию одновременных публикаций сверх случая с удерживаемой блокировкой и не покрывает сценарий кандидата, потому что его еще нет. Интеграционным тестам нужен Docker.
|
||||
|
||||
## Тесты сигналов оценки и полосы проверки
|
||||
|
||||
`backend/internal/domain/assessment_signal_policy_test.go` и `assessment_signal_review_test.go` проверяют без базы: демо-раздел сигналов корректен и проходит круг через документ схемы 2, один раздел сигналов - допустимое расширение и никогда не получает значений по умолчанию, схема 1 отклоняет ключ, значения вне диапазона и несогласованные пороги отвергаются, время ответа следует порогам формата и отношению к медиане только на быстрой стороне в пределах одного формата и не учитывает первый элемент сессии, метки происхождения считают чередования и различные сети по времени (возврат в прежнюю сеть не новая сеть), полоса следует политике, слабые сигналы (параллельные сессии и лишние сети - одна коррелированная группа) останавливаются на «внимание», пока нет сильного сигнала, ответ считается один раз как быстрый или как отклонение, клиентские сигналы поднимают полосу только до «внимание», и имя оператора должно быть `operator:<handle>`. `backend/internal/usecase/identity/keyring_test.go` проверяет новые методы keyring: отпечаток ответа детерминирован, ключевой и привязан к версии семейства; дайджесты сессии и сети различаются между попытками (связать нельзя), между сессиями и между ключами клиента и используют отдельные ключи назначения.
|
||||
|
||||
`backend/internal/usecase/assessment/signal_review_test.go` проверяет наблюдателя и задание проверки на поддельных портах: принятый ответ сохраняет серверное время, признак отсчета от предыдущего ответа, версию ключа и только ключевой отпечаток, без текста ответа, адреса и идентификатора сессии ни в сохраняемых значениях, ни в тексте ошибки; метки происхождения пишутся только при смене сессии или сети; первый ответ планирует задание дедлайна (через минуту после дедлайна), а завершение - задание завершения; тренировочные попытки и запросы без сессии ничего не сохраняют; версия политики без раздела сигналов не создает проверку; задание отклоняет испорченную нагрузку, пропускает отсутствующую попытку, блокирует проверки пары по возрастанию идентификатора попытки до чтения любого факта и пишет их под своими закрепленными политиками, и обновляет только завершившиеся попытки на уровне «внимание», ограниченно. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` берет по 4000 seed каждого демо-семейства, строит распределение общих значений с их битами и считает вероятность того, что одна честная пара достигнет каждого демо-порога на попытке из 23 заданий; умноженная на 10 000 соперников она равна примерно 4e-5 («внимание») и 3e-9 («проверить») при целях 1e-3 и 1e-8. `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` считает, сколько ответов на семейство нужно скопированной паре, чтобы демо-пороги ее пометили (26 для «внимание» и 61 для «проверить» при 13 заданиях, 9 и 14 при 23). Модель ложных срабатываний использует только распределение эталонных ответов, а не неверные ответы и коррелированные ошибки. Цели - константы теста, выбранные здесь, а не продуктовое решение, а измерение покрывает четыре семейства, написанных ИИ.
|
||||
|
||||
`backend/internal/adapter/primary/http/assessment_signal_review_contract_test.go` обходит каждый путь публичного контракта по ссылкам и отвергает любое свойство, имя схемы или enum, которые несли бы полосу, ее причины, отпечатки или дайджесты происхождения, и проверяет, что в квитанции сигналов по-прежнему ровно `status`, `accepted_events` и `received_at`. `backend/internal/adapter/primary/cli/assessmentreview/command_test.go` проверяет проверку аргументов до чтения окружения, выводимые поля и очищенные ошибки. Тест bootstrap проверяет, что вид задания проверки зарегистрирован.
|
||||
|
||||
`TestAssessmentSignalReviewOverHTTP` в `backend/integration_test/assessment_signal_review_http_test.go` запускает настоящий роутер, PostgreSQL и worker заданий по сроку:
|
||||
|
||||
- Кандидат отвечает на все задания за миллисекунды из двух сессий входа и с трех сетевых адресов и шлет события вставки из второй сессии. Пока worker не запущен, проверки нет, а задания проверки ожидают, то есть в транзакции кандидата ничего не считалось. Затем у попытки полоса `attention` с причинами быстрые ответы, параллельные сессии, лишние сети и клиентские сигналы, а результат `confirmed` совпадает по исходу, баллам, ограничениям и режиму с результатом столь же верной попытки с полосой `normal`; ни в одной таблице оценки, кроме таблицы проверок, нет колонки полосы.
|
||||
- Пока попытки идут, публикуется версия политики с другими порогами и под ней открывается категория. Попытки, начатые раньше, сохраняют первую версию, попытка, созданная позже, закреплена за новой версией и остается `normal` при том же поведении, а ее факты все равно сохранены.
|
||||
- Двое кандидатов с разными seed копируют одинаковые неверные ответы: у первой попытки нет признака дубликата, пока второй кандидат не ответил и не завершил попытку, после чего у обеих полоса `review` с причиной одинаковые ответы. Третья копирующая попытка брошена: пока она идет, ее не помечают, а после окончания ее задание дедлайна (часы worker сдвинуты за срок) ее помечает. Честные попытки с верными ответами не помечаются, даже если совпал ответ из малого пространства, а у попытки с одной сессией и одной сетью ровно одна метка происхождения.
|
||||
- Чтения кандидатом попытки, результата и доступности не содержат полосу, причины, отпечатки и названия сигналов. Команда оператора выводит полосу, а строки аудита пишутся для найденной и для отсутствующей попытки; имя без префикса `operator:` отклоняется. Факты, проверки и строки аудита отклоняют UPDATE и DELETE, а аудит - и TRUNCATE.
|
||||
- Журналы и текст новых таблиц и `scheduled_jobs` не содержат сетевых адресов, значений ответов, токенов сессии и CSRF.
|
||||
|
||||
`TestAssessmentSignalReviewHonestPopulationHasNoDuplicateFlag` создает 30 честных кандидатов с разными seed, которые отвечают на каждое задание верно или нет случайно (фиксированный генератор), и двоих, копирующих одинаковые ответы: ни одна честная попытка не помечена дубликатом, обе копирующие помечены. Совокупность мала, поэтому тест использует пороги 32 и 44 бита, а не демо-пороги. `TestAssessmentSignalReviewConcurrentJobsFlagEveryCopiedAttempt` завершает четыре копирующие попытки одновременно среди восьми честных и запускает их задания на четырех worker сразу: ни одно задание не падает и не повторяется, и каждая копирующая попытка помечена. `TestAssessmentSignalReviewJobWaitsForTheReviewLock` держит блокировку проверки попытки в одной транзакции и проверяет, что задание проверки ждет, ничего не пишет и считает проверку по зафиксированным фактам после снятия блокировки; именно этот порядок не дает устаревшей оценке затереть более новую проверку. Тест параллельных заданий прогнан десять раз подряд (`-count=10`). `TestAssessmentSignalReviewMigrationDownRetainsAudit` проверяет, что откат миграции 33 отклоняется, пока в аудите есть строка (таблицы и строка остаются, TRUNCATE отклоняется), и проходит при пустом аудите.
|
||||
|
||||
Тесты доказывают сохраненные факты, закрепление политики, вычисление заданием и отсутствие полосы в контракте и в чтениях кандидата. Они не доказывают качество обнаружения: пороги не откалиброваны, измерение ложных срабатываний покрывает четыре написанных семейства, исследования на реальных кандидатах нет. Чтения работодателя покрыты обходом контракта, а не HTTP-вызовом каждой операции.
|
||||
|
||||
## Тесты ограничений во время попытки
|
||||
|
||||
Vitest работает в Node без DOM, поэтому ограничения проверяются по частям. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` покрывает определение поддержки (в том числе браузер без полноэкранного режима элемента, например iPhone Safari), то, что запрос делается синхронно внутри вызова и остается внутри клика, и то, что отказ - это результат, а не исключение. `model/cover.test.ts` - таблица случаев, когда задание закрыто: выход из полноэкранного режима, скрытая вкладка, окно без фокуса, запрос в процессе и режим без полноэкранного режима. `ui/protected-region.test.tsx` рисует область с поддельным состоянием и проверяет, что закрытое задание не оставляет в разметке текста условия и вариантов, что у закрытия из-за ухода с вкладки нет кнопки полноэкранного режима, и объяснение для неподдерживаемого браузера; `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что скрытая форма ничего не рисует. Версия 4 текста уведомления и перечень мер проверяются в `features/assessment-signals/ui/signal-notice.test.tsx`. В бэкенде `usecase/assessment/signal_notice_test.go` проверяет, что любая версия, кроме текущей, отклоняется, а `TestAssessmentSignalNoticeOverHTTP` по HTTP с PostgreSQL проверяет, что сохраненное подтверждение версии 1 не засчитывается для текущей версии, а ее версии следуют за `CurrentSignalNoticeVersion`.
|
||||
|
||||
Модульные тесты защиты задания: `model/task-guard.test.ts` проверяет правила на небольших поддельных элементах и событиях: выделение, контекстное меню и перетаскивание отменяются на тексте задания и не трогаются в поле, сброс текста мышью никогда не заполняет поле, вставка отклоняется в полях ответа (и об этом сообщается, чтобы экран мог сказать) и разрешена в редакторе кода, пути `beforeinput` для вставки и сброса закрыты, а набор и композиция никогда не затрагиваются, копирование и вырезание отклоняются, когда цель или выделение доходят до задания, и не отклоняются внутри поля. `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что исключение для вставки есть только у редактора кода.
|
||||
|
||||
Две браузерные спецификации работают с подставным API, поэтому им не нужны данные бэкенда, и их можно запускать и на сервере Vite (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`), и в `make -C deploy test-e2e`; подставной API лежит в `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: выход из полноэкранного режима закрывает задание (его текста нет в странице), отправляет сигнал `fullscreen_exit`, а кнопка продолжения возвращает задание вместе с набранным черновиком; уход с вкладки закрывает задание, а возврат в полноэкранном режиме показывает его; браузер без полноэкранного API показывает объяснение и проходит тест с клавиатуры; отказ в полноэкранном режиме не мешает продолжить; закрытие уведомления без подтверждения выходит из полноэкранного режима и ничего не сохраняет. `assessment-task-protection.spec.ts`: текст задания нельзя выделить, копирование после выделения всего или из скрипта не оставляет текста задания в буфере, контекстное меню и перетаскивание отменяются на задании, но не в поле, поле копирует собственный текст, текст остается в дереве доступности, печать скрывает задание; поле ответа отклоняет вставку и показывает сообщение, а отклоненная вставка уходит сигналом `paste` с размером и без текста; редактор кода принимает вставку и отправляет ее размер; задание отвечается только с клавиатуры. Подтверждение уведомления с настоящим бэкендом покрывает существующий тест уведомления в `assessment.spec.ts`, который теперь ожидает версию 4. Эти спецификации показывают поведение страницы в Chromium с подставным сервером; они не показывают поведение в других браузерах, на телефоне, с настоящим экранным диктором и в оконном менеджере, который сам меняет полноэкранный режим. Правило вставки не видит текст, который экранная клавиатура вставляет как набор.
|
||||
|
||||
## Тесты водяного знака оценки
|
||||
|
||||
`backend/internal/domain/assessment_watermark_test.go` покрывает метку: две попытки с одним настоящим сгенерированным вариантом получают разные тексты с меткой, у которых равны канонический текст и эталонный ответ; разметка детерминирована и идемпотентна; невидимый запуск декодируется в видимый код, переживает копию двух предложений, а обрезанный, удлиненный или с неверной контрольной цифрой запуск игнорируется; доступный текст содержит только слова; выравнивание сохраненного условия с утекшим текстом читает только найденные там обороты (слова вокруг условия, например цитата или сообщение, игнорируются), согласование формулировок попытки, которая написала текст, выполняется для каждой группы оборотов, другие затравки не согласуются, фрагмент дает обороты фрагмента, посторонний текст ничего не выравнивает, а другой вариант того же семейства выравнивается на меньшее число символов, чем утекший; части между оборотами одинаковы в каждой копии условия; числовая защита оставляет `at most` в конце предложения; коды разбираются так, как их читает оператор или распознавание. `usecase/assessment/watermark_test.go` проверяет, что размечаются только root и corrective, что сохраненный снимок не меняется, что видимый код равен невидимому и что отсутствие `Watermarker` оставляет снимки как есть; `adapter/primary/http/v1/assessment_test.go` проверяет, что каждый ответ с попыткой проходит через презентер и что отказ презентера - ошибка. `TestAssessmentWatermarkOverHTTP` (PostgreSQL) по HTTP проверяет, что реальная попытка при создании, чтении и повторе показывает код, выведенный на сервере, и текст с меткой, что учебный запуск не показывает ни того, ни другого, что в ответе только код и что в сохраненном условии метки нет. Во фронтенде у `features/assessment-watermark` есть тесты Vitest разбиения текста, доступного текста отрисованной разметки (без всего, что в `aria-hidden`, остаются ровно слова) и плитки (код и время UTC, без `@`, скрыта от вспомогательных технологий). `e2e/assessment-watermark.spec.ts` работает с подставным API (и на сервере Vite, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-watermark.spec.ts --project=chromium`): плитка есть на экране задания с кодом и временем и без email аккаунта, бледная и не перехватывает клики, у попытки без кода плитки нет, а дерево доступности размеченного условия содержит слова и ни одного символа форматирования, хотя документ их хранит. Эти тесты не запускают настоящий экранный диктор, брайлевский дисплей или другой браузер, поэтому не показывают, как диктор читает текст; они не показывают и того, сколько попыток можно различить по утечке, потому что канал формулировок дает около одного бита на группу оборотов.
|
||||
|
||||
## Тесты подсказок о съемке экрана и рабочего сеанса оценки
|
||||
|
||||
Домен и юзкейс. `assessment_signal_review_test.go` проверяет правила полосы: подсказки о съемке, лишние User-Agent и все слабые сигналы вместе останавливаются на attention при любых счетчиках, лишние агенты достигают review только рядом с сильным сигналом, а политика без порогов съемки игнорирует подсказки. `assessment_signal_policy_test.go` проверяет, что версия, опубликованная до этих полей, декодируется с ними выключенными и кодируется обратно в тот же документ (поэтому хеш содержимого сохраняется), что демо-политика не менялась, что пороги проходят туда и обратно и что значения вне диапазона или противоречивые отклоняются. `assessment_signal_test.go` покрывает два новых вида событий и отказ при наличии измерения. `assessment_work_lease_test.go` покрывает занятие: одна страница допускается, вторая получает отказ до освобождения или истечения, продление сохраняет время занятия, освобождает только владелец, неверные записи отклоняются. `usecase/assessment/work_session_test.go` прогоняет шаги занятия и проверку ответа и начала сеанса на репозиториях в памяти: вторая страница, страница без заголовка и запрос после истечения; учебный запуск и сервис без рабочих сеансов не получают отказов; источник занятия записывается только с отпечатком User-Agent. `signal_review_test.go` проверяет, что метка источника хранит User-Agent как ключевой отпечаток, пишет новую метку только при изменении, а проверка считает лишние агенты и подсказки о съемке и останавливается на attention. `keyring_test.go` проверяет, что новые отпечатки ключевые, привязаны к попытке и различны между собой. Тесты HTTP-адаптера проверяют отображение занятия, освобождения, отказа для занятой попытки при начале сеанса и ответе, новых вариантов событий и их несовпадений и ограничение User-Agent.
|
||||
|
||||
По HTTP с PostgreSQL. `TestAssessmentWorkSessionOverHTTP` создает реальную попытку и проверяет, что первая страница занимает сеанс, что вторая страница и запрос без заголовка получают 409 на занятие, начало сеанса и ответ, при этом ничего не сохраняется, что отказ не сохраняется под ключом (владелец использует оба ключа повторно), что освобождение чужой страницей ничего не меняет, что освобождение владельцем освобождает сеанс сразу, что занятие, переставшее продлеваться, заканчивается само, что неверные идентификаторы страницы дают 400, а отсутствие CSRF-токена - 403, что хранятся только отпечатки страницы и User-Agent (ни один текст таблицы не содержит идентификатор страницы или строку браузера), что события съемки хранятся без измерения и отклоняются с ним и что задание проверки дает полосу attention с учтенными лишними агентами и подсказками о съемке. `TestAssessmentSignalNoticeOverHTTP` следует за `CurrentSignalNoticeVersion`. Ограничения миграции 50 проверяются этими тестами.
|
||||
|
||||
Фронтенд. Vitest покрывает правила клавиш (`capture-keys.test.ts`), эвристику и ее наблюдателя с поддельными окнами и таймерами (`devtools-heuristic.test.ts`), сборщик (одно событие на нажатие и отпускание, без отмены, без события без задания), подключение наблюдателя к сеансу, контроллер рабочего сеанса (занято, свободно, потеряно при продлении, обрыв сети, освобождение во время продления, границы продления, `work-session.test.ts`), заголовок идентификатора страницы в команде ответа и текст версии 4 уведомления. `e2e/assessment-capture.spec.ts` работает с подставным API (и на сервере Vite, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-capture.spec.ts --project=chromium`): PrintScreen и Cmd+Shift+4 записываются как события `screenshot_key` без клавиши и изображения, событие клавиши не отменяется, и тест доходит до ответа; подставная пристыкованная панель записывается как `devtools_open`; вторая вкладка с той же попыткой получает отказ с объяснением и не показывает задание, в ней ничего не начинается, первая вкладка не нарушена, а после ухода первой вкладки вторая продолжает; `pagehide` освобождает сеанс; вкладка, потерявшая сеанс при продлении, останавливается и говорит об этом. Эти тесты не показывают поведение в других браузерах и на телефоне, отдает ли операционная система сочетание странице, как выглядит настоящий снимок и как часто эвристика ошибается на настоящих окнах; подставной сервер изображает правила настоящего, которые покрывает тест HTTP.
|
||||
|
||||
## Тесты поиска источника утечки
|
||||
|
||||
`backend/internal/usecase/assessment/leak_trace_test.go` запускает поиск на репозиториях в памяти с настоящими водяными знаками: утекший текст варианта среди других слов находит правильную из трех попыток, которым выдано одно условие (по невидимой метке); без невидимых символов видимый код из текста плитки находит попытку, а одни формулировки различают попытки, которым выдано одно условие и которые выбрали разные обороты; видимый код допускает один неверно прочитанный символ, но не два; посторонний текст, слишком короткий текст и метка несуществующей попытки не находятся и объясняют причину; условие, выданное одной попытке, находится по варианту и исключается, если ее формулировки противоречат тексту; попытки с одинаковыми оборотами или текст без групп оборотов дают ambiguous без названия попытки; метка, приклеенная к другому тексту, находится с пометкой; метка и видимый код, называющие разные попытки, дают ambiguous; другой вариант того же семейства не конкурирует с утекшим, а утечка удаленной попытки не приписывается оставшемуся варианту ее семейства; утечка, оборванная внутри условия, находится, а другие слова там, где условие продолжается, - нет; каждый поиск попадает в журнал с ключевым отпечатком и без какой-либо части текста, один и тот же текст дает один отпечаток, а неудача записи в журнал проваливает поиск; неверные запросы отклоняются без цитирования текста. `domain/assessment_watermark_test.go` покрывает выравнивание и согласование формулировок (читаются только обороты, выровненные с сохраненным условием, фрагмент, посторонний текст, другой вариант, выравнивающийся на меньшее число символов), `domain/assessment_leak_trace_test.go` - запись журнала, `usecase/identity/keyring_test.go` - ключевой отпечаток текста, `config/identity_test.go` - чтение секрета, а `adapter/primary/cli/leaktrace/command_test.go` - правила аргументов, чтение из файла и стандартного ввода с ограничением, вывод (исход и фиксированные примечания, никогда не текст, честный not found), безопасные сообщения об ошибках и то, что окружение не читается, пока аргументы неверны. `TestAssessmentLeakTraceOverHTTP` (PostgreSQL) создает по HTTP две реальные попытки и проверяет, что текст задания с меткой находит первую по метке, текст без невидимых символов находит вторую по условию, текст снимка с плиткой находит первую по видимому коду и времени плитки, посторонний и короткий текст не находятся, поиск не меняет ни версию и состояние попыток, ни проверки и результаты, каждый поиск попадает в журнал без текста, журнал отклоняет UPDATE, DELETE, TRUNCATE и найденную строку без попытки, журнал переживает удаленную попытку (которая после этого не находится), а команда с секретом сервера находит попытку, тогда как с другим секретом метку не читает. Они не запускают инструмент распознавания, поэтому здесь не измерено, как команда справляется с настоящими ошибками распознаванияLine truncated
|
||||
|
||||
## Тесты внутренних уведомлений
|
||||
|
||||
Модульные тесты (`make -C backend test`, `make -C frontend test`):
|
||||
|
||||
- `domain/notification_inbox_test.go`: запись принимает только разрешенные пары типа события и типа источника (синтетическое событие с организацией, `invitation.delivered` с приглашением), новая запись непрочитана, а `MarkRead` сохраняет первое время.
|
||||
- `usecase/notification/inbox_test.go` с памятью вместо репозитория и фальшивым unit of work: список вычисляет каждый элемент по текущему источнику и при отказе показывает его без содержимого; кабинет кандидата отказывает работодателю, кабинет организации отказывает кандидату, неизвестному или неподтвержденному аккаунту и отозванному членству (оно отвечает как неизвестная организация, и для списка, и для отметки); строка репозитория вне области получателя - внутренняя ошибка; владелец и рекрутер (и остальные роли) читают и отмечают только свои элементы организации, а членство блокируется на время чтения; работодатель с неподтвержденной почтой получает `ErrInboxEmailNotVerified`; отметка сохраняет первое время и не может задеть элемент другого получателя; ссылки содержимого отклоняют внешний URL, URL без схемы, query, fragment, обратную косую черту, escape, сегмент с точками и длинный путь; синтетический преобразователь следует положению получателя, а тип источника без преобразователя недоступен.
|
||||
- `usecase/notification/inbox_handler_test.go`: повторное событие дает одну строку; неверная версия схемы, агрегат, неизвестное поле, отсутствие организации, payload не объектом, лишние данные и ID события, повторенный с другими метаданными, отклоняются окончательно; удаленный получатель пропускается; сбой хранилища остается повторяемым; неподтвержденный адрес все равно получает строку (inbox не читает состояние почты); получатель, исчезнувший между проверкой и вставкой, повторяется и затем пропускается, а не отклоняется; синтетическое событие игнорируется при выключенном флаге; событие `invitation.delivered` с тем же контрактом payload сохраняет приглашение как источник.
|
||||
- `adapter/primary/http/v1/notifications_test.go` и `adapter/primary/http/notification_contract_test.go`: отображение содержимого и запасного варианта, курсор, привязанный к аккаунту и кабинету (чужой или перепутанный курсор дает 400), отказы, соглашения четырех операций и закрытые схемы. `bootstrap/consumers_test.go` фиксирует два зарегистрированных обработчика.
|
||||
- Frontend: `features/notifications/` проверяет проверку ссылки, один повтор отметки после 403 (и отсутствие повтора после 401, 404 и 500), подписи, формулировку элемента без содержимого, ключи запросов и их удаление по аккаунту и отрисованный список (состояние прочтения словом, кнопка отметки только у непрочитанных, нет небезопасной ссылки, пустое состояние, отказ для чужого кабинета).
|
||||
|
||||
Интеграционные тесты (`make -C backend test-int`; PostgreSQL и Redis, без Kafka): `TestNotificationInboxOverHTTP` пишет синтетическое событие через настоящий писатель outbox и доставляет его через хранилище обработчика с настоящим обработчиком. Одно событие, доставленное дважды и еще раз переименованным обработчиком, дает одну строку. Затем на том же роутере проверяются список кандидата, чужой кандидат, чужой кабинет, отсутствие CSRF-токена и чужой Origin, отметка и ее повтор (первое время сохраняется), сохранение состояния прочтения, потеря содержимого, когда кандидат скрывает организацию, страницы с курсором, привязанным к аккаунту, кабинет работодателя только с его элементами организации, рекрутер со своими элементами, не участник, элемент другой организации и 404 для списка и отметки после отзыва членства. `TestSyntheticNotificationMigrationAllowlistAndGuardedRollback` и `TestSyntheticNotificationMigrationRollsBackWithoutSyntheticRows` проверяют список разрешенных значений миграции 00036, отказ отката при синтетической строке и восстановленное ограничение. `TestNotificationInboxStoreNamesTheMissingReference` проверяет, что отсутствующий получатель и отсутствующая организация различаются. `TestPostgresMigrations` покрывает подъем и откат до нуля.
|
||||
|
||||
Браузерный тест: `frontend/e2e/notifications.spec.ts` запускается в `make -C deploy test-e2e-registration`, overlay которого задает `NOTIFICATION_SYNTHETIC_ENABLED=true`. `company-fixture` (тег сборки Go `e2e`, bearer-токен, только синтетические получатели `@example.test`) добавляет синтетическое событие в настоящий outbox, поэтому relay, Kafka и обработчик `notification_inbox` доставляют его; тест ждет появления элемента. Затем он повторяет событие через fixture, который обязан сообщить, что настоящий обработчик уже применил его, и проверяет, что в списке по-прежнему один элемент. Кандидат открывает список, отмечает элемент с клавиатуры, перезагружает страницу и видит сохраненное состояние, а второй кандидат получает пустой список и 404 на тот же ID. После скрытия организации элемент остается без содержимого. Второй тест читает inbox организации как владелец, проверяет не участника, отзывает членство через fixture и проверяет, что тот же ID отклоняется, а страница не показывает содержимое.
|
||||
|
||||
Чего эти тесты не показывают: событие настоящего приглашения через Kafka и relay (`TestOrganizationInvitationSendOverHTTP` доставляет его только через хранилище обработчика), поведение inbox при сбое почтового провайдера (по построению обработчик не читает состояние почты, а модульный тест покрывает неподтвержденный адрес), задержку доставки и нагрузку, push и живые обновления, а также вёрстку и работу страницы со скринридером (автоматической проверки нет).
|
||||
|
||||
## Тесты демонстрационного seed
|
||||
|
||||
`backend/internal/usecase/demoseed/seeder_test.go` без базы проверяет, что сброс разрешен только для базы без аккаунтов или только с синтетическими аккаунтами, что синтетические наборы проходят правила загрузчика и совпадают между сборками (поэтому повторный импорт ничего не меняет), что подготовленные ответы имеют задуманную правильность и что в наборе данных два работодателя на синтетическом домене, один кандидат для самостоятельного прохождения и когорта не меньше чем из пяти подготовленных кандидатов. `backend/internal/adapter/primary/cli/demoseed/command_test.go` проверяет разбор аргументов, отказ каждой подкоманды без `DEMO_MODE=isolated` до чтения настроек базы, отказ при коротком пароле без вывода его значения, то, что вывод seed называет логины и подготовленные попытки, но никогда не пароль, безопасные сообщения об ошибках и отказ `check-reset` при любом аккаунте вне синтетического домена.
|
||||
|
||||
`TestDemoSeedCommand` в `backend/integration_test/demo_seed_test.go` использует `bootstrap(t, postgresService)` и запускает операторскую команду против баз с миграциями и стартовой политикой:
|
||||
|
||||
- Без изолированного режима, в том числе против недоступной базы, каждая подкоманда отказывает и ничего не записывает.
|
||||
- База с обычным аккаунтом и без seed отклоняется и seed, и проверкой сброса; аккаунт и политика остаются прежними.
|
||||
- Первый seed создает девять подтвержденных синтетических аккаунтов, две организации, три членства (владелец «Альфы» - рекрутер «Беты»), шесть подготовленных попыток с результатами, текущими синтетическими категориями, доказательствами и опубликованными карточками, версию политики seed, 28 опубликованных семейств, одно открытие, одну аттестацию и одну учебную привязку. Повторный seed от другого оператора ничего не создает и печатает тот же перечень.
|
||||
- Каждый синтетический кандидат находится на шаге онбординга `candidate_assessment`, который оставляет сохраненная анкета, а оба работодателя - на `employer_company`. Стенд, на котором кандидаты остались на шаге согласий, исправляется еще одним запуском: он печатает строку `updated` для каждого кандидата на более раннем шаге, сохраняет кандидата на более позднем шаге, ничего не создает и оставляет перечень прежним.
|
||||
- Каждая организация, имя профиля и подготовленный профиль содержат пометку о синтетических данных или о подготовке, а каждая категория - неоткалиброванная категория `synthetic_demo`.
|
||||
- Владелец «Альфы» видит ровно шесть подготовленных карточек через тот же список карточек, что использует поиск, и не видит неопубликованного кандидата для самостоятельного прохождения.
|
||||
- Безошибочное экспресс-прохождение этого кандидата через операции попытки берет три задания из учебной категории, завершается результатом `demonstration` с русским текстом итога учебного запуска и не добавляет ни категории, ни доказательства; после этого тот же кандидат может начать полный тест.
|
||||
- После регистрации обычного аккаунта в заполненной базе проверка сброса отказывает и учитывает его, повторный seed по-прежнему ничего не создает, а аккаунт не меняется.
|
||||
|
||||
`make -C deploy check-demo` (часть `make -C deploy check`) запускает `deploy/scripts/demo.sh` с записывающей заглушкой docker CLI: каждое действие отказывает без `DEMO_MODE=isolated`, с именем проекта, равным `APP_PROJECT` или без `demo`, с неверным исполнителем или без env-файла, до любой команды Docker; том проекта без демонстрационной метки отклоняется до любой команды Compose; отказ проверки сброса останавливает сброс до `down`; сброс обращается только к демонстрационному проекту и заново заполняет его; `down` сохраняет тома; манифест выпуска, который нельзя восстановить, останавливает `seed` и `reset` до любой команды Compose, а `down` его не использует. При наличии docker CLI тест также рендерит overlay: опубликован только frontend и только на loopback; у контейнера seed только сеть default, корень только для чтения и явный профиль; у каждого тома есть демонстрационная метка; демонстрационный backend включает синтетические категории; release-overlay называет образ seed `lincodex.invalid/demo-seed:<tag>` с `pull_policy: never`; backend-образы команду не содержат.
|
||||
|
||||
Тесты не запускают Make-цели против настоящего стека. Ручная проверка на одноразовом проекте: дважды `make -C deploy demo-seed DEMO_MODE=isolated DEMO_PROJECT=lincodex-demo-check DEMO_HTTP_PORT=18090` с одинаковыми перечнями, вход подготовленными аккаунтами при выключенной почте, экспресс-прохождение и начало полного теста, затем отказ `demo-reset` после регистрации посетителя. После проверки удалите проект командой `docker compose -p lincodex-demo-check down --volumes` с теми же переменными. Тесты не проверяют содержание синтетического банка или какой-либо грейд, а браузерный маршрут жюри здесь не покрыт. Интеграционным тестам нужен Docker.
|
||||
|
||||
## Тесты исполнителя кода
|
||||
|
||||
| Команда | Что проверяет |
|
||||
| --- | --- |
|
||||
| make -C runner test | Unit-тесты с race detector: checker, конфигурация, исходы judge на сценарном sandbox, идемпотентность и занятость менеджера прогонов, HTTP API (токен, 202/200/422/503, 400, 413, 404) и отсутствие исходника, входа и токена в логах |
|
||||
| make -C runner lint | golangci-lint для Linux, включая тесты изоляции |
|
||||
| make -C runner check-generated | Сгенерированный ogen-сервер совпадает с bundle |
|
||||
| make -C runner test-sandbox | Эталонные решения и тесты изоляции в привилегированном dev-контейнере с настоящими nsjail и cgroup v2 |
|
||||
| make -C runner test-a16 | Только набор A16 с отчетом в `runner/.reports/`; `A16_ENV` передает переменные `RUNNER_*` |
|
||||
| make -C runner a16-bundle | Пакет набора A16 для запуска на хосте исполнителя |
|
||||
| make -C deploy check-runner-dev | Dev-переключатели не попадают в production-файлы |
|
||||
| make -C deploy check-runner-vm | Скрипт VM исполнителя сохраняет границу VM: VM только со своим профилем, без общих устройств, привилегированных и raw-настроек, sudo и dev-переключателей, настройки песочницы и бюджета в unit, статический адрес без маршрута и секреты вне репозитория |
|
||||
| make -C deploy runner-vm-check | На хосте приложения: работающая VM исполнителя, см. [DEPLOY.md](DEPLOY.md#шаги-скрипта-vm) |
|
||||
| make -C deploy runner-vm-a16 | На хосте приложения: набор A16 в VM исполнителя с настройками песочницы сервиса |
|
||||
|
||||
Сначала `test-sandbox` прогоняет эталонные решения `runner/testdata/judge/manifest.json` на трех задачах с одной публичной и тремя скрытыми группами: верные и неверные решения на Python и Go получают ожидаемый исход каждой группы (`exact` и `tokens`; `numbers` на дробных ответах с абсолютным и относительным допуском; `custom` с checker на Python и на Go в nsjail); Go-код с ошибкой компиляции дает `compile_error` с сообщением `main.go:` и ни одного запущенного теста. Тест также проверяет, что группа останавливается на первом проваленном тесте, у скрытых тестов нет диагностики, а каталоги и cgroup прогонов удалены.
|
||||
|
||||
Затем `test-sandbox` запускает набор A16 (см. ниже).
|
||||
|
||||
### Набор враждебных программ A16
|
||||
|
||||
`make -C runner test-a16` собирает образ и запускает только набор A16 в привилегированном dev-контейнере без сети и без init; отчет JSON записывается в `runner/.reports/` (игнорируется Git). Случаи и ожидания описаны в `runner/testdata/hostile/manifest.json`, программы есть на Python и на Go:
|
||||
|
||||
| Категория | Попытки | Ожидание |
|
||||
| --- | --- | --- |
|
||||
| network | TCP, UDP, listen, DNS, raw ICMP, AF_PACKET и netlink-сокеты | все отказаны, проба печатает `blocked` |
|
||||
| files_and_secrets | `/etc/passwd`, `/etc/shadow`, `/run/secrets` и токен API, файлы runner, `/proc`, `/sys`, `/dev/mem`, переменные окружения с `RUNNER`, `TOKEN` или `SECRET`, запись в корень, исходник и `/out` | ничего не видно и не записывается, кроме `/tmp` |
|
||||
| privileges | setuid, setgid, chown на root, повышение rlimit | отказ, uid и gid не 0 |
|
||||
| escape | ptrace, mount нового procfs, unshare user namespace | процесс убит seccomp (SIGSYS, `runtime_error`) |
|
||||
| processes | fork bomb, на Go также thread bomb (256 горутин, заблокированных в системных вызовах, поэтому стеки остаются намного ниже лимита памяти) | лимит процессов cgroup (`runtime_error`, limit `processes`) |
|
||||
| memory | бесконечное выделение памяти, на Go также бесконечные горутины, ожидающие на канале (без новых потоков) | лимит памяти cgroup (`memory_limit_exceeded`) |
|
||||
| disk | один большой файл и заполнение `/tmp` | отказ лимита размера файла и размера tmpfs |
|
||||
| output | бесконечный вывод | лимит вывода (`output_limit_exceeded`) |
|
||||
| timeout | занятый цикл с игнорированием сигналов, сон, отсоединенный демон в своей сессии | лимит CPU, лимит стены; демон погибает вместе с PID namespace |
|
||||
|
||||
Базовые случаи проверяют, что верное решение принимается, а синтаксическая ошибка дает `compile_error`. После каждого случая тест проверяет, что каталог прогонов пуст, cgroup прогонов удалены, живых процессов uid 99999 нет и не появилось незабранных (zombie); набор работает без init, поэтому это подтверждает, что nsjail забирает каждый остановленный процесс.
|
||||
|
||||
Отчет содержит версию runner (`git describe`), ядро (`uname`), контроллеры cgroup, версию пакета и SHA-256 nsjail, профиль изоляции (аргументы nsjail для тестового прогона, политику seccomp, лимиты cgroup и rlimit), результат каждого случая и вердикт. Любой проваленный случай дает вердикт `fail` и `practice_may_be_enabled: false`: практику нельзя включать, пока набор не прошел на хосте исполнителя.
|
||||
|
||||
Проверка самого набора: `TestA16WeakenedProcessLimitIsDetected` поднимает лимит процессов до 4096 в тестовой копии конфигурации и требует, чтобы случаи категории processes провалились. Тот же эффект вручную: `make -C runner test-a16 A16_ENV="RUNNER_SANDBOX_MAX_PROCESSES=4096"` завершается ошибкой и отчетом `fail` ровно по трем случаям processes.
|
||||
|
||||
На хосте исполнителя набор запускается из пакета: `make -C runner a16-bundle` (по умолчанию `A16_GOARCH=amd64`) собирает `runner/bin/a16-bundle.tar.gz` с тестовым бинарником, fixtures и `run-a16.sh`; на VM его распаковывают и запускают `sudo sh run-a16.sh [report.json]` с теми же переменными `RUNNER_*`, что и у сервиса. Скрипт не обращается к сети и пишет только отчет и рабочий каталог. На production VM то же делает `make -C deploy runner-vm-a16` во временном unit systemd с настройками песочницы сервиса; результаты 2026-10-11 (20 из 20 прогонов проходят с кодом выхода 0) приведены в [DEPLOY.md](DEPLOY.md#проверка-на-хосте-приложения).
|
||||
|
||||
Что тесты не доказывают: изоляцию в production VM, пока набор там не прошел; защиту от уязвимостей ядра, nsjail или cgroup; отсутствие побочных каналов (время, кеш процессора) и устойчивость под нагрузкой.
|
||||
|
||||
## Тесты практики с кодом
|
||||
|
||||
`TestAssessmentPracticeSubmissionStorage` в `backend/integration_test/assessment_practice_http_test.go` использует `bootstrap(t, postgresService, redisService)`, изолированную базу с миграциями, настоящий роутер, usecase практики и репозиторий PostgreSQL. Поток попытки пока не выдает элементы практики, поэтому тест сам переводит настоящую попытку в `practice_pending` и создает ее основную и дополнительную практики; синтетическая задача помечает текст каждого скрытого теста. Последовательные случаи:
|
||||
|
||||
- Отладочный прогон отвечает 202 с `Cache-Control: no-store` и сохраняется ровно с одним заданием в очереди, а повтор с тем же ключом и телом возвращает тот же прогон без новой строки; тот же ключ с другим телом получает 422. Другой кандидат, другая попытка и неизвестный прогон читаются как 404.
|
||||
- Отказы ничего не сохраняют: практика другого кандидата (404), дополнительная практика, пока попытка на основной (409), и код длиннее предела задачи (400).
|
||||
- Сохраненный результат, в котором есть и скрытая группа, показывается только с публичными тестами; в ответе только поля контракта и нет скрытого текста, исходного кода и текстов тестов.
|
||||
- Финальное решение переводит практику в `pending` и сохраняется с одним заданием; повтор возвращает его, то же решение под новым ключом ничего не сохраняет, другое решение дает конфликт, а ключ с другим телом отклоняется. База отказывает в замене исходного кода или языка сохраненного решения, в его удалении и во второй записи результата. После сбоя песочницы практика принимает другое решение, а первое остается неизменным.
|
||||
- С отключенным исполнителем прогон отклоняется как недоступный, и ничего не сохраняется. В конце у каждой сохраненной отправки ровно одно задание.
|
||||
|
||||
`backend/internal/usecase/practice/request_test.go` проверяет, что запрос к исполнителю для отладочного прогона содержит только публичные примеры и тесты кандидата, а для финального решения - ровно три скрытые группы.
|
||||
|
||||
`TestAssessmentPracticeQueue` в `backend/integration_test/assessment_practice_queue_test.go` использует ту же обвязку с ограничителем в Redis (два отладочных прогона в минуту), настоящие хранилище заданий PostgreSQL, исполнитель и обработчик, поддельного исполнителя кода, который идемпотентен по ключу прогона и считает запущенные прогоны, и тестовые часы для аренд и ожиданий. Последовательные случаи:
|
||||
|
||||
- Двенадцать кандидатов одновременно запускают отладочный прогон: одиннадцать принимаются, и ровно один получает 503 `service_unavailable` с `Retry-After` и ничего не сохраняет. Пока исполнитель держит прогон, задания - одно `running` и десять `queued`, а второй обработчик ничего не берет. После того как исполнитель закончил, все одиннадцать `finished`, каждая отправка выполнена один раз и сохранено одиннадцать результатов.
|
||||
- Пока в очереди одиннадцать прогонов, финальное решение получает практику в `failed` с `sandbox_busy`: отправка не сохраняется, версия попытки не меняется. Когда очередь освободилась, то же решение принимается и завершается.
|
||||
- Занятый исполнитель возвращает задание без учтенной попытки, и задание ждет его `Retry-After`; сбой инфраструктуры учитывает одну попытку, повышает поколение и оставляет практику в `pending` без результата; после паузы следующая попытка ее завершает.
|
||||
- Обработчик убит посреди задания (его пул закрыт, поэтому вернуть задание он не может): другой обработчик ничего не берет, пока аренда жива, забирает задание после ее истечения и завершает его с тем же ключом прогона: один прогон у исполнителя, одна учтенная попытка захвата и один результат; позднее завершение от убитого обработчика отклоняется и не меняет результат.
|
||||
- Второй отладочный прогон, пока первый не завершен, и третий в пределах минуты получают 429 `rate_limited` с `Retry-After` и ничего не сохраняют.
|
||||
|
||||
`TestAssessmentPracticeRunnerProtocol` в `backend/integration_test/assessment_practice_runner_test.go` использует ту же обвязку с настоящим обработчиком очереди и настоящим клиентом исполнителя кода по TLS 1.3 (`adapter/secondary/code_runner`) против локальной подделки протокола исполнителя (`practice_runner_fixture_test.go`: TLS-сервер `httptest` с bearer-токеном, PUT и GET на `/v1/runs/{id}`, одним прогоном на ID прогона и 422 для другого содержимого). Подделка не запускает код: она узнает одну программу на Python и одну на Go, которые печатают сумму двух целых, и сравнивает их вывод с ожидаемым выводом каждого теста; у проваленного публичного теста вывод программы лежит в диагностике. Боевая VM исполнителя не вызывается. Последовательные случаи:
|
||||
|
||||
- Отладочные прогоны на Python и на Go двух кандидатов завершаются через API. Собственный тест каждого кандидата ожидает неверную сумму, поэтому диагностика показывает, что напечатала программа: `got 42` у отправки на Python и `got 123` у отправки на Go, но не наоборот. Задание хранит `runner_run_id` прогона, и подделка запустила этот прогон из исходного кода именно этой отправки. Запрос на проводе содержит только поля `groups`, `language`, `limits` и `source`, группы `public` и `custom` и ни одной скрытой, заголовки только транспортные и сервисный токен, ID прогона версии 8, который не совпадает ни с ID пользователя, попытки, практики или отправки, и ни одного из этих ID, email и cookie сессии в пути, заголовках и теле. Другой кандидат читает прогон как 404.
|
||||
- Финальное решение, ответ на которое оборван после приема прогона исполнителем (соединение сброшено), повторяется после паузы с тем же ключом прогона: у исполнителя один прогон, задание `finished` с одной учтенной попыткой и поколением 0, сохранен ровно один финальный результат, и его `runner_run_id` - этот прогон. Запрос финального решения содержит только группы `hidden-1`...`hidden-3`.
|
||||
- Отладочный прогон, ответ на который идет дольше тайм-аута запроса, завершает попытку повтором, прогон читается как `queued`, а повтор присоединяется к прогону, который исполнитель уже держит.
|
||||
- Обработчик, умерший посреди прогона (его пул закрыт), заменяется после истечения аренды обработчиком с новым клиентом, собранным из тех же настроек. Новый клиент получает тот же ID прогона, поэтому у исполнителя по-прежнему один прогон, учтен один захват, сохранены один результат и один `runner_run_id`.
|
||||
- При остановленном исполнителе отладочный прогон остается `queued`, пока есть попытки, затем читается как `failed` с `sandbox_error`, без результата и `runner_run_id`, со временем завершения. Состояние и версия попытки, число результатов и подтвержденные категории кандидата до и после одинаковы, а практика остается `not_started`. Новый отладочный прогон той же практики принимается и завершается, когда исполнитель снова работает. Финальное решение при остановленном исполнителе переводит практику в `failed` с `sandbox_error` без результата, не меняет состояние кандидата и принимается снова и завершается рабочим исполнителем. В конце ни один `runner_run_id` не принадлежит двум заданиям.
|
||||
|
||||
Подделка доказывает путь по протоколу и правила хранения и повтора; она не доказывает, что настоящая песочница собирает и запускает Python и Go, и не доказывает время работы настоящего исполнителя.
|
||||
|
||||
Unit-тесты: `usecase/practice/execute_test.go` с подделками проверяет, что недоступный исполнитель сохраняет ключ прогона, сбой инфраструктуры и повторно использованный ключ повышают поколение, неверный запрос и последняя попытка завершаются без сохраненного результата, потерянный прогон отправляется снова, остановка возвращает задание без учета попытки, а завершенный прогон без верного ID повторяется и не сохраняет результат, тогда как верный ID сохраняется вместе с результатом. `config/practice_test.go` проверяет значения по умолчанию и отклоняемые значения настроек практики. Тесты не запускают код в песочнице и не доказывают время работы настоящего исполнителя.
|
||||
|
||||
## Тесты семантического подбора
|
||||
|
||||
- ML-сервис (`make -C ml test`, без модели и сети): `tests/test_embeddings.py` проверяет контракт `POST /v1/embeddings` на детерминированном хеш-кодировщике: порядок ответа, нормировку, одинаковые векторы двух одинаковых запросов, микропакеты по длине, 503 `service_unavailable` до готовности и ready только после прогрева, 400 на лишние тексты, длину и неизвестные поля, 413 на тело больше лимита (с Content-Length и потоком), отсутствие текстов запроса в логах; `tests/test_model_files.py` проверяет lock-файл (только safetensors и конфиги, полная ревизия, без кода и pickle) и сверку размера и SHA-256.
|
||||
- Ансамбль и токен ML (`make -C ml test`): `tests/test_ensemble_and_auth.py` проверяет выбор одной из нескольких загруженных моделей полем `model` и 400 для чужой, готовность только после всех моделей, отказ от двух кодировщиков с одним id, 503 и остывание readiness после нехватки видеопамяти с восстановлением, повтор загрузки при нехватке памяти и выход по `ML_EXIT_ON_LOAD_FAILURE` при другой ошибке, 401 без токена, с неверным токеном, со схемой Basic и на `/metrics`, открытые `/healthz` и `/readyz`, только loopback без токена, отказ до чтения тела, отсутствие токена в логах и ошибках настроек, отказ точки входа слушать не-loopback адрес без токена. На CUDA вручную проверено: загрузка при нехватке памяти повторяется, процесс жив и не готов; запрос сверх предела аллокатора получает 503, `/readyz` 30 секунд отвечает 503, затем сервис снова отвечает 200.
|
||||
- Реальные модели: `make -C ml model-fetch` и `make -C ml test-model` (маркер `slow`, обычные проверки его пропускают) сверяют векторы Giga-480M и Qwen3-Embedding-0.6B с векторами исследования для четырех текстов (разница меньше 1e-4) и повторное кодирование (тот же вектор); `ML_TEST_DEVICE=cuda` запускает их на GPU в float32. 2026-10-11 обе модели прошли и на CPU, и на CUDA на GPU-хосте. Это проверка воспроизводимости рецепта, а не оценка качества; сравнение точности float16 с float32 и расчет политики ансамбля - отдельная оценка на DEV исследования (см. [DEPLOY.md](DEPLOY.md#ml-сервис-на-gpu-хосте)).
|
||||
- Backend unit: представления потребности и карточки (`domain/semantic_test.go`: точный текст исследования, только подтвержденные значения, метаданные только у проверенного репозитория), кодек float32 и косинус, калибровка (интерполяция, ступени, монотонность демонстрационной таблицы), пороги, проверка и круговой проход документа политики V5; проекты и адрес GitHub (`domain/candidate_project_test.go`: допустимые и отклоненные адреса, нормализация, лимиты, повтор репозитория, отсутствие адреса в карточке); выбор объяснения (`usecase/matching/semantic_test.go`: порядок, лимит, устаревшее название, скрытые стек и проекты не объясняют, запись поля `projects`); Fit с известным и нейтральным Sem; клиент ML (пакеты по 32, проверка ответа, circuit breaker, отсутствие текста в ошибках); GitHub (`adapter/secondary/github`: httptest, только публичный репозиторий, токен только когда задан, ETag и 304, лимиты 403/429 с ожиданием, ошибки сервера, отказ от редиректа на другой origin, ограничения размера, текст README без разметки и HTML); задания и триггер (ключи и payload без адреса репозитория, отключенные функции ничего не ставят).
|
||||
- Интеграция (Testcontainers): `TestSemanticMatchingOverHTTP` проходит через HTTP, PostgreSQL и настоящий worker заданий с фиктивным ML-сервисом (httptest по контракту) и фиктивным GitHub: сохранение профиля ставит задания без адреса в ключах, проверка репозитория и векторы карточек, нейтральный Sem и флаг до векторов потребности, затем первым идет кандидат с близким проектом, объяснение называет проект и `repository_verified`, а в ответе и карточке нет адреса и владельца репозитория; одинаковые ответы двух поисков; история доступа с полем `projects`; повторный backfill с той же меткой ничего не ставит дважды и не вызывает ML для неизменных текстов; снятие поля `projects` удаляет векторы проектов и название из объяснения; недоступный ML оставляет задание в повторе, а поиск отвечает; лимит повторной проверки (429, затем 202).
|
||||
- Ансамбль и токен в backend: unit-тесты `domain/policy_matching_ensemble_test.go` (политика ансамбля проходит проверку, объясняет Giga с ее порогами, слитый балл в среднем равен 0, калибровка монотонна и обрезана, круговой проход документа V6), `usecase/policy` (публикация ансамбля поверх V5, повтор ничего не публикует, одиночная команда не трогает ансамбль), `cli/policypublish` (трек `semantic-ensemble`), `adapter/secondary/ml` (bearer-токен в каждом запросе, 401 как недоступность без текста токена, клиент без токена не создается), `config` (токен обязателен при включенном подборе, короткий и с пробелами отклоняются, форматирование настроек токены скрывает). В `TestSemanticMatchingOverHTTP` фиктивный ML требует токен и обслуживает обе модели; после публикации ансамбля и до backfill у всех записей нейтральное `Sem`, backfill добавляет векторы `whole` Qwen3 для шести карточек и потребности без повторного кодирования Giga и без векторов элементов Qwen3, после чего у всех записей `Sem` известен.
|
||||
- Не проверено: качество ранжирования и точность объяснений на реальных данных, задержка на рабочем сервере, сборка образа ML на этой машине и запуск стенда с моделью. Внешний GitHub в тестах не вызывается.
|
||||
|
||||
## Будущая программная валидация
|
||||
|
||||
Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером.
|
||||
|
||||
Общие тестовые данные должны быть изолированы по БД/схеме или сбрасываться последовательно. Не запускайте параллельные сценарии с общим truncate. Переиспользуйте окружение bootstrap внутри родительского теста; независимые тесты создают свои окружения. Integration job не должен молча пропускать тесты при отсутствии runtime.
|
||||
|
||||
Контракты проверяются через bundle, lint, codegen всех Go, TypeScript и Python потребителей и generated drift, включая новые untracked файлы. Frontend component tests не заменяют браузерный тест сквозного пути. После реализации продукта расширить набор Playwright сценариями двух ролей и явно синтетического кандидата без ФСП.
|
||||
|
||||
Критические будущие проверки:
|
||||
|
||||
- До принятия предложения контакты не видны другой компании ни через API, поиск, PDF, ошибки или ML объяснения.
|
||||
- Кандидат не получает доступ к чужим приглашениям, файлам, jobs или попыткам; компания не получает чужие потребности и подборки.
|
||||
- Отказ по тесту не понижает грейд; первый переход на более низкий уровень разрешен; cooldown не обходится параллельными запросами.
|
||||
- Повторная отправка результата и принятия идемпотентна; конкурентные status transitions сериализованы.
|
||||
- Выключенный ML сохраняет ручной путь; истекший worker lease восстанавливается; устаревший ответ не заменяет новый профиль.
|
||||
- Нет истории ФСП и ошибка интеграции различаются; отсутствие истории не исключает кандидата.
|
||||
- Уточнение поиска сохраняет прежний снимок; отозванный профиль исключается и из него.
|
||||
|
||||
## Будущая оценка качества
|
||||
|
||||
Подбор оценивается отдельно от функциональных тестов. Начальный план: 60-100 синтетических кандидатов, 8-12 запросов, два независимых разметчика, разбор разногласий и holdout по потребностям. Не помещать близкие копии одного профиля одновременно в настройку и holdout.
|
||||
|
||||
Сравнить keyword search, подтвержденные навыки и ML. Считать Precision@5, nDCG@5, нарушения жестких фильтров, покрытие категорий и долю релевантных результатов без ФСП истории. При выдаче короче пяти зафиксировать знаменатель до прогона и показать размер выборки. Синтетический набор не доказывает качество на реальном рынке.
|
||||
|
||||
Оценка тестов требует пилота на людях с независимой экспертной оценкой навыков. Сравнить эквивалентные формы, менять порядок, измерить agreement грейда, разброс баллов, решения по заданиям и разделение групп. Синтетические ответы годятся для отладки rubric, но не заменяют пилот.
|
||||
|
||||
ML оценка фиксирует набор документов и разметку полей, precision извлечения, выдуманные факты, полезность рекомендаций, schema-valid rate, latency и ошибки. Сохраняются модель, prompt/schema version, параметры и дата. Сравнить с простым baseline и правомерно использовать обезличенные документы.
|
||||
|
||||
Проектные ориентиры: 30 одновременных пользователей; p95 чтения профиля до 500 мс; baseline поиск до 1 секунды на демонстрационных данных без учета внешней сети. Это будущие критерии прогона, фактических результатов пока нет. ML получает отдельный latency budget.
|
||||
Старый результат не подтверждает новый коммит. Проверка health не доказывает бизнес-путь, синтетическая категория не доказывает валидность грейда, а подмена зависимости не доказывает ее реальную работу.
|
||||
Reference in new issue
Block a user