332 lines
72 KiB
Markdown
332 lines
72 KiB
Markdown
# Checks and quality evaluation
|
|
|
|
Routine checks prove individual code properties. They do not establish ranking accuracy, grade validity, production latency, or complete product readiness.
|
|
|
|
## Commands
|
|
|
|
Use the root Make targets:
|
|
|
|
make test
|
|
make check
|
|
make verify
|
|
make docs-check
|
|
|
|
make test runs backend, frontend, and ML tests. make check also runs API contract, formatting, lint, type, build, Compose, observability, and documentation checks. make verify sequentially generates contracts, checks generated drift, runs root check, API toolchain/backend race and integration checks, and then starts an isolated deployment smoke. It uses Docker.
|
|
|
|
Useful focused commands:
|
|
|
|
| Command | Coverage |
|
|
| --- | --- |
|
|
| make -C api check | Schema merge, bundles, OpenAPI lint, merge-script tests |
|
|
| make -C backend test | Go unit suite with race detector |
|
|
| make -C backend test-fast | Faster Go tests without race instrumentation |
|
|
| make -C backend test-int | Go integration tests with Testcontainers/PostgreSQL/Redis/SeaweedFS/Kafka |
|
|
| make -C frontend check | Prettier, ESLint, Stylelint, TypeScript, Vitest, FSD boundaries, build |
|
|
| make -C ml check | Ruff, mypy, pytest, and wheel build |
|
|
| make -C ml check-generated | Pydantic models match the ML bundle without rewriting files |
|
|
| make -C deploy config | Render Compose configurations without starting them |
|
|
| make -C deploy check | Render Compose configurations and run `check-workflows`, which fails when a workflow `aggregate` job does not need every other job or lacks `if: always()`, and `check-release`; see [Release manifest tests](#release-manifest-tests) |
|
|
| make -C deploy smoke | Isolated technical smoke of service health routes |
|
|
| make -C deploy test-e2e | Playwright browser suite against an isolated throwaway stack |
|
|
| make -C observability check | Validate Prometheus, Loki, Alloy, and dashboard JSON |
|
|
|
|
make -C deploy test-e2e currently runs a technical browser suite, not a business-flow suite; see [Browser E2E suite](#browser-e2e-suite).
|
|
|
|
make -C ml check-generated uses datamodel-code-generator --check: a mismatch fails the check and leaves the models file unchanged. Prepare the bundle with make -C api bundle before checking; use make -C ml generate to update Python models. Generated models do not establish inference functionality or support for every OpenAPI 3.2 feature.
|
|
|
|
Security checks run separately: `make -C security check` scans source/dependencies/secrets, `make -C security test` validates local Semgrep fixtures, installer integrity, and govulncheck failure handling, and `make -C security images` builds and scans all three service images. Install tools with `make -C security install` first. Scanner failure is a failed check, not a clean result. See [SECURITY.md](SECURITY.md) for Git/Docker requirements, blocking findings, and CI reports.
|
|
|
|
## Current scaffold coverage
|
|
|
|
Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, the private file layer and SeaweedFS access controls (see [Private file storage tests](#private-file-storage-tests)), the Kafka test harness (keyed records with headers and per-partition order, refusal to create a missing topic on demand, and topic cleanup), the outbox relay (see [Outbox relay tests](#outbox-relay-tests)), the event consumer runtime (see [Event consumer tests](#event-consumer-tests)), mail deliveries (see [Mail delivery tests](#mail-delivery-tests)), metrics, the API client, ML schemas, and current endpoint availability. There are no registration, login, assessment, search, invitation, or file workflows, no product event producer in Kafka (the mail delivery consumer is exercised only by tests), and no real model inference to validate as product behavior.
|
|
|
|
API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub.
|
|
|
|
Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, rejection of anonymous SeaweedFS bucket access, isolation of SeaweedFS from the frontend (by name and by its storage network address), rejection of filer, master, and volume HTTP requests that do not come from inside the SeaweedFS container, and the backend startup log for `EMAIL_PROVIDER=disabled`. The backend relay connects to Kafka in the smoke stack, but the smoke does not check that it publishes. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It sends no mail and does not check mail delivery, contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application.
|
|
|
|
## Browser E2E suite
|
|
|
|
`make -C deploy test-e2e` runs the Playwright suite from `frontend/e2e/` in Chromium against the real frontend and backend images. It needs Docker and frontend dependencies installed with `make -C frontend install`; no browser is installed on the host. `deploy/scripts/e2e.sh` does the following:
|
|
|
|
- Reads the exact `@playwright/test` version from `frontend/package.json`, checks that the installed package matches it, and runs the suite in the official `mcr.microsoft.com/playwright:v<version>-noble` image with `frontend/` mounted read-only.
|
|
- Starts the core stack under a unique project `lincodex-e2e-<random>` with fresh volumes and a generated throwaway env file: random passwords, `EMAIL_PROVIDER=disabled`, no mail transport settings. Shell variables other than Docker client settings do not reach Compose. The run refuses to reuse an existing project, network, or volume.
|
|
- Publishes no host port. The browser container shares the frontend container's network namespace, so it opens `http://localhost:8080`, the same loopback origin as `APP_PUBLIC_URL`. The Playwright config refuses a base URL outside a loopback host.
|
|
- 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.
|
|
|
|
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.
|
|
|
|
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. Later business tests create their own synthetic users and records through the public API in the fresh stack of each run; they do not use shared fixtures or real data.
|
|
|
|
The suite does not cover candidate or employer workflows, sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, layout, or 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.
|
|
|
|
## 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 stop pinning Go 1.26.8, 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 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.
|
|
|
|
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` handler 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.v1`. A handler with a test renderer that stands for `notification.v2` 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.v1` 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. The suite does not send mail: the sending worker, retries, and the permission check are later tasks, quotas have their own [Mail quota tests](#mail-quota-tests), and there is no test of a verification or password reset delivery, which the identity flows will create.
|
|
|
|
## 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 suite does not call a transport: the worker that runs `PrepareSend`, `Send`, and `SettleSend` in sequence is TASK-016.
|
|
|
|
## 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.
|
|
|
|
## Integration test sharding
|
|
|
|
`make -C backend test-int` runs the full suite through `backend/scripts/run-integration-suite.py`. The runner discovers every top-level `Test*` in `./integration_test/...`, sorts by package and name, and distributes tests round-robin. Each test belongs to exactly one shard with all its subtests. Changing the test set may change the assignment; duration-based balancing is not implemented.
|
|
|
|
```sh
|
|
make -C backend test-int-list
|
|
TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 make -C backend test-int
|
|
TEST_SHARD_INDEX=2 TEST_SHARD_TOTAL=2 make -C backend test-int
|
|
```
|
|
|
|
Indexes start at 1. Set both variables together; invalid settings, an empty suite, excess shards, and discovery failures fail the command. `test-int-list` compiles test packages and lists selected tests without starting containers. `make -C backend test-scripts` verifies for every shard count that each test runs in exactly one shard, that a shard listing matches the tests the shard runs, parent-test selection, and runner failure propagation. It is included in `make -C backend check`.
|
|
|
|
CI uses a separate matrix of two integration jobs with `GOFLAGS=-race` and `fail-fast: false`. Every shard must pass before aggregate and deployment smoke succeed. Run `GOFLAGS='-race -shuffle=on' make -C backend test-int` locally to check races and order independence. Shards use their own containers; runners do not share a database or a broker, so a Kafka test passes in whichever shard it lands. CI takes `TEST_SHARD_TOTAL` from the matrix size (`strategy.job-total`), so adding a shard index to the matrix is enough when suite duration warrants more runners; an index above the total fails the job.
|
|
|
|
## Consent ledger tests
|
|
|
|
Unit tests (`make -C backend test`) cover the ledger rules without a database:
|
|
|
|
- `internal/domain/` (`consent_test.go`): only `c1` to `c5` are purposes and only C4 is organization scoped; a text version follows the contract pattern of 1 to 64 characters; a text hash must be 32 bytes and not all zero; a stored text whose body no longer matches its hash, a C4 text without the `{organization}` placeholder, and another text with it are refused; the rendered C4 text hashes differently per organization and from its template, and an empty, padded, or multi-line organization name is refused. `NewConsentGrant` refuses C4, an empty or malformed version, a missing hash, subject, or time, and a source that the purpose does not allow; `NewContactConsentGrant` requires the C4 text, the organization with a valid name, a field set, the invitation, and a positive terms version, and hashes the text as shown for that name. Grants and revocations print and log no subject, organization, name, or field. A field set is canonical in any input order and refuses empty, repeated, unknown, and more than four fields. `RestoreConsentRecord` refuses what the database refuses, and a record prints and logs only its ID, purpose, and state.
|
|
- `internal/adapter/secondary/postgres/` (`consents_test.go`): ledger constraint errors map to their sentinels by SQLSTATE and constraint name without the row detail, the restricting consent key in the cleanup maps to `ErrTransactionConflict`, invalid input fails before any statement, every generated row type converts to one record row, and the stored field set keeps the order the database accepts.
|
|
- `internal/usecase/consent/` (`service_test.go`, with an in-memory text repository, ledger, transactor, and a controllable clock): a grant of C1, C2, C3, and C5 records the current text version and hash, the source of its entry point (`GrantAtRegistration` fixes C1 and `registration`, `GrantInSettings` fixes `consent_settings`), and the time of the injected clock, never another time; a grant with an older, unknown, or scheduled version fails with `ErrStaleConsentText`, names the current version, and never reaches the ledger; granting version one, publishing version two, and repeating version one is stale and leaves one record; `CheckTextVersion` returns the current text, fails stale for an older, unknown, and scheduled version, refuses an unknown purpose and a malformed version, and never touches the ledger; C4 on the generic path fails with `ErrScopedConsentRequired` before any repository is read; a malformed or empty version, an unknown purpose, and a nil subject are refused; a repeat returns the existing record with `Created` false and its first time, and the ledger keeps one record; failures of the repositories (no published text, unknown subject) keep their sentinel and a missing text is not reported as stale; a subject who withheld C3 has the other purposes with their own records and no C3 record; `GrantContact` records the scope, the source `invitation_acceptance`, and the hash of the text as shown, returns the existing record for a repeat, reports an invitation of another subject as taken, and refuses a stale C4 version, a padded name, and missing fields, organization, invitation, subject, or terms version; `GrantInSettingsInNewTransaction` retries a transaction conflict after a wait, stops after three attempts, does not retry another error or a canceled context, and rolls back a stale grant; `NewService` panics on a nil transactor or clock.
|
|
- `internal/adapter/primary/http/` (`router_test.go`): `ListMyConsents` answers 501 after validation for a session and 400 with the query pointer for an unknown state, a limit over 100, and a malformed cursor; under `DenyAllSecurity` it answers 401 with or without a cookie and with a `subject_id` parameter; the DTOs carry no hash, subject, or contact field, the parameters are only the state and the page, and the contract example decodes and validates.
|
|
- `frontend/src/shared/api/consent-contract.test.ts`: the generated Zod schemas accept a C4 record with its scope and a revoked unscoped record, refuse an unknown purpose, state, or source, an empty or malformed version, an empty or oversized field set, an unknown contact kind, and a terms version below 1, require every nullable field, and drop a hash or subject; the operation takes only the state and page parameters.
|
|
|
|
`TestConsentLedger` in `backend/integration_test/consent_ledger_test.go` uses `bootstrap(t, postgresService)` with the migrated schema, publishes a second C1 text the way a migration would, and truncates the ledger between cases:
|
|
|
|
- The migration publishes one demo text per purpose with a matching hash; the current C1 text depends on the time; an unknown version and a version of another purpose are not found.
|
|
- Versions and purposes: C1 at registration, C2, and a newer C1 version give three rows; the older C1 row stays byte-for-byte the same and is listed as `superseded`, the current C1 is the newer one, a repeated grant of the older version returns the existing row without a new one, and revoking C2 leaves C1 unchanged.
|
|
- Revocation stamps once: a second revocation finds nothing and keeps the first time, the current C3 is gone, and a new grant is a new row next to the revoked one. Revoking C1 also closes its superseded row.
|
|
- C4: the generic grant and a scoped grant without organization and fields are refused by the domain; a grant stores the organization, the canonical fields, the invitation, and the terms version, with the hash of the shown text rather than the template; a repeat returns the same row; an invitation consent of another subject fails with `ErrConsentInvitationTaken`; revoking C4 for organization A leaves organization B, and a revoked invitation consent never comes back.
|
|
- Repository validation: an unknown subject, an empty or malformed version, an empty hash, an invented version, a version of another purpose, a hash of another text, and a grant before publication are refused and store nothing. Another subject neither sees nor revokes the owner's consent.
|
|
- Database constraints through raw SQL: an empty version, an empty or short hash, C4 without a scope or with an empty, repeated, or unknown field, C2 with a scope or from the registration, a revocation without a source, and a hash of another text are refused by name; an update of a granted row, a revocation that also moves the grant, a second revocation, an update or delete of a published text, and a delete of an account with consent history are refused.
|
|
- Read model: pages of three return exactly the owner's four records newest first and never the other subject's; the state filter returns the active and the revoked records.
|
|
- Business transaction: a C4 grant rolls back with a failing acceptance, a failing statement after the grant rolls back the whole transaction, and a committed acceptance is visible after the commit and to its own transaction before it.
|
|
- The unverified account cleanup deletes the stale account with its C1 row and keeps the verified account and its record.
|
|
- C4 snapshot: raw rows whose hash belongs to another organization name, to another name than the stored one, or to the template are refused (`consent_records_c4_text_hash`), C4 without a name and C1 with one are refused (`consent_records_c4_scope`); after a rename, two acceptances keep their own names, and each hash still proves the text shown with its snapshot.
|
|
- A revocation dated an hour before the grant is stamped at the grant time.
|
|
- Deleting a consent row of a confirmed account is refused (`consent_records_retained`); a row of an unconfirmed account can be deleted.
|
|
- Re-registration: `UpdateRegistration` and a new C1 grant in one transaction leave only the new C1; a stale re-registration and an attempt on a verified account change and delete nothing.
|
|
- Eight concurrent grants of one version on their own connections store one record, and all of them return it with exactly one `created`.
|
|
- Twenty rounds of a grant racing a revocation return no error other than `ErrTransactionConflict` and never leave more than one unrevoked record of the version.
|
|
- With only the consent row of a stale account locked, the cleanup on a session with a 200 ms lock timeout skips the account without waiting, and deletes it after the lock is gone.
|
|
|
|
`TestConsentGrants` in `backend/integration_test/consent_usecase_test.go` runs the usecase on the bootstrap database with a fixed application clock, a second C1 text, and a C5 text scheduled after the clock:
|
|
|
|
- Registration: `UserRepository.Create` and `GrantAtRegistration` of C1 run in one `Transactor` transaction with no session (the sessions table stays empty) and commit one account and one C1 at the application time with the current text version. C2 and C5 follow as separate operations, each with its own active record; C3 is withheld and has no record while the others stand; a C3 granted later and revoked leaves C1, C2, and C5 active.
|
|
- Atomicity: a transaction that fails after the account and C1 were written leaves neither, and a grant for a subject without an account fails with `ErrUserNotFound` and stores nothing.
|
|
- Idempotency and versions: a repeat in its own transaction and in a business transaction returns the first record and its time and stores no row, and a repeat does not abort the transaction. An outdated C1 version, a scheduled C5 version, and an unknown C3 version fail with a stale error that names the current version and store nothing; the current C1 version goes through and the outdated one stays refused. A grant after a revocation is a new row. Eight concurrent repeats create exactly one row.
|
|
- Republication: after C3 version one is granted and version two is published, a repeat of version one is stale, names version two, and leaves one row and the first record as the current C3.
|
|
- Re-registration: `UpdateRegistration` followed by `GrantAtRegistration` in one transaction returns `created` true with a new record and leaves exactly one C1. The opposite order is shown as a hazard: the grant finds the earlier registrant's C1 and returns it with `created` false, the update then deletes it, and the account ends with no C1.
|
|
- C4: the generic path refuses it and stores nothing; `GrantContact` in a transaction stores the organization, the name, the fields, the invitation, and the source `invitation_acceptance`; a repeat returns the same record, an outdated C4 version is stale, and the C4 does not create a C2.
|
|
- Restart: after the pool is closed, a new pool, store, and usecase list the same four records in order with their states, the revocation stamp and source, and the original grant times, and a repeat grant through the new instance stores nothing.
|
|
|
|
`TestPostgresMigrations` rolls migration 00009 back with the others and checks that no table or function remains. The integration tests of identity, mail delivery, and mail quotas name `consent_records` in their TRUNCATE of `users`. The suite does not cover the revocation usecase, the HTTP handler, or the call of the consent usecase from registration and the invitation acceptance, and the cleanup race that ends in SQLSTATE 23001 is covered only by the unit test of its mapping, because its window cannot be reproduced deterministically.
|
|
|
|
## Organization tests
|
|
|
|
Unit tests (`make -C backend test`) cover the organization rules without a database:
|
|
|
|
- `internal/domain/` (`organization_test.go`, `membership_test.go`): a profile accepts a name only and a complete card; every rule names the field that breaks it by a JSON Pointer (`/name`, `/contacts/website`, `/representatives/1/name`) without quoting the value: an empty, padded, multi-line, over-long, or non-UTF-8 name, a description or sphere with a line break or control character, a website that is not `https` or has credentials, a port, an IP address, a numeric or hexadecimal host, or no dot, an email without a domain dot, a phone outside E.164, a Telegram username without `@`, and eleven representatives. CRLF in a description is stored as LF. `NewOrganization` starts at version 1 with a UUIDv7 and the level `e0` on `confirmed_email`, whatever the profile looks like; `ApplyProfile` keeps the identifier, the version, and the verification and never moves the update time backwards; a level pairs only with its own bases; `e0` to `e2` map to the quota tiers of the policy and `e3` has none; a stored row that was changed outside the application fails to restore. The card holds the profile and the level only. A representative is redacted in `fmt` and `slog` output, also inside an enclosing struct, and an organization logs only its identifier, version, and level. Only the owner manages the company, only an `active` membership gives access, the four roles and four states are the contract values, and `NewMembership` refuses a nil identifier, an unknown role, and a zero time.
|
|
- `internal/adapter/secondary/postgres/` (`organizations_test.go`): organization constraint errors map to their sentinels by SQLSTATE and constraint name without the failing row, which holds representative names; other errors keep only the SQLSTATE and the constraint; a deadlock maps to `ErrTransactionConflict`; invalid input fails before any statement; the manager roles passed to SQL come from the domain rule.
|
|
- `internal/adapter/primary/http/` (`organization_test.go`): under a session the operations answer 501 after validation and 400 with the pointer for each rule of the schema (a name over 200 characters or with a line break, a missing `expected_version`, contacts that omit a field, an http website or one with credentials, a phone outside E.164, a Telegram username without `@`, eleven representatives, a representative with a contact, null `name`, `contacts`, or `representatives`, a limit over 100, an identifier that is not a UUID); the representatives of the candidate card may be absent, null, or empty, and a card without contacts is refused. Each of eleven fields that would carry a right or a trust level (`role`, `owner_id`, `verification_level`, `verification`, `verification_basis`, `members`, `membership`, `candidate_card`, `id`, `version`, `created_at`) is refused alone on create and on update with the whole-body pointer. Under `DenyAllSecurity` all four operations answer 401, with or without a cookie and with a `user_id` parameter. The request DTOs have exactly the profile fields and no role, owner, member, or verification field, the card has no membership, role, basis, or time, the list takes only the page, an absent list differs from an empty one in `OrganizationUpdate`, every documented example decodes and validates, and the bundle has closed request objects, the CSRF scheme on both writes, the Idempotency-Key on create, 412 on update, and no operation that sets a level or a role.
|
|
- `frontend/src/shared/api/organization-contract.test.ts`: the generated Zod schemas accept a name only and a complete card for create and update, require `expected_version`, accept null only for `description` and `sphere`, refuse the same limits as the contract, drop a role or a verification level that a client adds, list the four levels, roles, and states, and, at the type level, give the requests no role, owner, member, verification, or identity field, the card no membership or basis, and the membership no account.
|
|
|
|
`TestOrganizationsAndMemberships` in `backend/integration_test/organizations_test.go` uses `bootstrap(t, postgresService)` with the migrated schema and truncates the organization tables with `users` between cases:
|
|
|
|
- Storage: an organization is stored with its owner and read back with its profile, representatives in order, version 1, the level `e0`, and the active owner membership; fields that are not set are NULL.
|
|
- Membership uniqueness: a repeated membership of the same account and organization, in each of the four roles and after the member left, fails with `ErrMembershipExists` naming `memberships_user_id_organization_id_key`, a raw insert fails with SQLSTATE 23505, and only one row remains; another account or organization is another pair.
|
|
- Atomic creation: an unknown owner account rolls back the organization, its representatives, and the membership; a later failure of the same transaction does too; an owner membership that is a recruiter, belongs to another organization, or is zero is refused before any write.
|
|
- Owner at commit: a transaction that inserts an organization alone, with a recruiter only, with a suspended owner only, or with an owner that it moves to `removed` before it commits fails at commit with SQLSTATE 23514 on `organizations_owner_required` and leaves nothing; an organization and an active owner inserted in one transaction commit.
|
|
- Scoped list: the organizations of one account include the ones where it is a recruiter and exclude those where its membership is suspended, left, or removed and every organization of another account; pages of two follow the same order with no gap or repeat; memberships created at the same instant order by the organization identifier; invalid queries, including a position without an organization identifier, are refused; an organization without representatives reads back with an empty list.
|
|
- Access: an account that is no member, an unknown account, an unknown organization, and a `suspended`, `removed`, or `left` member all get `ErrOrganizationNotFound`, a restored member reads again, and `Memberships().Get` returns the stored state in any state.
|
|
- Update: the owner replaces the profile, the representative list, and the contacts, the version advances to 2 and the update time changes, cleared fields become NULL, and a verification level that a process set to `e1` is still `e1` after the next profile update. A recruiter gets `ErrOrganizationManagerRequired`, a suspended owner, an outsider, and an unknown account get `ErrOrganizationNotFound` even with a stale version, a stale version gets `ErrOrganizationVersionConflict`, and none of them changes the stored organization.
|
|
- Revocation during an update: a transaction that revokes the second owner stays open, an update by that owner queues behind its membership lock (seen in `pg_stat_activity`), and when the revocation commits the update returns `ErrOrganizationNotFound` and writes nothing. Without `FOR SHARE` on the actor's membership the test fails.
|
|
- Concurrency: eight updates from the same version on their own connections give exactly one success and seven conflicts, and the stored name and representative belong to the same winner.
|
|
- Constraints through raw SQL: an empty, padded, multi-line, or over-long name, an unknown level, a basis of another level, version zero, a description with a padded end or a control character, a sphere with a line break, an http website or one with credentials, an email with a space, a phone without `+`, a Telegram username without `@`, an update before the creation time, the level and basis pairs of `e1`, `e2`, and `e3` (the right ones accepted, the wrong ones refused), a composite foreign key onto `(organization_id, id)` of the memberships (accepted for the member's own organization, refused for another), an unknown role (including `manager`), an unknown state (including `invited`), an eleventh representative, and a padded job title are refused by constraint name; the organizations table has no column for a role, an owner, a member, or a user.
|
|
- Deletion: an account with a membership and an organization with a member cannot be deleted (SQLSTATE 23001); once the memberships are gone, the organization takes its representatives with it.
|
|
|
|
`TestPostgresMigrations` rolls migration 00010 back with the others, checks that its three tables and its function disappear while the identity tables stay, and checks them again after the second migration. The tests that truncate `users` name `usersDependentTables` (identity, delivery, consent, and organization tables), the one list to extend when a migration adds a table that references users. The suite does not cover the usecases, the handlers, the session and CSRF mapping, or the claim that the contract is enforced end to end, because none of them exists yet; 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.
|
|
|
|
## 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.
|