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
+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.
|
||||
Reference in new issue
Block a user