1077 lines
301 KiB
Markdown
1077 lines
301 KiB
Markdown
# Lincodex architecture
|
|
|
|
This document separates the target product architecture from the technical scaffold in the repository. The requirements source is the [specification](../../requirements/specification.pdf). Page references in the coverage table use the printed pagination without the cover page. The [brandbook](../../requirements/brandbook/) is stored alongside the specification. The team supplied October 11 and October 30, 2026, as project milestones.
|
|
|
|
## Current scaffold
|
|
|
|
The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface scaffold with public pages and two cabinet shells of placeholder screens, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port.
|
|
|
|
Registration, email confirmation, login, and basic current-session operations work through the backend API. The frontend implements registration, confirmation, sign-in, and continuation from the server-provided scenario step; local browser E2E covers candidate and employer accounts. Consent settings and organization creation/editing work through the backend API. The internal notification inbox of both cabinets lists and marks synthetic notices, and no product module produces a real one yet (see [Internal notifications](#internal-notifications)). The organization side of the invitation draft (list, create, read, and update with versioned terms) works through the backend API; sending and the candidate side are not implemented (see [Invitation drafts](#invitation-drafts)). Other product workflows are not implemented: roles, profiles, assessments, grades, sending and answering invitations, resume processing, PDF generation, and FSP integration. The deterministic basic match search of the organization-visible bank works through the backend API without ML, competition data, snapshots, or invitations (see [Matching and explanations](#matching-and-explanations)). ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.
|
|
|
|
See [development](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTING.md) for source layout, commands, and current check coverage.
|
|
|
|
## Target system
|
|
|
|
The target is a modular Go backend with Clean Architecture, a React SPA using Vite and FSD, and a separate ML HTTP service in one repository. The planned Go process runs the HTTP API and background worker together. PostgreSQL stores product records and jobs; Redis provides the cache. Private S3-compatible SeaweedFS storage is selected for resumes and generated PDFs; the file workflows are not implemented yet. The initial target uses Docker Compose on one application host, with ML in a separate environment.
|
|
|
|
Go owns authorization, verified categories, invitations, contact grants, and final search results. ML proposes resume fields, helps interpret employer needs, and can take part in semantic search experiments. Model outages must leave manual profiles, assessments, filter-based search, and invitations available.
|
|
|
|
Combining API and worker simplifies the demo deployment, while sharing process lifecycle, memory limits, and metrics registry. The worker can move to its own process when independent scaling is needed without moving usecases or ports. That worker is planned.
|
|
|
|
The project brief assigns 35% of its score to matching, 25% to assessment and categorization, and 7% to technical implementation. The October 11 milestone calls for a working prototype flow. Technical work alone does not provide that flow.
|
|
|
|
## Contracts and code generation
|
|
|
|
The contract roots are split by boundary: api/core/ contains browser-to-Go operations, and api/ml/ contains internal Go-to-ML operations. The shared Makefile, package.json, and Redocly configuration stay under api/. Python schema tools live in the repository-level scripts/ directory. Each contract is assembled from small source YAML files.
|
|
|
|
The public Go handler is generated by ogen from backend/codegen/ogen.yml and mounted in chi. Orval independently generates the TypeScript client, TanStack Query hooks, Zod schemas, and MSW handlers. The ML Go client is configured at backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. datamodel-code-generator produces Pydantic v2 models from the same ML bundle in ml/src/lincodex_ml/api/models.py; the health/readiness handlers use these models. Python generator settings live in ml/codegen/pyproject.toml, while dependencies remain in ml/pyproject.toml. Backend sqlc configuration is backend/codegen/sqlc.yml and its generated SQL adapter is under backend/internal/adapter/secondary/postgres/sqlc/. Frontend configuration is frontend/codegen/orval.config.ts. There are three codegen directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Configuration belongs to the service that uses the generated code.
|
|
|
|
OpenAPI 3.2.0 is the target version. Verify the subset used here across bundling and lint, ogen, the chi adapter, the API runtime path, Orval, Python Pydantic models, and documentation. A parser version or one fixture does not prove support for every OpenAPI 3.2.0 feature.
|
|
|
|
The public API prefix /api/v1 is applied once. The internal /metrics endpoint remains separate. Health operations use names ending in z: healthz and readyz. Generated types and request validation do not implement ownership checks, company membership, consent, or valid product state transitions.
|
|
|
|
Generate bundles from contract sources, then regenerate each Go, TypeScript, and Python consumer through its Make target. A contract change includes generation and drift checks for every consumer. Never edit generated files by hand.
|
|
|
|
## Service and data boundaries
|
|
|
|
The planned backend boundaries are:
|
|
|
|
- Primary adapters receive HTTP requests and translate them into inbound ports.
|
|
- Usecases implement application flows and depend on domain rules and ports.
|
|
- Secondary adapters implement storage, ML, email, and file operations.
|
|
- Bootstrap wires implementations and controls process startup and shutdown.
|
|
- Product rules stay in domain and usecase code, away from chi handlers, workers, SQL, and ML.
|
|
|
|
Shared Go configuration belongs in backend/config/ outside internal. wahrwelt-kit logkit 0.6.0, httpkit 0.7.0, and cachekit 0.7.0 currently provide technical functions. Metrics use bounded custom collector/middleware code, and pgxpool collection must not block startup. pgkit and httpkit/metrics are not currently used. Technical libraries do not own product rules. Do not add unselected JWT or WebSocket dependencies for hypothetical features.
|
|
|
|
PostgreSQL with pgx, sqlc, and goose is the database stack. Developers own SQL; sqlc generates typed adapters. goose manages versioned migrations: the SQL files are embedded in the binary, and the backend applies them at startup under a PostgreSQL advisory lock before it opens its listeners. wire provides compile-time dependency construction in bootstrap, with no runtime DI container. API and worker share the database pool in the planned single-process deployment.
|
|
|
|
Redis is part of the core Compose project and connects through `backend/internal/adapter/secondary/redis/` to the outbound cache port. The adapter provides Get/Set/Del with TTL; bootstrap manages client construction and cleanup. The internal /readyz requires PostgreSQL, Redis, and the SeaweedFS bucket to be available. The cache is not a source of truth: future consumers must tolerate key eviction and Redis restarts. Profile, search, resume, and other product caching rules are not implemented yet.
|
|
|
|
SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. The shared file layer and the access controls of the SeaweedFS container are described in [Private file storage](#private-file-storage). Resume uploads, authorization, product content rules, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup.
|
|
|
|
The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. The [event consumer](#event-consumers) runtime applies events idempotently; two product consumers are registered, `notification_delivery` for mail deliveries and `notification_inbox` for the [internal notifications](#internal-notifications). Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help.
|
|
|
|
### HTTP perimeter and client address
|
|
|
|
Implemented. The frontend Nginx is the only public HTTP entry. It serves the SPA, proxies `/api/v1/` to Go, and proxies the restricted `/telemetry`; every other path, including `/metrics`, `/readyz`, and administration paths of other services, is refused with 404. Security headers, a strict same-origin CSP, a 1 MB default body limit that answers 413 in the contract's problem format, and coarse per-client `limit_req`/`limit_conn` (429 with `Retry-After`) are set there; the limits are far above normal use and do not replace the domain quotas, which stay in the backend. The details and the checks are in [DEPLOY.md](DEPLOY.md#public-perimeter-and-client-address).
|
|
|
|
The client address is derived only through trusted proxies. The edge replaces `X-Forwarded-For`; the app Nginx trusts the edge tunnel address and passes the backend one resolved entry; `middleware.ClientIP` (`backend/internal/adapter/primary/http/middleware/clientip.go`) trusts `X-Forwarded-For` only from `TRUSTED_PROXY_CIDRS` (by default only the pinned frontend container address) and reads it from the right, so an entry a client puts to the left of the first untrusted hop never counts. Usecases and handlers that need the address for a limiter read it with `middleware.ClientAddr(ctx)` and key the limiter with `middleware.LimiterKey` (IPv6 reduced to /64). The address is never logged or stored beyond the limiter window; the request log and metrics have no field for it. Registration, resend, and confirmation use client-address limits (see Registration, email verification, and resend); the router mounts `ClientIP`.
|
|
|
|
### Private file storage
|
|
|
|
`backend/internal/usecase/files/` is the shared private file layer over the `ObjectStorage` port. It holds technical rules only. A feature package (resume upload, import, PDF generation, document jobs, exports) defines a `Policy` with a namespace, a size limit in bytes, and exact media types, and owns every product rule: who may read or delete a file, page counts, content inspection, parsing, and retention. The layer is not wired into bootstrap until the first such feature uses it. Namespaces are declared in one place, `namespace.go`, and `NewPolicy` accepts no other value, so two features cannot share a namespace by accident.
|
|
|
|
- Keys have the form `<namespace>/<32 hex characters>` from 128 random bits. Only the validated policy namespace comes from code; file names and other client input never become part of a key. `Open` and `Delete` accept only keys of their policy's namespace and format, so a client-shaped key, a traversal path, or another feature's key is rejected before storage is called.
|
|
- Writes take the exact size. A declared size above the policy limit is rejected before any request. The stream passes through an `io.LimitReader` guard that withholds the last chunk until the source has ended, so a longer or shorter source aborts the request before storage receives a complete body. Any failure after the write started deletes the key, also after caller cancellation. Sources of unknown length are not buffered; a feature that needs them must spool to a bounded temporary file or add multipart upload. The source needs its own deadline, such as `http.ResponseController.SetReadDeadline` on a request body: `Put` waits for a blocked read, and canceling the context does not interrupt it.
|
|
- `Put` returns a `Record`: the key, the bare media type, the size, the SHA-256 digest computed while streaming, and the sanitized original name. The layer keeps no index and adds no tables. Callers follow one order: `Put`, then persist the record with their ownership data in a database transaction, then `Delete` the key if that transaction fails. One race remains: when the whole body was sent before the caller canceled, the server may commit after the cleanup `Delete` returned. Such orphans have no record and no request reaches them; a namespace sweeper that removes keys without a record is planned together with backups and exports and does not exist yet. The original name is display metadata only: it is not stored in SeaweedFS and is never used in keys or logs, but it may still contain personal data. Sanitizing removes path elements, control, format, separator, and private-use characters and does not normalize Unicode. The content type is declared by the caller; detection by content belongs to the document parser.
|
|
- `Open` checks that the stored object still fits the policy and closes the response on every rejection. The caller closes the returned `File`; reading fails when the body differs from the stored size. The adapter's `SEAWEEDFS_TIMEOUT` bounds connection setup, the TLS handshake, and the wait for response headers, not the body transfer of `Put` and `Get`, so the caller's context is the only bound on a long or slow stream. `Delete` is idempotent, and absence maps to `files.ErrNotFound`.
|
|
- There are no public URLs. The layer creates no public, permanent, or presigned URLs, and the bucket has no public policy or anonymous ACL. A browser download must go through an authenticated backend endpoint that checks current access and streams `File` with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`, so a stored file is never rendered as a page of the application origin. The key, bucket, and storage URL never reach clients.
|
|
|
|
SeaweedFS access. The primary control is the network: SeaweedFS joins only the internal `storage` Compose network, which the backend and the monitoring Prometheus (for the metrics on port 9327) also join. The frontend, PostgreSQL, Redis, Kafka, and other containers cannot resolve or reach it. This matters because `mini` serves much more than S3. The S3 gateway requires SigV4 credentials: the container's `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` create its only identity, `-s3.iam=false` removes only the IAM management API, and Compose refuses empty credentials because SeaweedFS without any identity accepts anonymous S3 requests. The other listeners do not use S3 credentials: the filer (8888), master (9333), and volume (9340) HTTP APIs; unauthenticated gRPC on 18888, 19333, 19340, and 18333 with server reflection; and an admin server on 23646 with worker gRPC on 33646 that `-admin.ui=false` does not stop and that `mini` cannot disable. Defense in depth inside the storage network: each start sets fresh random JWT signing keys for the filer and volume HTTP APIs, and `-ip=127.0.0.1` with `-whiteList=127.0.0.1,@` limits master and volume HTTP to callers inside the container. The upstream filer ignores its IP whitelist, so the JWT is its only HTTP control.
|
|
|
|
Remaining risk, limited to members of the storage network, which today means the backend (and Prometheus): they can reach the unauthenticated gRPC ports 19333, 18888, and 18333 and the admin ports 23646 and 33646. Master gRPC `Assign` returns a file ID with a signed volume write token, filer gRPC `ListEntries` returns object metadata, and entry changes through filer gRPC should be treated as possible. Volume gRPC 19340 refuses such callers. Integration tests verify that a volume write with a token from `Assign` is refused from outside the container (HTTP 401, whitelist) and that a volume read without a token is refused; this was not verified for the admin and worker ports. Low-priority disclosure inside the same network: the master UI and `/cluster/status` and the volume `/status` reveal topology and disk usage. A compromised backend already holds the S3 credentials, so these paths add little for it; any new member of the storage network widens the risk. gRPC mutual TLS would close the gRPC paths and is not configured.
|
|
|
|
### Transactional outbox
|
|
|
|
Implemented: migration `backend/db/migrations/00001_create_outbox_events.sql` creates `outbox_events`. Columns:
|
|
|
|
- `position`: a bigint identity, unique and monotonic in insertion order; the relay scans by it.
|
|
- `event_id`: uuid primary key, a UUIDv7 generated in Go.
|
|
- `event_type`: a lowercase dotted name of at most 128 bytes.
|
|
- `schema_version`: an integer above zero.
|
|
- `aggregate_type`: snake_case, at most 64 bytes.
|
|
- `aggregate_id`: a uuid.
|
|
- `aggregate_version`: a bigint above zero.
|
|
- `payload`: a jsonb object.
|
|
- `occurred_at`: `clock_timestamp()` at insert. It is informational only and does not define order.
|
|
- `published_at`: null until the relay publishes the row.
|
|
|
|
A unique key on aggregate type, aggregate ID, aggregate version, and event type rejects a second event of the same type for the same aggregate version. A partial index on `position` where `published_at` is null serves the relay scan. CHECK constraints repeat the domain rules for versions, names, and the object payload as a backstop. The payload size limit lives only in Go, because the jsonb text and binary sizes differ from the compact input and a database length check could reject an event the domain accepted.
|
|
|
|
A usecase writes through outbound ports. `Transactor.WithinTransaction(ctx, fn)` opens one READ COMMITTED transaction and passes a `UnitOfWork`; every repository it returns, including `Outbox().Append(ctx, events...)`, uses that transaction. The transaction commits when fn returns nil and rolls back when fn returns an error, panics, or its context is canceled. Calling `WithinTransaction` again with the callback context returns `outbound.ErrNestedTransaction` instead of opening a second connection. A conflict on the event ID or the unique key returns an error that wraps `outbound.ErrOutboxEventConflict` and names the constraint. A network error during commit leaves the outcome unknown, so callers that retry must be idempotent.
|
|
|
|
The outbox uniqueness rule is a backstop, not concurrency control. Aggregate updates still check the expected version (`UPDATE ... WHERE version = $n`), so a stale writer fails before it records an event.
|
|
|
|
`domain.NewDomainEvent` validates the event. The compact JSON payload is limited to 16 KiB and 32 nesting levels; numbers must fit a float64; NUL characters are rejected because jsonb cannot store them. jsonb normalizes the stored payload (key order, whitespace, duplicate keys), so consumers compare JSON values rather than bytes. Payloads carry identifiers and minimal facts only, never contact data, tokens, passwords, or resume and document contents.
|
|
|
|
The relay that publishes these rows is described in [Outbox relay](#outbox-relay). Idempotent consumers are described in [Event consumers](#event-consumers). Still planned: retry bookkeeping columns (attempt count and last error) and retention of published rows. Bootstrap does not wire the transactor yet because no product usecase uses it; the first business transaction wires it together with a shared pool.
|
|
|
|
### Outbox relay
|
|
|
|
Implemented: the relay loop in `backend/internal/worker/outboxrelay/`, the `outbound.OutboxRelayStore` and `outbound.EventPublisher` ports (`backend/internal/port/outbound/outbox_relay.go`), the PostgreSQL store (`adapter/secondary/postgres/outbox_relay.go`), and the franz-go producer (`adapter/secondary/kafka/`). Bootstrap starts the relay together with the HTTP servers in the same process and stops it on shutdown. The relay has its own PostgreSQL pool of at most two connections, one for the claim transaction and one for the backlog read, so it never takes connections from request handling. It does not run when `RELAY_ENABLED=false` or `DATABASE_URL` is unset; the outbox then keeps the events. Settings are listed in [DEPLOY.md](DEPLOY.md#outbox-relay).
|
|
|
|
One pass is one READ COMMITTED transaction:
|
|
|
|
1. `SetRelayTransactionTimeouts` sets `statement_timeout` to `RELAY_STATEMENT_TIMEOUT` and `idle_in_transaction_session_timeout` to `RELAY_PRODUCE_TIMEOUT + RELAY_STATEMENT_TIMEOUT` for this transaction only (`SET LOCAL` through `set_config`). The pass context already cancels a slow pass of a live process; these server-side limits also hold when the process freezes or loses the network without closing the connection, so the server ends the transaction and releases its row locks instead of waiting for TCP keepalive.
|
|
2. `LockPendingOutboxEvents` selects rows with `published_at IS NULL` in `position` order, at most `RELAY_BATCH_SIZE`, with `FOR UPDATE OF pending SKIP LOCKED`. A row qualifies only when it is the earliest unpublished event of its aggregate (lowest `aggregate_version`, then `position`). There is no `position` or `occurred_at` watermark; every pass scans the unpublished rows again.
|
|
3. The relay publishes the batch and waits for the broker acknowledgements, at most `RELAY_PRODUCE_TIMEOUT`.
|
|
4. `MarkOutboxEventsPublished` sets `published_at` for exactly the acknowledged event IDs, and the transaction commits.
|
|
|
|
Several relays, for example several backend instances, can run against one database. SKIP LOCKED lets them take different rows without waiting. Plain SKIP LOCKED would let a second relay skip a locked version 1 and publish version 2 first; the earliest-event rule prevents that, because version 2 does not qualify while version 1 is unpublished, whether another relay holds it, a failed pass left it pending, or a pass rolled back. The rule relies on aggregate writers checking the expected version: version 2 then commits only after version 1, so a statement that sees version 2 also sees version 1. Migration `00004_add_outbox_relay_index.sql` adds the partial index `(aggregate_type, aggregate_id, aggregate_version, position) WHERE published_at IS NULL` for this check. Trade-off: a pass publishes at most one event per aggregate, so a burst of N events of one aggregate needs N passes. A pass that found events starts the next one immediately, and different aggregates share a batch and spread across relays.
|
|
|
|
Selection cost. The plan is a nested-loop anti join: an index scan of `outbox_events_unpublished_idx` in `position` order, one probe of `outbox_events_unpublished_aggregate_idx` per scanned row, and LIMIT on top, with no sort over the backlog; the generic plan of the prepared statement is the same. A pass reads rows until it has found `RELAY_BATCH_SIZE` aggregate heads, so it reads every non-head row in front of them. Measured with `EXPLAIN ANALYZE` on PostgreSQL in a scratch container with 100,000 pending rows and a batch of 100: 0.2 ms and 100 rows read when versions of 1,000 aggregates interleave; 16 ms and 9,901 rows read when each aggregate's 100 versions are contiguous; 225 ms and about 50,000 rows read when one aggregate has 50,000 pending versions ahead of 1,000 other aggregates. In the last case the hot aggregate drains one version per pass and every pass reads its remaining versions again, so draining k pending versions of one aggregate costs O(k²) row reads. Product aggregates change a few times per business action, so k stays small; a large k appears only when a writer emits many versions of one aggregate during a long Kafka outage. Publishing several consecutive versions of an aggregate whose head a pass has locked would remove that cost and is a possible later change.
|
|
|
|
Kafka record:
|
|
|
|
- Topic: `KAFKA_EVENTS_TOPIC`, `lincodex.domain.events` by default. All events go to one topic; consumers filter by `event_type`. One topic is enough while consumers are few, and per-aggregate order needs only the key.
|
|
- Key: `<aggregate_type>:<aggregate_id>`. The default franz-go partitioner hashes the key, so all events of an aggregate land in one partition in publication order.
|
|
- Value: a compact JSON envelope with `envelope_version` (currently 1; changes only with the envelope fields), `event_id`, `event_type`, `schema_version` (the payload layout version of that event type), `aggregate_type`, `aggregate_id`, `aggregate_version`, `occurred_at` (RFC 3339 in UTC, informational), and `payload` (the stored jsonb object, so key order can differ from what the writer appended).
|
|
- Headers: `event_id`, `event_type`, `schema_version`, so a consumer can deduplicate and route without decoding the value.
|
|
|
|
The producer uses acks from all in-sync replicas and idempotent writes (the franz-go default). By default franz-go cannot fail an in-flight idempotent record until the broker answers, so behind a frozen broker the record and every later record of its partition would wait indefinitely. The relay enables `AllowIdempotentProduceCancellation`, which lets the delivery timeout and the pass deadline fail such a record, and `Publish` stops waiting at the deadline in any case. The client retries a record at most five times within one publish; later attempts belong to the next pass. Kafka does not create topics on demand: before its first pass the relay calls `Prepare`, which creates `KAFKA_EVENTS_TOPIC` through `kadm` with `KAFKA_EVENTS_TOPIC_PARTITIONS`, `KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR` (-1 by default, the broker's `default.replication.factor`), and, when set, `min.insync.replicas` from `KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS` (otherwise the broker default). It accepts an existing topic without changing it and logs one warning when that topic has another partition count or, with an explicit replication factor, another replication factor. A failed `Prepare` does not block startup: the relay retries it with backoff and events stay pending. When a publish reports an unknown topic, for example after the topic was deleted, the relay calls `Prepare` again before its next pass. With acks from all in-sync replicas, a write is durable only on `min.insync.replicas` brokers; the production requirement is in [DEPLOY.md](DEPLOY.md#outbox-relay). With `KAFKA_PROVISION_TOPICS=false` the topic is managed outside the backend. Adding partitions later moves keys to other partitions, so per-aggregate order is not guaranteed across that change.
|
|
|
|
Failure semantics:
|
|
|
|
- Kafka unavailable: the publish fails within `RELAY_PRODUCE_TIMEOUT`, nothing is marked, and the rows stay pending. The relay logs a warning with counts and the error (event IDs and broker errors, never payloads), waits a backoff, and retries indefinitely. The backoff starts at `RELAY_BACKOFF_INITIAL`, doubles with every consecutive failure up to `RELAY_BACKOFF_MAX`, and waits half the current value plus a random share of the other half. Business transactions write only to PostgreSQL, so an outage never rolls back a saved business action.
|
|
- Partial acknowledgement: only acknowledged events are marked; the rest are retried on later passes. Because a pass holds at most one event per aggregate, a failed event never lets a later version of its aggregate through. A pass that published at least one event resets the backoff and is followed by the next pass at once, so a failing event does not slow down the others; the backoff grows only across passes that published nothing.
|
|
- A failure after publish and before commit, including a crash or a lost database connection: the rows stay unpublished and a later pass publishes them again with the same `event_id`. A record whose publish timed out can also reach the broker later. Delivery is at least once: consumers must deduplicate by `event_id` and ignore an `aggregate_version` they already applied, because a late duplicate of an earlier version can follow a later version.
|
|
- Shutdown: when the process receives SIGTERM, the relay starts no new pass. A pass in progress has `SHUTDOWN_TIMEOUT` to finish and commit; after that it is canceled and its transaction rolls back. An unacknowledged event is never marked. Bootstrap closes the producer and the relay's pool only after the relay stopped.
|
|
- The transaction stays open during the publish, holding row locks on at most `RELAY_BATCH_SIZE` outbox rows and one connection for at most `RELAY_PRODUCE_TIMEOUT`. Business writes only insert new rows and are not blocked; the bound also limits how long the open transaction delays vacuum. A smaller batch or timeout shortens it.
|
|
- An event the broker rejects every time (a poison event; not expected, because the payload is at most 16 KiB and the topic is provisioned) blocks its own aggregate. While a pass still publishes other events, the relay keeps going at full speed. Because `ORDER BY position` returns the oldest heads first, every pass claims the poison heads again; when `RELAY_BATCH_SIZE` or more aggregate heads are poison, they fill the whole batch, no pass publishes anything, and the relay stalls at one pass per `RELAY_BACKOFF_MAX` while the backlog grows. An operator sees `failed` in `lincodex_outbox_relay_events_total` rising while `published` stays flat, `lincodex_outbox_relay_oldest_pending_age_seconds` growing, and warnings with the event IDs of the batch. The usual causes are on the Kafka side (the topic, its ACLs, or `min.insync.replicas` above the live replicas); after that is fixed, the next pass publishes everything. A raised `RELAY_BATCH_SIZE` lets other aggregates through meanwhile. There is no dead-letter path: an event that can never be published needs a decision by the owners of its consumers, and marking it published by hand skips it for every consumer.
|
|
|
|
The metric `lincodex_outbox_relay_events_total{outcome}` counts published and failed events; a pending event is counted as failed on every attempt. The gauges `lincodex_outbox_relay_pending_events` and `lincodex_outbox_relay_oldest_pending_age_seconds` show the unpublished events and the age of the earliest one by `position`, measured by the database clock. The relay reads them with `GetOutboxBacklog`, which uses the partial index, at most once every 15 seconds, also while it retries `Prepare`, so a busy relay does not count the outbox on every pass. Every backend instance reports the same database-wide values; aggregate them with `max`. `/readyz` does not check Kafka, so a Kafka outage does not take the API out of service.
|
|
|
|
### Event consumers
|
|
|
|
Implemented: the consumer runtime in `backend/internal/worker/eventconsumer/`, the handler port `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`), the franz-go consumer group member (`adapter/secondary/kafka/consumer.go`), the PostgreSQL store (`adapter/secondary/postgres/event_consumer.go`), and migration `00005_create_event_consumer_tables.sql` with the `consumer_processed_events` and `consumer_dead_letters` tables. Two product handlers are registered: `eventHandlers()` in `backend/internal/bootstrap/consumers.go` returns the mail delivery handler `notification_delivery` described in [Mail deliveries](#mail-deliveries) and the inbox handler `notification_inbox` described in [Internal notifications](#internal-notifications), so a backend with `CONSUMER_ENABLED` and `DATABASE_URL` runs one consumer in each of the groups `<CONSUMER_GROUP_PREFIX>.notification_delivery` and `<CONSUMER_GROUP_PREFIX>.notification_inbox`. The runtime integration tests use a test-only handler that writes into a table the test creates. A product module adds its handler to that list. Settings are listed in [DEPLOY.md](DEPLOY.md#event-consumers).
|
|
|
|
A handler implements three methods:
|
|
|
|
- `ConsumerName()`: a snake_case name of at most 64 characters. It names the Kafka consumer group `<CONSUMER_GROUP_PREFIX>.<name>` and scopes deduplication, so renaming a consumer makes it process every retained event again.
|
|
- `Handles(eventType)`: events of other types are counted as `ignored` and committed without a transaction.
|
|
- `Handle(ctx, unit, event)`: receives the decoded envelope and an `outbound.UnitOfWork` bound to the transaction that holds the dedup marker. The effect must use only that unit. An error that wraps `inbound.ErrEventRejected` is final; any other error is retried. Errors must not quote the payload or personal data, because their text is logged and stored with a dead letter.
|
|
|
|
Deduplication uses `event_id` only. Order by `aggregate_version` stays with the handler: a replayed dead letter can arrive after a later version of its aggregate, so a handler that keeps aggregate state ignores a version it has already passed.
|
|
|
|
One record is processed as follows:
|
|
|
|
1. The Kafka adapter decodes the envelope. It requires `envelope_version` 1, a non-nil `event_id`, the domain rules of `domain.NewDomainEvent` for type, schema version, aggregate type, ID, and version, a non-zero `occurred_at`, a JSON object `payload`, and an `event_id` header, when present, equal to the envelope field. A record that breaks a rule is an invalid record; the handler never sees it. The error names the broken rule and never quotes the value.
|
|
2. One READ COMMITTED transaction sets `statement_timeout` and `idle_in_transaction_session_timeout` to `CONSUMER_HANDLER_TIMEOUT` for this transaction only, runs `INSERT INTO consumer_processed_events (consumer_name, event_id) ... ON CONFLICT DO NOTHING`, and checks the row count. Zero rows means the event was applied before: the transaction rolls back and the record is a `duplicate`. One row means the handler runs in the same transaction, and the effect commits together with the marker.
|
|
3. The offset is committed only after that commit, or after the dead letter row is stored.
|
|
|
|
Why `ON CONFLICT DO NOTHING` in the same transaction as the effect. The marker is inserted before the effect, so the effect runs only while its transaction holds the uncommitted marker. A concurrent delivery of the same event, from another instance or after a rebalance, waits on that unique key until the first transaction ends: after a commit its insert affects zero rows and it skips the effect; after a rollback its insert succeeds and it applies the event itself. The effect therefore never runs twice or in parallel, and the outcome does not depend on timing. A plain `INSERT` that fails on the unique key waits the same way, but a duplicate then aborts the transaction with SQLSTATE 23505, puts an expected case into the PostgreSQL error log, and drives control flow by error. Checking with a `SELECT` before the insert leaves a race window under READ COMMITTED. The server-side timeouts end the transaction of a frozen process, so its marker cannot block a duplicate indefinitely.
|
|
|
|
Offsets and partitions. Each consumer is one member of its group with autocommit off and franz-go `BlockRebalanceOnPoll`. It polls at most `CONSUMER_MAX_POLL_RECORDS` records and processes them one at a time in poll order, which keeps the order within every partition. After the batch it commits, for each partition, the position after the last finished record (with its leader epoch), and only then allows a rebalance. Because rebalances wait for that point, a commit never lands on a partition the member no longer owns. A failed commit is logged; the position is retried with the next commit and when the partition is revoked, and dropped when the partition is lost, in which case the next owner receives the records again and the markers turn them into duplicates. A new group starts at the earliest retained record, so a new consumer never skips an event. The adapter refuses a commit whose finished records are not, per partition, the first records of the last poll without a gap, so a commit can never move past an unfinished record.
|
|
|
|
Rebalance budget. A batch holds rebalancing while it runs. If it takes longer than the rebalance timeout, the broker removes the member, its commit fails, and the new owner reprocesses from the last committed offset; deduplication makes that harmless, but the work is repeated. The timeout is set explicitly from `CONSUMER_REBALANCE_TIMEOUT` (60 seconds by default), and configuration refuses to start when the slowest record does not fit in it with a 5-second margin. The slowest record without a database outage is `CONSUMER_MAX_ATTEMPTS` handler attempts, the longest backoff before each retry, one dead letter write (each bounded by `CONSUMER_HANDLER_TIMEOUT`), and one offset commit (`CONSUMER_COMMIT_TIMEOUT`): 42.5 seconds with the defaults. A record is the unit because the consumer commits the finished prefix of a batch right after every record that needed a retry or a dead letter, so a member removed during the next slow record does not make its successor repeat the earlier ones. A database outage is not part of the budget: store failures are retried without a bound, and the removal they can cause only repeats work. The alternative, stopping a batch early when franz-go reports a blocked rebalance (`OnPartitionsCallbackBlocked`), would leave polled but unprocessed records behind on the partitions the member keeps; they would be skipped unless the fetch position were rewound with `SetOffsets`, which franz-go documents as prone to odd interactions inside a poll loop. The static budget is simpler and testable.
|
|
|
|
Failures, retries, and dead letters:
|
|
|
|
- Handler error: up to `CONSUMER_MAX_ATTEMPTS` attempts with the same backoff as the relay: the wait starts at `CONSUMER_BACKOFF_INITIAL`, doubles up to `CONSUMER_BACKOFF_MAX`, and is half the current value plus a random share of the other half. Each attempt is bounded by `CONSUMER_HANDLER_TIMEOUT` and rolls back its effect and marker. When the attempts run out, the record becomes a dead letter of class `retries_exhausted`. `inbound.ErrEventRejected` gives `handler_rejected` after one attempt. A handler panic is recovered, the transaction rolls back, the stack is logged without the panic value, and the record becomes `handler_panic`, so one event cannot crash the process on every delivery.
|
|
- Invalid record: a dead letter of class `invalid_record` with zero attempts.
|
|
- Refused commit: when the handler returns nil but PostgreSQL refuses the commit, the event is at fault, not the database. `pgx.ErrTxCommitRollback` (the handler ignored a failed statement, so the transaction was aborted) and SQLSTATE class 23 (a deferred integrity constraint) match `outbound.ErrEventEffectRejected`; class 40 (serialization failure or deadlock) matches `outbound.ErrTransactionConflict`. Both count as a handler attempt and are retried with backoff, so a deterministic refusal ends in `retries_exhausted` instead of a retry loop without end. Class 40 is transient by nature and usually succeeds on the next attempt; it still uses up an attempt so that a handler that deadlocks every time cannot retry forever. The same applies to a panic in `Handles`, which gives `handler_panic` without an attempt.
|
|
- Store failure (begin, marker, a commit lost in transport, or the dead letter write): it does not use up the handler's attempts, because the event is not at fault. The consumer retries with the same backoff until the database answers or shutdown begins, and never dead-letters a record because the database was down. The offset stays uncommitted meanwhile, so a database outage stops the partition without a hot loop and loses nothing.
|
|
- After the dead letter row exists, the offset is committed and the partition continues with the next record. A dead letter writes no marker, so a later replay of the event is applied.
|
|
|
|
`consumer_dead_letters` stores the consumer name, topic, partition, offset, `event_id` (from the envelope, or from the `event_id` header of an invalid record; NULL when neither is a UUID), `event_type` (NULL for an invalid record), the class, a reason of at most 256 printable characters, the attempt count, the value size, its SHA-256, and the time. A unique key on consumer, topic, partition, offset, and value digest keeps one row per record: when the same record fails again, after a crash before its offset commit or a rewind of the group, the row gets the new class, reason, attempt count, and time. The digest is part of the key because a topic that was deleted and created again reuses offsets; a different value at a reused position is another record and keeps its own row instead of being dropped. Handler errors reach the reason and the logs only after the store replaced the text of any PostgreSQL error in them with its SQLSTATE and constraint, because a PostgreSQL message can quote row values. The record value itself is not stored. A valid event is still in `outbox_events` under its `event_id`, which is also the replay source, so a second copy would only duplicate data that events may carry later and that a dead letter table would keep without a retention rule. An invalid record did not come from the relay; while the topic retains it, an operator can read it by topic, partition, and offset, and the SHA-256 confirms it is the same value. The replay procedure is in [DEPLOY.md](DEPLOY.md#dead-letters-and-replay).
|
|
|
|
Lifecycle. Startup runs the migrations, then wire builds the consumers: one PostgreSQL pool shared by all of them with one connection per consumer (a consumer holds one transaction at a time and writes a dead letter only after it ended) and one franz-go client per consumer. Nothing connects at that point, so an unavailable Kafka or database does not block startup. The application opens its listeners, starts the relay and every consumer next to the HTTP servers, and serves. On SIGTERM the HTTP servers, the relay, and the consumers stop at the same time; none depends on another. A consumer starts no new record and abandons any backoff wait at once. An attempt in progress has `CONSUMER_SHUTDOWN_GRACE` to commit; after that it is canceled and its transaction rolls back. Finished records are committed within `CONSUMER_COMMIT_TIMEOUT`; unfinished records are never committed, so the next member of the group processes them. Bootstrap waits for all workers before the cleanup, in which the members leave their groups in parallel, each within `CONSUMER_COMMIT_TIMEOUT` plus 2 seconds (the final revocation commits only finished positions), and then the pool closes. The whole shutdown budget is in [DEPLOY.md](DEPLOY.md#event-consumers).
|
|
|
|
Trade-offs: one consumer processes one record at a time on one connection. Parallel processing comes from more backend instances in the same group, up to the partition count of the topic (3 by default). Markers are kept indefinitely; their retention is planned and must outlast the replay horizon, because deleting a marker lets a replay of that event apply again. The retention task also adds the index on `processed_at` that it needs; until then every applied event would pay for an index that nothing reads.
|
|
|
|
The metric `lincodex_event_consumer_records_total{consumer,outcome}` counts finished records by `applied`, `duplicate`, `ignored`, or `dead_lettered`; `lincodex_event_consumer_failures_total{consumer,stage}` counts every failed operation, including the last handler attempt before a dead letter, by `handler`, `store`, `poll` (a failed poll of the event bus), or `commit` (a failed offset commit). The consumer label comes from the registered names in code, so the series are bounded. Every series of a consumer exists from its start at zero. Logs carry the consumer, group, topic, partition, offset, event ID, and event type, never the value or payload.
|
|
|
|
### Scheduled jobs
|
|
|
|
Implemented: durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. One product handler is registered in `jobHandlers()` (`backend/internal/bootstrap/jobs.go`): `assessment.signal_review`, which computes the [assessment review band](#assessment-signals-and-the-review-band). The tests also use a test-only kind. The first planned deadline kind is the invitation response deadline. Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs).
|
|
|
|
Scheduling. A usecase calls `unit.ScheduledJobs().Schedule(ctx, job)` in its business transaction, so the job exists exactly when the change that needs it committed, and `Cancel(ctx, kind, key)` stops a job that has not finished. A job has a kind (the handler name, a lowercase dotted name), a key that identifies the logical job within its kind (for example an aggregate ID), a due time from the application clock, an optional attempt limit, and a payload: a flat JSON object of identifiers of at most 2 KiB. Neither the key nor the payload may contain personal data; the handler reads everything else from the source tables when it runs. `(kind, key)` is unique and the first schedule wins: a repeat inserts nothing (`INSERT ... ON CONFLICT DO NOTHING`) and reports `false`, also after the job ran or was canceled. This is insert-or-ignore rather than an upsert on purpose: a repeated command cannot move a deadline that must not be reset, and a stale writer cannot revive a finished job. A new occurrence needs a new key, for example `<id>:<version>`.
|
|
|
|
States. `due_at` is the deadline the job stands for and never changes; `available_at` is when a worker may claim the job next, `due_at` at first and the retry time after a failed attempt. `pending` waits for `available_at`; `failed` waits for its retry after a failed attempt; `running` is claimed under a lease; `done`, `dead`, and `cancelled` are final. Finished rows are kept, so their key stays reserved; their retention is not implemented yet.
|
|
|
|
Claim and lease. The worker claims up to `JOBS_BATCH_SIZE` jobs in one statement: a CTE selects waiting jobs whose `available_at` passed and running jobs whose `lease_expires_at` passed, of the kinds that have a handler in this process, in `available_at` order, with `FOR UPDATE SKIP LOCKED`, and the same statement sets `status = running`, `lease_owner` (a random ID per worker instance), and `lease_expires_at = now + JOBS_LEASE_DURATION`, and counts the attempt. Two partial indexes serve the claim, one on waiting rows and one on running rows; the kind filter applies after the index, so when many waiting jobs belong to kinds that the claiming process has no handler for, an index on `(kind, available_at, id)` is the next step. `now` is passed from the injected application clock; the database clock never decides whether a job is due or a lease expired, so tests move a fake clock instead of waiting days. Jobs of a kind without a handler stay untouched, so an older instance during a rolling deployment leaves them to the instances that have the handler. Right before its handler transaction, each job is started: a separately committed, guarded `UPDATE` renews its lease from now and sets `started_at`, but only while the lease of the claim has not expired. The attempt is counted at the claim, so a job that crashes its process while its handler runs cannot loop forever: when the lease of a started attempt expires on the last allowed attempt, the claim marks the job `dead` with `lease_expired` instead of running it again. A claim whose attempt never started (the worker stopped or was busy before the job's turn) is not the job's fault: the next claim reuses that attempt without counting another one and records no error class.
|
|
|
|
Run and completion. Each job runs in its own READ COMMITTED transaction: it sets `statement_timeout` and `idle_in_transaction_session_timeout` to the lease duration, locks the job row with a guard on `status = running`, the lease owner, and the attempt number, calls the handler with an `outbound.UnitOfWork` of the same transaction, marks the job `done` with the same guard, and commits. The handler effect and the completion therefore commit together: for an effect that stays in PostgreSQL a job is applied exactly once even when workers race, restart, or a lease expires. While the handler runs the row is locked, so another worker's claim skips it even after the lease expired by the clock; when the guard fails because the job was canceled or reclaimed, the handler is not called and nothing commits (`lease_lost`). A handler may cancel its own job through the unit, for example an expiry that also cancels the deadline job it stands for: the completion then finds the job `cancelled` in its own transaction, treats it as finished, and commits the effect, and the job stays `cancelled`. Any other change of its own job by the handler rolls back and makes the job `dead` with `completion_conflict`, because it would repeat on every attempt. A handler whose effect leaves the database, such as a call to another service, can repeat after a crash between that call and the commit and must be idempotent itself. The handler context ends with the renewed lease. A handler decides by `job.DueAt`, the deadline the job stands for, which a retry keeps, not by when it happens to run.
|
|
|
|
Lock order. The handler holds the job row lock and may then lock product rows. A business transaction that cancels a job, such as accepting an invitation at its deadline, should call `Cancel` before it locks those product rows. `Cancel` waits for a handler transaction in progress: after its commit the job is done and `Cancel` reports `false`, so the caller sees the expiry; otherwise the job is canceled and the worker finds its lease gone. The opposite order can deadlock, which PostgreSQL resolves by aborting one side with `ErrTransactionConflict`; the job side counts a failed attempt and retries.
|
|
|
|
Failures. A failed attempt rolls back its effect; a second statement, guarded the same way, records it. A handler error, a lease timeout, a deadlock or serialization failure (`conflict`), or a commit that PostgreSQL refuses (`effect_rejected`, for a handler that ignored a failed statement or a deferred constraint) moves the job to `failed` with `available_at = now + backoff`, where the backoff is the shared `worker/retry` delay from `JOBS_BACKOFF_INITIAL`, doubling up to `JOBS_BACKOFF_MAX`, with jitter. `inbound.ErrJobRejected`, a handler panic, and `completion_conflict` are final, also when they happen during shutdown. After the last allowed attempt (the job's own limit or `JOBS_MAX_ATTEMPTS`) the job is `dead`: it is logged at error level and counted as `dead`, and it needs an operator. `last_error_class` stores only a bounded class; a sanitized reason appears only in the log. A database failure outside the handler is not the job's fault: the worker releases its unfinished jobs without counting the attempt and backs off before the next claim, so an outage causes no hot loop. When the failure record itself cannot be written, the job keeps its started lease; a later claim then counts it as `lease_expired`, which on the last attempt makes it dead.
|
|
|
|
Shutdown. When the context ends, the worker claims nothing more. A job in progress has `JOBS_SHUTDOWN_GRACE` to commit; after that it is canceled and its transaction rolls back, so an unfinished job is never marked done. The worker then releases it, and the claimed jobs of the batch it did not start, explicitly: back to `pending` or `failed`, without counting the attempt, guarded by owner and attempt so a job that another worker reclaimed or a caller canceled meanwhile is left alone. Release makes the jobs claimable at once by another instance instead of after up to one lease, which matters during a rolling deployment; if the release cannot reach the database, the lease expires and a later claim takes the jobs, so the release is only a shortcut and never needed for correctness. Bootstrap starts the worker next to the HTTP servers, the relay, and the consumers, and runs the cleanup that closes its pool only after it stopped.
|
|
|
|
Trade-offs: one worker runs one job at a time on a pool of two connections; more throughput comes from more backend instances. The jobs of one batch are claimed together but each renews its lease when it starts, so a slow job ahead costs the next ones only waiting time: a job whose claim lease expired before its turn is not started and is released with its attempt intact, or, when another worker already took it over, that worker runs it on the same attempt. Due times are honored with a delay of up to `JOBS_POLL_INTERVAL` plus the batch ahead of it. There is no separate `cmd/worker`: the worker is a goroutine of the backend process, and migrations run as before.
|
|
|
|
Metrics: `lincodex_scheduled_jobs_total{kind,outcome}` counts claimed jobs by `done`, `retry`, `dead`, `lease_lost`, or `released`; the kind label comes from the registered handlers, and every series exists at zero from the start. `lincodex_scheduled_jobs_due`, `lincodex_scheduled_jobs_oldest_due_age_seconds`, and `lincodex_scheduled_jobs_dead` describe all kinds at the last backlog read, at most every 15 seconds. Logs carry the job ID, kind, attempt, and error class, never the key or payload.
|
|
|
|
### Mail transport
|
|
|
|
Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. The only caller is the sending worker for service identity mail (see [Sending service mail](#sending-service-mail)); product notifications are stored as deliveries but not sent until product notification sending is implemented. Settings are described in [DEPLOY.md](DEPLOY.md#mail).
|
|
|
|
`Send(ctx, OutgoingMail)` makes exactly one attempt. `OutgoingMail` carries the recipient, subject, text and HTML bodies, and an idempotency key that stays the same for one logical delivery across retries (1 to 256 printable ASCII characters, the Resend limit, without personal data); the sender comes from `EMAIL_FROM`. With a nil error the result is one of:
|
|
|
|
- `accepted`: the provider accepted the request and returned `ProviderMessageID`. This is not delivery or reading.
|
|
- `rejected`: the provider did not take the message. Either it answered and refused, or the transport failed before the request was completely written (DNS, connect, or TLS), so no complete request reached the provider; the second case is always `temporary`, and a retry cannot duplicate the message. `Rejection` is `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted`, or `temporary`.
|
|
- `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`), for example a timeout, a connection lost after the request was written, or a provider error raised while handling it. It is not "not sent": a retry reuses the idempotency key and the same content. Resend keeps an idempotency key for 24 hours. The worker stops automatic retries at 23 hours, leaving a one-hour safety margin; after that an operator must decide whether to retry because the old key may no longer prevent a duplicate.
|
|
|
|
`rejected` and `unknown` may carry `RetryAfter`, the provider's wait hint or a wait the transport derived from documented provider rules, and `ProviderCode`, the provider's error name. A `quota_exhausted` rejection also names the exhausted window in `QuotaPeriod` (`day` or `month`) when the provider said which; it is empty otherwise. A transport sets `ProviderCode` only from its fixed list of documented names and leaves it empty otherwise, so it never carries provider text and is safe to log and store.
|
|
|
|
A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error when the caller's context ended before the request was written. A failure before the request was written while the context is still active is `rejected`/`temporary`, not an error. The transport makes one request; the worker owns retries, backoff, and outcome storage. The verification flows must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses.
|
|
|
|
The Resend transport uses `net/http` without an SDK. One `Send` is one `POST https://api.resend.com/emails` with `from` (`EMAIL_FROM`), `to` (one recipient), `subject`, `text`, and `html` (a blank part is omitted), an `Authorization: Bearer` key, a `User-Agent`, and `Idempotency-Key` set to the message's key. Resend keeps a key for 24 hours and answers the same key and body with the original result without sending again, so a retry must repeat the stored body under the same key; a changed body under an old key is a conflict, not a reason to make a new key. `EMAIL_TIMEOUT` bounds the whole attempt. The client follows no redirects, uses HTTP/1.1, and opens a fresh connection for every send: a kept-alive connection that the server closed while idle would fail after the request was handed to it and turn a message Resend never saw into a false `unknown`. The request also has no `GetBody`, because `net/http` treats a POST with `Idempotency-Key` as replayable on a broken reused connection. The adapter has no retry loop and does not log. An answer is read up to 64 KiB; only the message ID and the error `name` are parsed, and the provider's message and body are not kept.
|
|
|
|
| Resend answer | Result |
|
|
| --- | --- |
|
|
| 2xx with an `id` of up to 128 letters, digits, `-`, or `_` | `accepted` with `ProviderMessageID` |
|
|
| 2xx without a valid `id`, truncated, or over 64 KiB | `unknown`: the request may have been accepted |
|
|
| 3xx, not followed | `rejected`, `invalid_request`: the API documents no redirect, and a repeat gets the same one |
|
|
| 403 `validation_error` (unverified sender domain: without one Resend sends only testing emails to the account's own address) | `rejected`, `permanent` |
|
|
| Other 4xx: 400, 422, key and permission errors (401, 403), 404, 405 | `rejected`, `invalid_request` |
|
|
| 408; 409 `resource_locked` | `rejected`, `temporary`, `RetryAfter` from `Retry-After` |
|
|
| 409 `concurrent_idempotent_requests` | `unknown`: another request with the same key is in progress and may be accepted; retry later with the same key |
|
|
| 409 `invalid_idempotent_request` | `unknown`: the key was used with another body, so an earlier request may have been accepted; repeating cannot succeed, so the delivery layer stops and escalates |
|
|
| 409 without a known name | `unknown` |
|
|
| 429 `rate_limit_exceeded` or unnamed | `rejected`, `rate_limited`, `RetryAfter` from `Retry-After` (seconds or a future HTTP date), otherwise from `ratelimit-reset` |
|
|
| 429 `daily_quota_exceeded` | `rejected`, `quota_exhausted`, `QuotaPeriod` `day`, `RetryAfter` until the next 00:00 UTC |
|
|
| 429 `monthly_quota_exceeded` | `rejected`, `quota_exhausted`, `QuotaPeriod` `month`, no `RetryAfter`: the reset follows the billing cycle |
|
|
| 503 `service_unavailable` | `rejected`, `temporary`, `RetryAfter` from `Retry-After` |
|
|
| Other 5xx, including 500 `application_error` and `internal_server_error`, a truncated body, or a proxy or gateway answer | `unknown`: the API may have accepted the message before it failed |
|
|
| No answer after the request was written: timeout, reset, or closed connection | `unknown` |
|
|
| Failure before the request was written: DNS, connect, TLS, or the attempt timeout | `rejected`, `temporary`: no complete request reached Resend |
|
|
| The caller's context ended before the request was written | the context error; nothing was sent |
|
|
|
|
Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing and the attempt limit belong to the retry policy, the sending worker applies the minimum schedule described in [Sending service mail](#sending-service-mail), and automatic retries of uncertain sends stop at 23 hours, one hour before Resend's 24-hour key window ends. Waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas).
|
|
|
|
### Mail deliveries
|
|
|
|
Implemented: the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented; see [Mail quotas](#mail-quotas). Implemented: the service-mail worker, bounded retries, the unknown-outcome cutoff, and the audited local operator command, with migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql`; see [Sending service mail](#sending-service-mail). Sending product notifications with the permission check before a send is not implemented. The delivery state gauges are implemented; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). Product flows do not call `MailRequester` yet, so notification requests remain queued. Registration and resend create verification mail through `ServiceMailer`; password reset is not implemented.
|
|
|
|
A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds:
|
|
|
|
- `id`: the stable ID of the logical request, so a repeated request maps to the same row. The idempotency key sent to the provider with every attempt is `delivery/<id>` (`idempotency_key`, unique); it contains no personal data.
|
|
- `source_event_id`: the domain event the delivery was created from, or NULL for a delivery created directly in a business transaction.
|
|
- The recipient: `recipient_user_id`, a foreign key to `users` with `ON DELETE CASCADE`, and `recipient_email`, the delivery form of the account address when the delivery was created.
|
|
- The content: `kind` (`verification`, `password_reset`, or `notification`), `template_version` (`<kind>.v<N>`), `subject`, `text_body`, `html_body`, and `content_sha256` over the version, subject, and both parts, the same digest as the mail templates (`domain.MailContentHash`).
|
|
- The provider account: `provider` and `provider_account`, the values of `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation. They are configuration identity, never a credential.
|
|
- The attempt state: `status`, `attempt_count`, `next_attempt_at`, `last_attempt_at`, `provider_message_id`, the optimistic `version`, `created_at`, and `updated_at`, all from the application clock.
|
|
|
|
Creation path:
|
|
|
|
1. A usecase calls `MailRequester.RequestNotification(ctx, unit, request)` inside its own transaction with the recipient account ID and the notification data. The usecase checks the data with the current template, so a bad request fails its own transaction instead of becoming a dead letter, and assigns a UUIDv7 request ID. In the caller's transaction it inserts a `mail_requests` row with that ID, the recipient, the kind, the raw subject, body, and link path, and the request time, and appends `notification.mail_requested` with schema version 1: aggregate type `mail_request`, aggregate ID equal to the request ID, aggregate version 1, and the payload `{"mail_request_id": <id>, "kind": "notification"}` and nothing else.
|
|
2. The relay publishes the event, and the consumer `notification_delivery` applies it in the transaction of its dedup marker. It checks the envelope and that `mail_request_id` equals the aggregate ID, refuses trailing data after the payload object, and locks the request row (`FOR UPDATE`). It reads the account, renders the notification once with the current template version, inserts the delivery under the request ID with `source_event_id` set, and deletes the request row, all in that transaction.
|
|
3. A redelivered event is a `duplicate` of the consumer marker. A replay under another consumer name, a replayed dead letter after success, or a concurrent second consumer finds the request row gone (the second consumer waits on its lock) and skips. When an insert finds a delivery under the request ID already, the handler accepts it only for the same recipient and kind, and rejects the event otherwise.
|
|
4. Skips: a request that no longer exists, because it was handled or its account was deleted, and a notification to an account whose address is not verified (`email_verified_at` NULL). The unverified case deletes the request; notifications go only to confirmed addresses. Skips are logged at info level with the delivery and event IDs only. An unknown schema version, a payload that breaks the contract, or text that the template refuses is rejected for good and becomes a `handler_rejected` dead letter; storage errors are retried. An account deleted after the handler read it makes the insert fail on the foreign key; the transaction is aborted, so the error is retried, and the retry finds the request deleted with the account and skips.
|
|
|
|
Why the event carries only a reference. Events stay in `outbox_events` and in Kafka for the topic retention, and the domain event rule allows only identifiers and minimal facts. FR19 also requires that a queue does not keep revoked data available. The text therefore lives in `mail_requests`, which the account's deletion removes by cascade, and only as long as needed: the handler deletes the row in the transaction that stores the rendered delivery. After that the text exists only in the delivery, under the same retention and access rules. The address is read from the account in the handler transaction, so it is the address current at creation.
|
|
|
|
Token mail. Verification and password reset bodies carry a one-time bearer token, which must never enter an event or a request row, and storage keeps only its SHA-256. `mail_requests` and schema version 1 therefore allow only kind `notification`. Token mail deliveries are created by the identity flows directly in the transaction that issues the token, through `ServiceMailer`, which uses `domain.NewDelivery` and `DeliveryRepository.Create` and binds the delivery to the token. Registration and resend create verification mail; password reset is a future flow.
|
|
|
|
Immutable content. A delivery stores the rendered body and never renders it again. Rendering at send time would need the raw token, which exists only in memory when it is issued, and a retry under the same idempotency key must repeat exactly the same body: Resend treats a changed body under an old key as a conflict. The domain recomputes the content hash on every read and fails with `domain.ErrMailContentIntegrity` on a mismatch. The trigger `deliveries_refuse_content_change` refuses an UPDATE that changes the recipient, content, idempotency key, source event, or creation time (SQLSTATE 23000, constraint `deliveries_content_immutable`, mapped to `outbound.ErrDeliveryContentImmutable`). A new template version therefore applies to new deliveries only; old template files are not needed to send a stored delivery.
|
|
|
|
Personal data at rest. A delivery row holds the recipient address and the bodies, and a pending `mail_requests` row holds the raw notification text. The body of a token mail holds a live bearer token until it is used, replaced, or expires (at most 7 days by policy), so read access to `deliveries` is access to that account's confirmation or reset link, and database dumps and backups carry it. The consequences:
|
|
|
|
- Queries for operations select metadata columns (ID, kind, status, attempts, times, provider) and never the bodies, the request text, or the address; see [DEPLOY.md](DEPLOY.md#mail-deliveries).
|
|
- Deleting an account deletes its mail requests, deliveries, and their attempts by cascade. The unverified account cleanup locks them with `FOR UPDATE SKIP LOCKED` like tokens and sessions, so it never waits for the delivery consumer or a worker that holds a row.
|
|
- The bodies of a token mail are cleared when the delivery reaches `accepted`, `rejected`, or `cancelled` (`body_redacted_at`, see [Sending service mail](#sending-service-mail)), so a database dump or backup holds no token of a finished mail; a retention rule that deletes other terminal deliveries after a bounded period is not implemented yet, and until it exists those rows stay. Encryption of the bodies at rest is not implemented either.
|
|
- `Delivery`, `MailContent`, `MailRequest`, `NotificationText`, and `EmailAddress` redact themselves in `fmt` and `slog` output: a delivery logs its ID, kind, status, and provider. Handler errors name the broken rule and never quote the payload, and the adapter replaces PostgreSQL error text with its SQLSTATE and constraint. The delivery metrics carry only the kind, status, provider, and quota window labels, never the address, a user or delivery ID, the provider account label, or the subject.
|
|
|
|
Statuses. The values follow the `MailSender` outcomes:
|
|
|
|
| Status | Meaning | `next_attempt_at` |
|
|
| --- | --- | --- |
|
|
| `pending` | Waits for its first attempt, or for a retry after a `temporary` or `rate_limited` rejection | Required: when it is due |
|
|
| `accepted` | The provider accepted the message and returned `provider_message_id`: "accepted by the provider". Not delivery to or reading by a person; no status claims that | None; terminal |
|
|
| `rejected` | A `permanent` or `invalid_request` rejection; the cause must be fixed | None; terminal |
|
|
| `unknown` | The attempt may have reached the provider (`delivery_uncertain`). Never "not sent": an eligible automatic or operator-approved retry uses the pinned key and stored body | Optional; none means operator review is required |
|
|
| `cancelled` | The message was deliberately not sent and never will be: the token or the account no longer matches, or the stored message is unsendable. `cancel_reason` says why; no attempt is recorded | None; terminal |
|
|
| `waiting_quota` | A provider quota or the local quota is used up | Optional: the expected reset (see [Mail quotas](#mail-quotas)); none when the reset is unknown, for example after a provider quota answer that names neither a window nor a wait, and an operator decides |
|
|
|
|
Transitions:
|
|
|
|
- `Delivery.RecordAttempt` takes the result of one transport attempt and appends an attempt row. `pending`, `waiting_quota`, and `unknown` accept an attempt: `accepted` gives `accepted`, a `permanent` or `invalid_request` rejection gives `rejected`, `temporary` or `rate_limited` gives `pending`, `quota_exhausted` gives `waiting_quota`, and `unknown` gives `unknown`. `accepted`, `rejected`, and `cancelled` refuse any further attempt with `domain.ErrDeliveryTransition`.
|
|
- `Delivery.WaitForQuota(at, until)` parks a `pending` or `waiting_quota` delivery in `waiting_quota` without an attempt, for the case where the local mail quota defers a send before the transport is called; a zero `until` means the reset is unknown. It refuses `unknown`, whose earlier attempt may have been accepted and whose retry belongs to the retry policy, and the terminal statuses. `DeliveryRepository.WaitForQuota` stores it.
|
|
- `Delivery.Cancel(at, reason)` ends a `pending` or `waiting_quota` delivery in `cancelled` without an attempt; the reason is one of `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, or `processing_failed`. It refuses `unknown`, like `WaitForQuota`: an earlier attempt may have been accepted, so it is never reported as not sent. `DeliveryRepository.Cancel` stores it.
|
|
- `Delivery.Rebind(at, account)` moves a delivery that has no attempt yet to another provider account; see below. `DeliveryRepository.Rebind` stores it.
|
|
|
|
Every change advances `version`, and the store applies it only over the previous version. The next attempt time comes from the caller's retry policy and must fit the target status; the CHECK `deliveries_next_attempt_matches_status` repeats the rule, and `deliveries_provider_message_id_when_accepted` requires the provider ID exactly for `accepted`.
|
|
|
|
Attempts. The current state sits in counters on `deliveries`, so a worker reads one row, and every attempt is a row in `delivery_attempts`: number, time, outcome, rejection, provider code, provider message ID, wait hint, resulting status, and next attempt time. The first provider-call start is recorded by the database clock and is the age source for the automatic cutoff. Operator decisions are kept separately in `delivery_retry_decisions`, including the delivery ID, current attempt count, actor handle, explicit duplicate-risk acknowledgement, whether an expired lease was recovered, and decision time. It has no foreign key, so deleting the account does not erase the audit; row-level UPDATE/DELETE and statement-level TRUNCATE are refused. The wait hint is stored exactly as the Go `time.Duration` in nanoseconds (`retry_after_ns`), so a round trip never changes it. `RecordAttempt` stores the delivery and the attempt in one statement: a data-modifying CTE updates the delivery only while its version is still the one before the attempt and appends the attempt only if that update matched. A second writer of the same attempt gets `outbound.ErrDeliveryVersionConflict` and writes nothing. A trigger refuses an UPDATE of an attempt.
|
|
|
|
Quota accounting is not derived from this history: the cascade from an account deletes its deliveries and attempts, so counting sends from `delivery_attempts` would lose sends of deleted accounts and let the provider quota be exceeded. The quota therefore has its own counter that does not cascade, keyed by provider, provider account, and UTC day or month; see [Mail quotas](#mail-quotas).
|
|
|
|
Provider account. Each delivery is pinned to the transport and account configured when it was created. Providers and accounts share no idempotency keys, so FR19 forbids moving an uncertain delivery to another one; a configuration change applies to new deliveries only, and the sending worker must use the pinned account. `EMAIL_ACCOUNT` names the account (`default` unless set); change it whenever `RESEND_API_KEY` moves to another Resend account. The account may change only while the delivery has no attempt, because before the first attempt no provider has seen the key: `Delivery.Rebind` refuses a delivery with an attempt or in a terminal status, and the trigger refuses a provider change after an attempt (constraint `deliveries_provider_pinned`, mapped to `outbound.ErrDeliveryProviderPinned`). The service mail worker uses it for deliveries created while `EMAIL_PROVIDER=disabled` once the stand enables a transport; whether it rebinds them automatically or on an operator's request is its decision.
|
|
|
|
Migration `00012_add_delivery_sending.sql` is additive; existing rows stay valid. It adds to `deliveries`: `email_token_id` (a nullable foreign key to `email_tokens.id` for token mail, immutable like the rest of the content, NULL for notifications), `cancel_reason` (set exactly when the status is `cancelled`, CHECK-limited to the reasons above), the lease columns `claim_owner` and `claimed_until` (both or neither; only a delivery the worker may still send holds one), `first_send_started_at` (when the first request started, by the database clock), `failure_count` (consecutive failures of the worker on the row), `body_redacted_at` (the bodies of a token mail were cleared), the status `cancelled` with its CHECKs, and two partial indexes: `deliveries_due_idx` on `(next_attempt_at, id)` whose predicate names the service kinds and the statuses that are picked up again, so notification rows never enter it and an idle poll does not scan them, and one on `email_token_id`. The trigger `deliveries_refuse_content_change` also allows exactly one change of the bodies: a terminal token mail may have both set to empty together with `body_redacted_at`, once. It adds the `password_reset` token purpose to `email_tokens`. The down migration turns cancelled deliveries into rejected ones and deletes reset tokens. Planned: a cancelled delivery for a revoked permission.
|
|
|
|
The store provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, `Cancel`, and `Rebind`, and for the sending worker `ClaimDue`, `ReleaseClaim`, and `ServiceMailState`. Migration `00017_retry_unknown_mail.sql` adds the manual-cycle markers, the append-only decision journal, and `unknown` to the due index predicate. It drops and recreates the partial due index, which takes a table lock while it rebuilds. Rolling this migration back drops the decision journal and its audit data; preserve an export first if rollback is required.
|
|
|
|
### Mail quotas
|
|
|
|
Implemented: quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). The sending worker calls the gate around `MailSender.Send` and `bootstrap/mail_sender.go` builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP; see [Sending service mail](#sending-service-mail). Planned: the API or identity flow that shows the status reader's result. Only service identity mail counts against the quota until product notification sending is implemented.
|
|
|
|
Limits. `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` limit the recipients sent through the configured provider account (`EMAIL_PROVIDER` and `EMAIL_ACCOUNT`) per UTC day, from 00:00 to 00:00 UTC, and per UTC calendar month. Every recipient counts, as Resend counts them; a delivery has one recipient. The defaults are the Resend Free limits checked on 2026-10-05, 100 and 3000; they apply to `resend` and to `disabled`, which sends nothing. `smtp` has no default and does not start without both values, because a relay's limits are not Resend's. Values range from 1 to 1000000000, and the daily limit must not exceed the monthly one. No value turns the quota off, so no provider runs without the gate. Limits are configuration, not domain constants, and are not stored: a changed limit applies from the next reservation, and a limit lowered below the current usage defers every new send until the window resets.
|
|
|
|
Tables. Neither table has a foreign key to users or deliveries: deleting an account deletes its deliveries and attempts by cascade, but the provider has already counted those messages, so the usage stays. Neither holds personal data; `delivery_id` is an opaque ID.
|
|
|
|
- `mail_quota_usage`: one row per provider, provider account, period kind (`day` or `month`), and period start (a UTC date; the first day for a month), with `used_recipients`, `provider_exhausted_at`, and `updated_at`. An account accrues about 400 rows a year.
|
|
- `mail_quota_reservations`: a journal with one row per admitted send: the delivery, the account, the day and month windows it was counted in, the recipients, `reserved_at`, `released_at` (set once), and the last `settled_outcome` (`accepted`, `unknown`, `rejected`, or `not_sent`) with `settled_at`. A row without an outcome is a send in flight, or one whose process stopped before settling. A partial index serves the lookup of a delivery's open reservations. There is no retention rule for either table yet; journal rows are needed only within the reuse window and for the audit of a month.
|
|
|
|
Lock order. Every write first creates and locks all the usage rows it will touch with one statement, sorted by `(period_kind, period_start)`, and only then updates them or the journal; later `UPDATE` statements find their rows locked already. The order therefore never depends on the query plan. An `UPDATE ... WHERE (day) OR (month)` alone locks rows in scan order, which with a bitmap or sequential scan is heap order, and deadlocked against a reservation that locked the day first; the integration test reproduces that interleaving and checks that it no longer deadlocks. A settlement that releases yesterday's windows and marks today's locks all three rows in the same sorted statement. The guarantee covers the quota rows only: a caller that also locks other rows in the same transaction, such as the delivery, keeps its own consistent order for them.
|
|
|
|
Reservation. `QuotaGate.PrepareSend(ctx, unit, delivery)` runs in the caller's transaction:
|
|
|
|
1. A delivery pinned to a provider account other than the configured one fails with `notification.ErrQuotaNotConfigured`: no limits are known for it, and an account without a quota is never "unlimited". An `accepted` or `rejected` delivery fails with `domain.ErrDeliveryTransition`.
|
|
2. A retry inside the provider's idempotency window reuses an open reservation of the same delivery (the earlier attempt was `unknown`, or its process stopped before settling) and proceeds without counting again: the provider answers a repeated key with the original result instead of sending twice. The window is a gate parameter: `resend.IdempotencyWindow`, 24 hours per the Resend API documentation, or zero for SMTP, which has no provider-side deduplication, so every SMTP retry counts again. After the window a retry counts again; whether it may run at all is the retry policy's decision.
|
|
3. Otherwise the repository locks the day and month rows, adds one recipient to both only when it fits both limits, and journals the reservation. If it does not fit, nothing changes and the result says which limit would be exceeded. The reservation is all-or-nothing across both windows.
|
|
4. When the send is admitted, the decision carries a permit and the delivery is unchanged. Otherwise the delivery waits for the reset of the full window: the next 00:00 UTC for the day, the first day of the next month for the month; when both are full, the month reset wins. A `pending` or `waiting_quota` delivery is stored as `waiting_quota` with `next_attempt_at` at that time through `Delivery.WaitForQuota`. The change time is the later of the clock and the delivery's last change, and the reset is not earlier than that, so an instance whose clock runs a few milliseconds behind the one that last wrote the delivery can still park it. An `unknown` delivery is returned unchanged with the reset time: its retry belongs to the retry policy, and parking it would hide that an earlier attempt may have been accepted.
|
|
|
|
The row locks last until the caller's transaction ends, so the worker must commit before it calls the transport; the cost is that sends of one account reserve one after another.
|
|
|
|
Settlement. `QuotaGate.SettleSend(ctx, unit, permit, result, sendErr)` runs in the transaction that stores the attempt or, after a `Send` error, the delivery's next state. It always journals the outcome, and:
|
|
|
|
- `accepted` and `unknown` keep the reservation. An unknown attempt may have been sent, and counting it errs on the safe side.
|
|
- A `Send` error, where nothing left the process, and every `rejected` outcome release a new reservation: the provider did not take the message, so it did not count it. Without the release, a provider outage would use up the daily quota with failed retries. The journal sets `released_at` only on an open row, so a repeated settlement, for example after a commit whose answer was lost, releases nothing a second time, independently of the delivery's version. A reused reservation is never released: the earlier attempt under it may have been sent. A reservation that is never settled, for example after a crash between the two transactions, stays counted, which only over-counts.
|
|
- `rejected` with `quota_exhausted` also refines the count from the provider's answer. The window comes from `SendResult.QuotaPeriod`, which the transport fills from the provider's own error name (Resend `daily_quota_exceeded` gives `day`, `monthly_quota_exceeded` gives `month`), not from the wait hint. The window is the one current at settlement, because the provider answered about it, even when the reservation was made before midnight. The day mark raises that day's usage to the daily limit and the delivery waits for the next 00:00 UTC; the month mark raises the month's usage to the monthly limit and the delivery waits for the next UTC month start. A daily refusal on the last day of a month marks only the day. Resend's monthly quota follows the account's billing cycle; if that cycle resets later than the calendar month, the retry at the month start is refused again and waits another month unless an operator decides otherwise. Without a named window nothing is marked: the delivery waits for the provider's hint, or, without one, for an operator. A marked row records `provider_exhausted_at`, and a release no longer lowers it, so the local count stays at the provider's answer until the window resets. Raising the limit reopens the window; that is the operator's decision. `SettleSend` returns the time to store as the attempt's `next_attempt_at`.
|
|
|
|
No purchase, plan switch, or transport change. The gate only defers. Nothing buys a plan, moves the account to a paid tier, or sends a waiting delivery through another transport, provider, or account; the delivery stays pinned (see [Mail deliveries](#mail-deliveries)). Switching `EMAIL_PROVIDER` is an operator decision, and the gate applies to the new transport too: it runs in the usecase before any transport is called, `smtp` needs stated limits, and deliveries pinned to the old account are refused instead of being sent without a limit. Counters are kept per provider and account label, so a new transport or a new `EMAIL_ACCOUNT` label starts with its own count. A transport that reaches the same provider account by another route, for example Resend's own SMTP endpoint, shares the provider's quota but not the local count, and so does a relabeled account: the provider's refusal then refines the count as above, the startup report warns about other labels with usage this month, and the operator should set the limits to what the account has left.
|
|
|
|
Startup report. After the startup migrations, unless `EMAIL_PROVIDER=disabled`, bootstrap logs `mail quota usage` with the provider, account, and the day and month usage and limits, and warns `other accounts of this mail provider have quota usage this month; renaming EMAIL_ACCOUNT without changing the provider account resets the local count` when other account labels of the same provider have usage this month. A failed read is a warning and never stops startup.
|
|
|
|
What the user sees. `notification.DeliveryStatusReader.LatestForUser(ctx, userID, kind)` returns the status of the newest delivery of a kind addressed to the account: the kind, the status, `WaitingUntil` for `waiting_quota` (the stored `next_attempt_at`), and the time of the last change. It returns no address, subject, body, provider, or delivery ID, and false when there is none. The query is scoped to deliveries addressed to the given account, so the caller must pass the authenticated account's own ID, never an ID from request input. No HTTP route calls it yet; the identity flows and a later API show it. A user interface maps the statuses as follows:
|
|
|
|
| Status | What the user is told |
|
|
| --- | --- |
|
|
| `waiting_quota` with `WaitingUntil` | Your email is waiting until `<WaitingUntil>` |
|
|
| `waiting_quota` without `WaitingUntil` | Your email is waiting; the time is not known yet |
|
|
| `pending`, `unknown` | Your email is being sent. `unknown` is not shown as a failure: the message may have been accepted |
|
|
| `accepted` | Your email was handed to the email provider, which accepted it. We cannot confirm that it reached your inbox |
|
|
| `rejected` | Your email could not be sent |
|
|
| `cancelled` | Your email was not sent because the link in it is no longer valid; request a new one |
|
|
|
|
Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quotas). The gate logs `mail quota is used up; the delivery waits for the reset` at info level and `the mail provider reported its quota used up; local sending stops until the reset` at warn level, with only the delivery ID, provider, period, and reset time. The quota gauges come from `MailQuotaUsageReader.Usage` for the configured account, with the labels provider and window only; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts).
|
|
|
|
### Sending service mail
|
|
|
|
Implemented: the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the retry schedule `RetryPolicy` (`send_retry.go`), bounded retries of unknown Resend outcomes, audited operator decisions through `DeliveryRetryOperator`, and the local command `backend/cmd/mail-retry/`. `Delivery.CheckServiceMail` and `Delivery.Cancel` hold the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop is in `backend/internal/worker/mailsender/`, and the inbound port is `inbound.MailPass` (`port/inbound/mail_sender.go`). The repository and migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql` store attempts, leases, retry cutoffs, and operator decisions. Registration queues a verification email, and `ConfirmEmail` consumes its link. Product notification sending and the password reset flow are not implemented.
|
|
|
|
Scope. The worker claims only the kinds `verification` and `password_reset`. A product notification is never claimed here, whatever its state. Service mail needs no consent record of any purpose: it is part of the account flow, so nothing reads the consent ledger, and C2 (publication of the candidate card) and the other product consents play no part. What stands between the account and the mail is the check below, not a consent.
|
|
|
|
Enqueue. `ServiceMailer.EnqueueVerification` and `EnqueuePasswordReset` run in the transaction that inserts the token, with the token record, the raw token, the recipient address, and the lifetime in hours. They check that the token purpose fits the message, render the message once with the current template version, and store a `pending` delivery bound to the token (`email_token_id`) under the token's ID as the delivery ID. A repeated call for the same token stores nothing new, and the stored body stays as it was.
|
|
|
|
Links. The token travels only in the URL fragment: `<APP_PUBLIC_URL>/verify-email#token=<token>` and `<APP_PUBLIC_URL>/reset-password#token=<token>`, built by `mailtemplate` (`tokenLink`). A browser never sends the fragment to a server, so the token stays out of the nginx access log, which records `$uri`, out of Referer headers, and out of the Go request log; it is not in the path and not in the query. The frontend reads and removes the fragment, waits for explicit confirmation, then sends the token and registration password in the API request. It also consumes a new link opened in the same tab and ignores results from an older in-flight request. The password reset route and API are not implemented. The renderer rejects a token in any other place, its golden files and tests fix the format, and the delivery tests check that the stored body holds the link with the fragment and no `?token=`. The body in `deliveries` holds the live token until the mail is sent or cancelled; see Personal data at rest.
|
|
|
|
One pass of `ServiceMailSender.ProcessNext` takes one delivery through three steps:
|
|
|
|
1. Claim transaction. `DeliveryRepository.ClaimDue` takes the most overdue due delivery with `FOR UPDATE SKIP LOCKED`: kind `verification` or `password_reset` (literals that match the predicate of `deliveries_due_idx`, so the poll reads only that small index), status `pending`, `waiting_quota`, or a scheduled `unknown`, `next_attempt_at` passed, pinned to the configured provider account, and held by no live lease. An initial uncertain result is scheduled only while the delivery is inside the automatic cutoff; terminal unknown rows and unknown rows without a due time wait for an operator. A single-use manual authorization also makes an unknown row due. It sets `claim_owner` and `claimed_until` (the lease) without changing the version or the update time, so several processes never take one delivery. The lease is measured by the database clock (`clock_timestamp()` plus the lease length, and live while `claimed_until` is later than `clock_timestamp()`), never by the clock of an application instance, so instances whose clocks differ cannot take over a live lease or hold a dead one; due times stay on the application clock that wrote them. In the same transaction the sender rebinds mail stored while `EMAIL_PROVIDER=disabled` to the configured account (allowed before the first attempt only, so no provider holds its key), runs the check below, and then `QuotaGate.PrepareSend`, which reserves the recipient or parks the delivery in `waiting_quota`. The transaction commits before the transport is called, so a slow provider never holds a row lock. A failure inside it (a deterministic one, such as a row that cannot be restored) rolls the lease back too, so the failure is then recorded for the row in a transaction of its own; see Failing rows.
|
|
2. Check right before the send, one short transaction: it locks the delivery row (only for the lease holder), reads the token and the account again with `ServiceMailState`, so a revocation after the claim committed is honored, and records `first_send_started_at` by the database clock. For an uncertain retry, it rechecks the age against the 23-hour cutoff here, after quota and lease waits, immediately before any network call. A manual authorization is consumed only when this send-start is recorded. A mail that is no longer valid is cancelled and its reservation given back. Then one call to `MailSender.Send` with the stored content and the stable idempotency key `delivery/<id>`. The transport never retries internally. The call is bounded by what is left of the lease after the claim and the settlement budget, and by the shutdown grace.
|
|
3. Settlement transaction. It locks the delivery row first (only while this worker still holds the lease), then `QuotaGate.SettleSend` and `DeliveryRepository.RecordClaimedAttempt` commit together, and the lease ends with the attempt. `RecordClaimedAttempt` applies only over the delivery's version and only for the lease owner, so a worker whose lease was taken over cannot record, and if two workers reach this step for one delivery only the first is kept; the other rolls back, including its quota settlement, and reports `lease_lost`. A database failure while storing the answer is repeated up to three times inside a settlement budget, because the answer exists only in memory until it is stored.
|
|
|
|
Time budget. The lease is `EMAIL_TIMEOUT` plus one minute. The claim and the check come first; the call gets what remains of the lease minus the settlement budget (20 seconds), so claim, call, and the whole settlement fit inside the lease. When shutdown has begun the settlement budget is the shorter of 5 seconds and `SHUTDOWN_TIMEOUT` minus the 3-second shutdown grace (at least 1 second), so the process stops within its shutdown timeout, which is 10 seconds by default (the Compose stop grace period is 30 seconds). A result that cannot be stored in time is covered by the takeover below.
|
|
|
|
Lock order. Every path locks the delivery row first and the quota rows second: the claim locks the row with `FOR UPDATE SKIP LOCKED`, and the check and the settlement start with `LockClaimed` (`SELECT ... FOR UPDATE` of the row of the lease holder), so no two paths can wait for each other in opposite directions.
|
|
|
|
Check before sending. In the claim transaction, `Delivery.CheckServiceMail` compares the delivery with a snapshot read in one statement (`ServiceMailState`: the token and the account, no lock, only the address comparison key). The first failure cancels the delivery with `cancelled` and that reason; nothing is reserved and nothing is sent:
|
|
|
|
| Order | Rule | Reason |
|
|
| --- | --- | --- |
|
|
| 1 | A token is bound and its row exists | `token_missing` |
|
|
| 2 | Its purpose is the one the mail kind carries (`email_verification` for verification, `password_reset` for reset) | `token_purpose_mismatch` |
|
|
| 3 | It belongs to the recipient account | `token_owner_mismatch` |
|
|
| 4 | It is not consumed | `token_consumed` |
|
|
| 5 | It is not revoked (`invalidated_at`, by a resend or a re-registration) | `token_revoked` |
|
|
| 6 | It has not expired | `token_expired` |
|
|
| 7 | The account still has the registration version the token was issued for, and a verification mail does not go to an address that is verified already | `account_not_current` |
|
|
| 8 | The address in the delivery is still the account's address | `recipient_mismatch` |
|
|
|
|
A claimed row whose content no longer matches its hash (only a manual edit can cause that) is cancelled by the claim itself with `content_invalid`, with the bodies cleared like any cancelled token mail, and logged at error level with the delivery ID. Any other failure to restore a row may be transient, so it is not cancelled for good: it is a failing row, below.
|
|
|
|
There is no deactivated flag on an account. "Current" is rule 7 and the token rules: a re-registration moves the version and revokes the token, and a deleted account takes its deliveries with it by cascade, so nothing is left to send. A reset mail has no verification-state rule: that the reset applies only to verified accounts is a product decision for the reset flow. The check is a snapshot: a token consumed or revoked after it, before the provider call, still lets the mail go. That is harmless, because the link is checked again when it is used.
|
|
|
|
What a provider answer becomes. The delivery state machine of `domain.Delivery` decides; the worker only fills the attempt:
|
|
|
|
| Result | Delivery | Next attempt | Quota |
|
|
| --- | --- | --- | --- |
|
|
| `accepted` | `accepted`, provider message ID stored | none | counted |
|
|
| `rejected` `permanent` or `invalid_request` | `rejected` | none | released |
|
|
| `rejected` `temporary` or `rate_limited` | `pending` | now plus `RetryPolicy`: 1 minute, doubling to at most 30 minutes, never shorter than the provider's `Retry-After` | released |
|
|
| `rejected` `quota_exhausted` | `waiting_quota` | the reset the gate returns (next 00:00 UTC for a day, the first of the next month for a month); none when the provider named no window | window marked full |
|
|
| `unknown` | `unknown` | minimum retry schedule until the 23-hour cutoff; after that, none until an operator decision | counted |
|
|
| `Send` error: no transport (`ErrMailChannelUnavailable`) or the context ended | unchanged, lease released | still due | released |
|
|
| `Send` error: invalid message (`ErrInvalidOutgoingMail`) | `cancelled`, `content_invalid` | none | released |
|
|
| `Send` error: anything else without an answer | not counted against the row; it moves back by `RetryPolicy` and the worker backs off | now plus `RetryPolicy` | released |
|
|
|
|
The retry schedule has no attempt limit on purpose: the token expires, and the check then cancels the delivery with `token_expired`. Each delay gets bounded jitter, up to a fifth over the schedule, from an injectable source (nil in tests, so times are exact), so deliveries refused together do not return together. Confirmed `temporary` and `rate_limited` refusals are retried with the same pinned account, key, and body; the `Retry-After` value is a lower bound. A confirmed refusal proves that request was not accepted, but it does not clear uncertainty from an earlier unknown attempt. Automatic retries of uncertain Resend outcomes use the same key and exact body only until 23 hours after the database-recorded first send, one hour before Resend's documented 24-hour key expiry. The last storage check repeats this cutoff immediately before the provider call. An unknown answer or a lost lease after send-start ends automatic retries and requires operator review. A pending manual decision permits a potential send; confirmed temporary or 429 refusals may continue under that decision, but an unknown result or lost lease after send-start requires another explicit decision. Recovery records a lost send as an unknown attempt before it schedules the new decision, and does not call the provider. A manual decision does not restart Resend's key window. The local `mail-retry` command uses the database credential as its operator boundary: `make -C backend mail-retry ARGS='inspect --delivery <uuid>'` shows metadata and the duplicate warning, while `make -C backend mail-retry ARGS='retry --delivery <uuid> --actor operator:<handle> --acknowledge-duplicate-risk'` prints the warning before atomically scheduling and auditing a single-use decision. It never calls a provider. The actor is an audit handle, not an authentication mechanism; there is no HTTP operator endpoint. Reusing an expired key may send a duplicate despite the acknowledgement. The alert `LincodexMailDeliveryUnknownOutcome` fires while an outcome needs review.
|
|
|
|
Automatic retry after a lost worker. If a worker stops after a provider call but before storing the answer, another worker may claim that attempt and repeat the request with the same key while the 23-hour cutoff has not passed. A lost result after a manual send-start is recorded as unknown and waits for another operator decision; recovery does not call the provider. Resend answers a repeated key and body with the original result, and the quota gate reuses the open reservation, so the message exists once and counts once. The provider keeps the key for 24 hours from the first request, so the age is counted from `first_send_started_at` (set by the database clock right before the first request), not from the latest lease: however many workers were lost in turn, and whatever the lease length, once that age reaches 23 hours (the window less a one-hour safety margin) the earlier request may be forgotten and repeating it could send twice, so the delivery is recorded as an `unknown` attempt without a next attempt instead. The same applies at once to a transport without provider-side deduplication (window zero, SMTP). A lease that never reached the first request leaves nothing in doubt.
|
|
|
|
Failing rows. A fault in one row must not hold the head of the queue. When the claim transaction fails after it took a row, its lease rolls back with it, so the same row would be claimed again at once and every delivery behind it would wait. Only a fault that the row itself causes is counted against it: a domain rule it breaks (`ErrInvalidDelivery`, `ErrDeliveryTransition`, invalid content or address), a row that cannot be restored for a reason other than a hash mismatch, or a data or integrity constraint refusal (SQLSTATE classes 22 and 23, `outbound.ErrRowFault`). Everything else says nothing about the row and is never counted: a context that ended, a timeout, a deadlock, a lost connection (SQLSTATE 08, 40, 53, 57, XX), an I/O error, a missing quota configuration. Such an error is returned to the worker, which backs off like for any global failure, and the lease expires or rolls back. For a counted fault the sender records the failure in a short transaction of its own (`RecordFailure`): `failure_count` is incremented, the lease ends, and the row is due again by `RetryPolicy` (outcome `row_failed`; the next pass takes the delivery behind it). The statement leaves a row alone that another worker holds under a live lease, so a claim that rolled back cannot disturb a row that someone else has just claimed. The count means consecutive failures: a successful claim and preparation (the check before the send) clears it, and so does a recorded attempt. A circuit breaker in the worker stops the counting when failures hit different rows pass after pass: three passes in a row that fail on three different rows are read as a global fault, the worker waits with a growing backoff (a `row_failed` pass never loops at once), and failures are moved back but not counted, and no row is cancelled, until a pass succeeds. After 3 consecutive counted failures the row is cancelled with the reason `processing_failed`, the existing terminal status that fits: it is visible to the operator and the alert below fires, and a new status was not needed. A database outage that also stops this record leaves the row under its lease, which expires.
|
|
|
|
`EMAIL_PROVIDER=disabled`. Bootstrap does not start the loop: `newMailSenderWorker` returns no worker and logs `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`, so `lincodex_mail_sender_running` stays 0 and `LincodexMailDeliveriesOverdue` stays silent. Stored mail waits, pinned to `disabled`; after the stand restarts with a transport the worker rebinds it and sends it, if the token and the account still pass the check. The local operator command is available only with the Resend transport selected. A worker that is run against the disabled transport anyway (tests) gets `ErrMailChannelUnavailable` from every send, records nothing, releases the lease and the reservation, and backs off (5 seconds doubling to 2 minutes) instead of claiming again at once, so it never spins.
|
|
|
|
Loop and shutdown. `worker/mailsender` repeats passes: a pass that handled a delivery is followed at once by the next, an idle pass waits 5 seconds, and a database failure, a missing transport, or an interrupted call waits with the growing backoff. When the context ends the worker claims nothing more, lets the send in progress continue for 5 seconds, stores its result, and returns; the gauge is 0 from then on. The loop is a goroutine of the backend process on its own pool of two connections, like the other workers; more throughput comes from more instances, and each handles one delivery at a time, which suits service mail under the Resend Free quota.
|
|
|
|
Token at rest. The body of a token mail holds the one-time token, and a reset token is an account takeover primitive for anyone who can read the database or a backup. When a token mail reaches `accepted`, `rejected`, or `cancelled` (by any path: an attempt, a cancellation, the broken-row cancellation, or `processing_failed`), the same statement sets `text_body` and `html_body` to empty and `body_redacted_at`; the subject, the content hash, and the template version stay. The trigger allows exactly that change once, for a terminal row, and refuses any other change of the bodies or of the mark; the CHECK `deliveries_body_present` accepts an empty body only with the mark; the domain restores such a row as redacted content (`RestoreRedactedMailContent`), which cannot be sent. `unknown` keeps its body while it waits for review or a retry, because the worker may need to resend the stored content. The local command does not display or edit the body. Notifications are not redacted. Rolling back migration 00012 puts a placeholder in cleared bodies.
|
|
|
|
Privacy. Logs name a delivery only by `delivery_id`, its kind, and closed values (the outcome and the cancel reason); no address, token, link, subject, or body appears in a log line, an error, or a metric label, and the metric has no labels at all. `ServiceMailSender` builds the outgoing message from the stored content and never logs it; `OutgoingMail` and `Delivery` redact themselves.
|
|
|
|
Test fixture only. `resendfixture` and `resend.NewLoopbackSender` are never used by production code: `backend/.golangci.yml` forbids importing the fixture and calling the constructor outside `_test.go` files (depguard and forbidigo), and `bootstrap` binds the real transport with `resend.NewSender`.
|
|
|
|
Tests. `integration_test/mail_sender_test.go` runs a local Resend fixture (`resendfixture`, an `httptest` server speaking the part of the API the transport uses, reached through `resend.NewLoopbackSender`, which accepts only a loopback endpoint) against PostgreSQL; see [TESTING.md](TESTING.md). It is a test fixture only; production binds the real Resend transport with its fixed endpoint.
|
|
|
|
Open points. Sending product notifications and the permission check they need are planned; until then notifications wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume.
|
|
|
|
### Internal notifications
|
|
|
|
Implemented: the inbox of delivered events with a read state, the consumer that fills it, and four operations that list and mark it. No product module produces a notification yet. Invitations, the first planned producer, are not implemented, so the only event that reaches the inbox today is a synthetic one and a real recipient sees an empty list.
|
|
|
|
Code: migrations `backend/db/migrations/00032_create_notification_inbox.sql` and `00036_allow_synthetic_notification_event.sql`, queries `backend/db/queries/notification_inbox.sql`, the model `backend/internal/domain/notification_inbox.go`, the port `port/outbound/notification_inbox.go` (`UnitOfWork.NotificationInbox()`), the adapter `adapter/secondary/postgres/notification_inbox.go`, the usecase files `usecase/notification/inbox.go`, `inbox_handler.go`, and `inbox_content.go`, the HTTP handler `adapter/primary/http/v1/notifications.go` with its cursor `notification_cursor.go`, the wiring in `bootstrap/notification.go` and `eventHandlers()`, and the frontend feature `frontend/src/features/notifications/` with the page `frontend/src/pages/notifications/`. The operations are in [api/README.en.md](../../api/README.en.md#notifications).
|
|
|
|
- The inbox is the delivery state inside the platform. A row means that the notification reached the recipient's cabinet, and `read_at` says that the recipient read it. Mail is another channel with its own state in `deliveries` ([Mail deliveries](#mail-deliveries)), and neither reads the other. The inbox handler never reads `deliveries`, `mail_requests`, or the verification state of an address, so an unverified address, `EMAIL_PROVIDER=disabled`, or a failed send never blocks a notification, and a sent email never counts as seen. When invitations arrive, the delivered state of an invitation is the existence of its inbox row.
|
|
- A row holds references, not text. `notification_inbox_events` has the key `(recipient_user_id, event_id)` and the columns `organization_id`, `event_type`, `schema_version`, `source_type`, `source_id`, `occurred_at`, and `read_at`. It stores no title, summary, name, contact, or score. Triggers keep the reference immutable (only the first `read_at` may be set) and refuse a direct delete; deleting the recipient's account removes the rows by cascade, and the organization foreign key is `RESTRICT`. A CHECK allows only the pairs of event type and source type that `domain.NotificationInboxSourceFor` allows, both at schema version 1: `invitation.delivered` with `invitation`, and the synthetic `notification.synthetic_delivered` with `organization`. Migration 00032 is deployed and unchanged; 00036 only widened the CHECK, and its rollback refuses while a synthetic row exists.
|
|
- Producer contract. A producer appends, in its own transaction, an event of an allowlisted type with the payload `{"recipient_user_id": ..., "organization_id": ...}` (two identifiers, no unknown field, schema version 1) and the aggregate that the type names. For `invitation.delivered` the aggregate is the `invitation`, which is also the content source. The synthetic event uses a one-off `synthetic_notice` aggregate at version 1, and its source is the organization of the payload; `notification.SyntheticNoticeEventPayload` is the single writer of that payload. The invitation module therefore needs no change in the table, the consumer, or the API: it appends `invitation.delivered` and registers a content resolver for the source `invitation` in `notification.DefaultInboxSourceResolvers()`. Until a resolver exists, an item of that source is listed without content.
|
|
- Synthetic event type. `notification.synthetic_delivered` has no product meaning. It exists so that the whole path (outbox, relay, Kafka, consumer, read-time check, list, read state) can be exercised before a real producer exists and in browser tests. It is off by default: the consumer handles it and the inbox renders it only when `NOTIFICATION_SYNTHETIC_ENABLED=true` (a development or browser-test stand; the e2e overlay sets it). With the switch off the event is acknowledged and ignored and a stored synthetic row is listed without content; the database CHECK allows the type either way, so turning the switch on needs no migration. Only code that can append to the outbox can produce it, and its content is a fixed text that names the sending organization. The browser suite appends it through the `company-fixture` (Go build tag `e2e`), never through a user operation.
|
|
- Consumer `notification_inbox`. `InboxHandler` handles the allowlisted types. In the transaction of the dedup marker it checks the envelope and the payload and rejects a broken event for good (`ErrEventRejected`), skips a recipient whose account was deleted, and stores the row with `ON CONFLICT DO NOTHING` on the key. A recipient deleted between the check and the insert aborts the insert with a foreign-key error that names the recipient; the handler returns it as a retryable error, and the retry finds the account gone and skips, while a foreign-key error on the organization is rejected for good. Three layers keep one row per recipient and event ID: the consumer marker, the key, and the comparison of a duplicate with the stored metadata, which rejects an event ID that comes again with other metadata instead of overwriting it. A replay under a renamed consumer therefore stores no second row. `occurred_at` is the informational insert time of the outbox row; it orders the list together with the event ID. The consumer group `<CONSUMER_GROUP_PREFIX>.notification_inbox` is new, so it starts at the earliest retained event; events of other types are counted as ignored.
|
|
- Content is resolved at read time. `InboxService` lists a page and calls the resolver of each item's source type in the transaction that authorized the viewer; the result is never stored. A resolver returns `ErrInboxContentUnavailable` when the source is gone or the recipient may not see it now. The item then stays in the list with `content` null, the client shows a generic line, and an earlier text is never shown. A source type without a resolver is unavailable, never guessed. The one resolver today belongs to the synthetic notice: its fixed Russian text names the sending organization by its current name, which `OrganizationNameForRecipient` reads under the recipient's current standing. A candidate sees the name until they hide the organization, and an employer while their membership is active. A name that does not fit the presentation limits is not shown. A content link is a same-origin path of a narrow alphabet, and the client opens it only inside its own cabinet.
|
|
- Scope. The candidate cabinet needs a verified candidate account and lists every organization context of the caller. The cabinet of one organization needs an employer account with a verified email (otherwise 403 `email_not_verified`, like the other organization operations) and an active membership of any role in the organization of the path. The membership is locked `FOR SHARE` with `LockActiveMembership` in the transaction of the list or the mark, like the card reads, so a revocation cannot commit between the check and the read and stops the next request. The recipient always comes from the session; the organization of the path narrows the rows and a path identifier alone grants nothing. A candidate on an organization route and an employer on the candidate route get 403. A missing membership, an unknown organization, an item of another account, an item of another organization, and an unknown ID all get the same 404 `not_found`. The organization routes are not in the owner-only list of `NewCompanyContextMiddleware`; `TestCompanyContextOperationInventoryMatchesOpenAPI` names them as authorized in their own transaction.
|
|
- Reading and marking. `GET /api/v1/me/notifications` and `GET /api/v1/organizations/{org_id}/notifications` return a newest-first page with a cursor bound to the account and the cabinet; a cursor of another account or cabinet is a 400. `POST .../{notification_id}/read` stores the first read time and returns it again on every repeat. It reads no source and returns no content, so an item without content can still be marked. All four are `Cache-Control: no-store`; a mark needs the session, the CSRF token, and an allowed Origin, and no Idempotency-Key because it is idempotent by its effect. No problem code was added.
|
|
- Frontend. `features/notifications` exports `NotificationInbox` (candidate or one organization) and `OrganizationNotificationInbox` (the chooser of the organization in the `organization_id` parameter plus the inbox). The pages `/candidate/notifications` and `/employer/notifications` and an entry "Уведомления" in each shell use them. The list is read on every visit and never kept (`gcTime: 0`), is keyed by account and cabinet, and is dropped when the account or the session changes or when access is refused. States: loading, empty, error with retry, forbidden, an item without content, and "show more". The read state is a word, not only a style, the mark is a native button, and focus moves to the item's heading after it succeeds.
|
|
- Trade-off: eventual consistency. The row is written by the consumer after the relay and Kafka, so a notification appears seconds after the producer committed, not inside the producer's transaction. The alternative, writing the row in the producer's transaction through `UnitOfWork.NotificationInbox()`, would make it immediate but would tie every producer to the inbox and drop the replay and dead-letter handling that the consumer gives. The browser suite therefore waits for the item and then replays the event.
|
|
- Tests. Unit: `domain/notification_inbox_test.go`, `usecase/notification/inbox_test.go` and `inbox_handler_test.go` (cabinet checks, membership revocation, resolver fallback, idempotent handler, rejected events, an `invitation.delivered` event under the same contract), `adapter/primary/http/v1/notifications_test.go`, `adapter/primary/http/notification_contract_test.go`, `bootstrap/consumers_test.go`, and the feature tests in `frontend/src/features/notifications/`. Integration: `TestNotificationInboxOverHTTP` and `TestSyntheticNotificationMigration*`. Browser: `frontend/e2e/notifications.spec.ts` in the registration mode ([TESTING.md](TESTING.md#browser-e2e-suite)).
|
|
- Not implemented: the invitation producer and its content resolver, an unread counter or badge in the shells, live updates (the list is read on a visit and on window focus), archiving or deleting an item, retention of old rows, per-role filtering of employer notifications, a mail preference, and a metric for the inbox. The rows of the synthetic type are never removed by the application.
|
|
|
|
### Product policy versions
|
|
|
|
Implemented as storage, a publisher, and a startup seed: migration `backend/db/migrations/00003_create_policy_versions.sql`, queries in `backend/db/queries/policy.sql`, the typed policy in `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), the `outbound.PolicyRepository` port (`port/outbound/policy.go`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/policy.go`, and the publisher in `backend/internal/usecase/policy/`. No product rule reads the policy yet; invitations, quotas, assessment, sessions, and the search status will read it as their tasks are implemented.
|
|
|
|
`policy_versions` columns:
|
|
|
|
- `id`: uuid primary key, a UUIDv7 generated in Go (`domain.PolicyVersionID`).
|
|
- `policy_key`: the policy family. Each family has one document layout and one decoder; `product`, decoded as `domain.ProductPolicy`, is the only family, and both the domain and the `policy_versions_policy_key_known` CHECK reject any other. `version`: an integer above zero, unique within the family (`policy_versions_policy_key_version_key`); the newest publication has the highest number.
|
|
- `kind`: `demo` or `calibrated`, the calibration state of the whole version. Consumers read this flag. The `policy_versions_calibrated_kind_matches_document` CHECK and the domain refuse a `calibrated` version whose document marks the assessment section as uncalibrated.
|
|
- `created_at`: the publication time from the database clock. The BEFORE INSERT trigger `policy_versions_stamp_creation` sets it to `clock_timestamp()` on every insert and ignores a value from the caller.
|
|
- `effective_at`: when the version can start to apply. A NULL in the insert means "at publication", and the same trigger sets it to `created_at`; a scheduled time must not be earlier (`policy_versions_effective_after_creation`, mapped to `outbound.ErrPolicyVersionBackdated`).
|
|
- `author`: `system:<name>` or `operator:<handle>`, at most 128 bytes of lowercase letters, digits, `.`, `_`, and `-`. It excludes `@`, so it cannot hold an email address. It is text rather than a reference to `users`: the seed has no account, admin roles do not exist yet, and a version must outlive any account, while a cascading or nulling foreign key would conflict with immutability. An admin editor can add an account reference in an additive migration.
|
|
- `document`: a jsonb object with the typed policy. `document_sha256`: the SHA-256 of the canonical document, 32 raw bytes.
|
|
|
|
The database enforces immutability. The trigger function `policy_versions_refuse_change` refuses every UPDATE and DELETE (row trigger) and TRUNCATE (statement trigger) with SQLSTATE 23000 and the constraint name `policy_versions_immutable`; the adapter maps exactly that pair to `outbound.ErrPolicyVersionImmutable`, never the message. The port has no update or delete method, so a change is always a new version. The guarantee covers application statements and manual SQL; a role that owns the table can still disable the trigger or drop the table, so a least-privilege runtime role remains future work.
|
|
|
|
Typed policy, `domain.ProductPolicy`: every value is a named field whose type carries the unit: `CalendarDays`, `BusinessDays` (no conversion to a duration; the consuming feature supplies the business calendar), `Hours`, and `BasisPoints` for probabilities and the standard error, an integer count of 0.0001 (0.80 is 8000). Basis points compare exactly, without floating-point drift, and keep integers in the document. The `Validate` method of each section rejects zero, missing, and out-of-range values and inconsistent combinations, such as a default deadline outside the options, a higher quota tier with a lower limit, an inactive E0, an active tier above an inactive one, or stop probabilities that do not surround the confirmation threshold. The ranges are sanity bounds against unit mistakes, not product decisions. Quota tiers E0 < E1 < E2 are looked up with `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (for organization quota enforcement); every organization starts at E0, and the rules that move it between tiers belong to the quota feature.
|
|
|
|
The MVP attempt accounting decision is candidate-wide: `MaxAttemptsPerWindow` counts root attempts across specializations in the rolling `AttemptWindow`. A corrective attempt shares its root slot, and training does not consume it. Retry and promotion timers remain independent by specialization.
|
|
|
|
Legacy documents use `schema_version` 1 with the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`. Schema 2 adds independently optional `assessment.attempt`, `assessment.training`, `assessment.signals`, `support`, and `matching`, and requires at least one of those extensions. Encoding selects schema 1 without extensions and schema 2 otherwise. Each schema has a strict decoder: the legacy decoder rejects extension keys even when null, and an absent optional section never acquires defaults. Required fields reject missing/null values, wrong types, fractions, and values outside int32; both decoders reject unknown fields, unknown schema versions, trailing data, and documents over 64 KiB. Field names carry their unit (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). The canonical form is compact Go JSON in field declaration order. `domain.RestorePolicyVersion` decodes, validates, re-encodes, and compares SHA-256 with `document_sha256`; mismatch returns `domain.ErrPolicyDocumentIntegrity`. The schema 1 golden bytes and hash stay unchanged. Deploy readers supporting schema 2 before publishing it; a previous binary cannot read schema 2, so publishing it prevents rollback to that binary. Stored policy documents are never rewritten for compatibility.
|
|
|
|
The port `outbound.PolicyRepository` is available through `UnitOfWork.Policies()` and outside a transaction through `postgres.PolicyStore`. Methods that take a family reject an unknown one before reading storage.
|
|
|
|
- `Create` stores a numbered `domain.PolicyVersionDraft` and returns the stored `domain.PolicyVersion` with the database times. The insert uses `ON CONFLICT DO NOTHING`, so a taken number or ID returns `ErrPolicyVersionConflict` without aborting a surrounding transaction.
|
|
- `GetByID` reads one version.
|
|
- `GetEffective(key, at)` returns the newest publication, the highest number, among the versions whose `effective_at` is not after `at`. A version scheduled for later therefore never undoes a version published after it: an urgent correction stays in effect when an earlier scheduled version reaches its time, and the scheduled version is superseded. The unique `(policy_key, version)` index serves this lookup.
|
|
- `GetLatest(key)` returns the highest number, effective or not.
|
|
- `HasVersions(key)` reports presence without reading a document.
|
|
- Misses return `ErrPolicyVersionNotFound`.
|
|
|
|
`policy.Publisher` validates the whole input before it reads storage. It takes the application clock only to refuse a scheduled effective time that has already passed; the publication time comes from the database. `Publish` assigns the highest stored number plus one; when a concurrent publication takes the number, it reads again and retries up to 10 times, then returns `policy.ErrPublishContended`. It works on a standalone repository or inside a unit of work.
|
|
|
|
Demo and calibrated policy: `domain.DemoProductPolicyV1()` is the accepted initial policy for verifying the product flow. It is published as version 1 of `product` with kind `demo` and author `system:demo-seed`, and its assessment section is marked `uncalibrated_initial`. These values make no calibrated quality claim. The policy holds rules only; assessment content (the task bank, blueprints, and variants) is a separate task. Demo version 1:
|
|
|
|
| Section | Values |
|
|
| --- | --- |
|
|
| `invitations` | response deadline options 3, 7, and 14 days, default 7; at most 20 pending invitations per need; repeat after a decline in 30 days; interview proposal within 5 business days; 30-day pause after no deal |
|
|
| `organization_quotas` | rolling windows of 7 days for invitations and 24 hours for distinct card views; E0 10 invitations and 50 views, E1 40 and 150, E2 100 and 400; E2 is inactive until the organization verification that grants it exists |
|
|
| `assessment`, uncalibrated initial | same-grade retry after 30 days; at most 3 attempts per 180 days; at most one promotion per 90 days; confirmation at P_G >= 0.80, high strength from 0.90; after at least 8 scored items stop at P_G >= 0.90 or <= 0.10 or SE <= 0.25; at most 23 scored items plus 2 seed items; practice is mandatory |
|
|
| `identity` | verification token 24 hours; unverified account deleted 7 days after the latest registration; session idle timeout 24 hours, absolute lifetime 7 days |
|
|
| `search_status` | the "searching" status is confirmed every 30 days |
|
|
|
|
The identity lifetimes in this table are the values of the identity contract ([api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). They come from the versioned product policy, not from configuration: the registration, verification, and session usecases will read them from the effective policy version. The grade rules in [Assessment and grade verification](#assessment-and-grade-verification) use the same assessment values.
|
|
|
|
Matching coefficients (`matching`, schema 2, `domain.MatchingPolicy` in `policy_matching.go`, demo version `domain.DemoProductPolicyV4()`): every field is required once the section is present, and the units are basis points except the two skill weights and the cohort size. The demo values are the design values of PRD 4.9 for checking the flow, not measured results; they are published explicitly (the isolated browser fixture publishes V4; startup still seeds V1 only), and a policy version without the section makes the search fail closed instead of ranking with defaults.
|
|
|
|
| Field | Demo value | Meaning |
|
|
| --- | --- | --- |
|
|
| `fit_coverage_weight_bp`, `fit_domain_weight_bp`, `fit_semantics_weight_bp` | 7500, 1500, 1000 | `Fit = 0.75 * Cov + 0.15 * Dom + 0.10 * Sem`; the three add up to 1 |
|
|
| `rank_fit_weight_bp`, `rank_strength_weight_bp` | 5000, 5000 | `S = (0.5 * Fit + 0.5 * P) * freshness * responsiveness`; the two add up to 1 |
|
|
| `freshness_floor_bp`, `responsiveness_floor_bp` | 9000, 9000 | the multiplier `0.9 + 0.1 * x` of Fr and Rsp; a floor of zero is refused |
|
|
| `competition_boost_bp` | 3000 | `P = T + 0.3 * (1 - T) * V` |
|
|
| `neutral_unknown_bp` | 5000 | the neutral 0.5 for an unknown component (Dom, Sem, T, Fr, Rsp, and Cov of an empty request) |
|
|
| `near_skill_threshold_bp` | 2500 | a required skill that contributes less moves a confirmed profile to the near group |
|
|
| `required_skill_weight`, `desired_skill_weight` | 2, 1 | weights of the skills in Cov |
|
|
| `trust_stated_bp`, `trust_online_bp`, `trust_identity_bp`, `trust_in_person_bp` | 2500, 6000, 8500, 10000 | coefficients of the evidence trust levels 0 to 3 |
|
|
| `attribution_personal_bp`, `attribution_team_role_bp`, `attribution_team_unattributed_bp` | 10000, 8000, 5000 | personal result, team role, team result without a role |
|
|
| `relation_exact_bp`, `relation_narrower_bp`, `relation_broader_bp` | 10000, 8000, 4000 | evidence for the same skill, a narrower one, a broader one |
|
|
| `percentile_min_cohort` | 30 | the smallest comparable real cohort that allows a percentile; the search compares the real cohort of each returned category with it |
|
|
| `max_results_per_group` | 10 | entries of each group that one search may return; the whole bank is ranked and only the output is cut |
|
|
| `skill_taxonomy` | backend over docker, go, kafka, postgresql; devops_sre over docker | the technologies inside each specialization, which decide whether evidence is broader or narrower than a requested skill |
|
|
|
|
The validation keeps each share in 0..1, the fit and rank weights at a sum of 1, the trust and relation coefficients ordered, and the floors above zero. Not in the policy yet: the competition half-life of 24 months and the embedding-only relation 0.3, because no competition data and no embeddings exist.
|
|
|
|
Seeding: at startup, after migrations and under the same condition (`DATABASE_MIGRATE_ON_START` is true and `DATABASE_URL` is set), bootstrap calls `Publisher.EnsureDemoProductPolicy`. It checks only whether `product` has any version and never decodes one, so a stored version of a newer or unknown layout cannot block startup. When the family is empty, it publishes demo version 1 effective at publication; otherwise it changes nothing and logs that the seed was skipped. Instances that start together race for version 1, and the loser skips. The log line names only the key, number, kind, and ID. A database error stops startup. The seed is not a data insert in a migration, so the schema and the policy values change independently.
|
|
|
|
Referencing a version (planned): tables that record a decision built under a policy, such as grade decisions, selection snapshots, and invitations, carry `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)` and store the version used when the decision was made. An existing decision reads that version with `GetByID` and is never recomputed through `GetEffective`, whose answer for a given time changes when a scheduled version is superseded. A referenced version cannot be deleted, by the foreign key and by the trigger, and a new version never rewrites past decisions.
|
|
|
|
Test fixtures use their own values. Since `product` is the only family, the integration tests give every case its own database, and no fixture stands in for the demo policy.
|
|
|
|
## Release artifacts and restoration
|
|
|
|
The local release manifest separates core image verification from product data availability. It records immutable release IDs, source and Compose file hashes, exact built image IDs, registry digests for pulled images, and bounded hashes for versioned data artifacts. Restoration checks these references and hashes before Compose starts and never resolves a moving tag again. The bundled demo policy source is version 1, but that does not establish which policy row is active in PostgreSQL. The assessment bank and demo seed remain unavailable until accepted snapshots exist, so `product_data_status` is partial. Named Compose volumes persist across a release restart, but the manifest is not a database backup or data snapshot. See [DEPLOY.md](DEPLOY.md#release-manifest) for the commands and manifest schema.
|
|
|
|
## Repository map and package purpose
|
|
|
|
```text
|
|
api/core/ public browser-to-Go contract and bundle
|
|
api/ml/ internal Go-to-ML contract and bundle
|
|
backend/cmd/app/main.go calls bootstrap.Run and reports errors
|
|
backend/cmd/migrate/ local migration status, up, and down-one
|
|
backend/config/ shared runtime configuration
|
|
backend/internal/domain/ product invariants, planned modules
|
|
backend/internal/usecase/ application operations and orchestration
|
|
backend/internal/port/ inbound and outbound interfaces
|
|
backend/internal/adapter/ primary HTTP and secondary integrations
|
|
backend/internal/bootstrap/ dependency wiring and process lifecycle
|
|
backend/db/ migrations, SQL queries, and the embedded migration set
|
|
backend/codegen/ ogen server and ML-client configs, sqlc
|
|
frontend/src/ app, pages, widgets, features, entities, shared
|
|
frontend/codegen/ Orval configuration
|
|
ml/src/ FastAPI service and operational checks
|
|
ml/codegen/ Python datamodel-code-generator settings
|
|
deploy/ Compose, Nginx, and technical smoke checks
|
|
observability/ Prometheus, Loki, Alloy, Grafana provisioning
|
|
scripts/ shared documentation and schema tooling
|
|
docs/ maintained Russian and English guides
|
|
```
|
|
|
|
```text
|
|
backend/
|
|
cmd/app/main.go calls bootstrap.Run and reports errors
|
|
config/ shared runtime configuration
|
|
internal/
|
|
domain/ flat package; DomainEvent, identity types, consent ledger, organizations and memberships, product policy
|
|
usecase/health/ operational readiness usecase
|
|
port/inbound/ readiness and event handler input boundaries
|
|
usecase/identity/ password validation before hashing (Credentials)
|
|
usecase/policy/ publication of policy versions and the demo policy seed
|
|
usecase/consent/ granting of consents C1-C3 and C5 and the scoped C4 with the current-text check
|
|
usecase/files/ shared private file layer: policies, opaque keys, stream limits, checksums
|
|
usecase/notification/ mail requests and the consumer that stores them as deliveries, the quota gate, the service mail enqueue (`ServiceMailer`), and the sender of service mail (`ServiceMailSender`)
|
|
usecase/notification/mailtemplate/ pure rendering of versioned service emails; the delivery consumer renders notifications with it
|
|
port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, organization and membership, policy, password hashing, and mail boundaries
|
|
adapter/primary/http/
|
|
api/ generated ogen handler
|
|
middleware/ request log and request metrics by route template
|
|
observe/ request-scoped observations, such as the problem code
|
|
problem/ RFC 9457 error responses
|
|
v1/ handwritten health endpoint
|
|
router.go chi composition
|
|
adapter/secondary/
|
|
argon2id/ Argon2id password hasher with a memory budget
|
|
kafka/ franz-go event publisher and consumer group member: record envelope, its decoding, and events topic provisioning
|
|
mail/disabled/ mail transport that sends nothing and reports the channel unavailable
|
|
mail/resend/ mail transport that sends one request to the Resend HTTP API per message
|
|
mail/resend/resendfixture/ local stand-in for the Resend API, for tests only; production never imports it
|
|
ml/api/ generated client from backend/codegen/ogen-ml.yml
|
|
postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity, consent ledger, organization, membership, and policy repositories, health check
|
|
postgres/sqlc/ generated SQL adapter
|
|
redis/ cache adapter and Redis check
|
|
seaweedfs/ S3 adapter and bucket check
|
|
prometheus/ bounded Go/process, request, problem, outbox, consumer, job, delivery, quota, and answer save metrics
|
|
worker/outboxrelay/ outbox relay loop: claim, publish, mark, backoff, and shutdown
|
|
worker/eventconsumer/ event consumer runtime: dedup transaction, retries, dead letters, offset commits, and shutdown
|
|
worker/jobrunner/ scheduled job runtime: claim under a lease, run with the completion, retries, release, and shutdown
|
|
worker/mailsender/ sending loop of service identity mail: repeats passes, waits when idle, backs off on failures, reports lincodex_mail_sender_running
|
|
worker/retry/ backoff with jitter and a context-aware wait shared by the workers
|
|
worker/deliverymetrics/ periodic read of the delivery and mail quota aggregates into the metrics
|
|
bootstrap/ configuration, wiring, lifecycle, shutdown
|
|
db/ embedded migrations and SQL queries; outbox, identity, policy, event consumer, delivery, mail quota, scheduled job, consent ledger, and organization tables
|
|
codegen/ ogen and sqlc configs
|
|
pkg/testutil/ fake application clock and identifier scan shared by tests
|
|
```
|
|
|
|
Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The consent ledger types live in `consent.go`. The organization, verification, and membership types live in `organization.go` and `membership.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`.
|
|
|
|
Outside the implemented identity and consent flows, domain types and usecases for other product workflows are not implemented. SMTP and FSP adapters, and product worker jobs, remain planned. `main.go` starts bootstrap and handles process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
|
|
|
|
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` and `notification_inbox` handlers, the internal notification inbox with its list and read-state operations, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for every operation protected by the API contract, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, sending product notifications, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
|
|
|
|
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. A `mailer` package remains a candidate. Mail templates live in `internal/usecase/notification/mailtemplate/`: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; `ServiceMailer` creates verification mail during registration and resend. Password reset mail belongs to the planned reset flow. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
|
|
|
|
`api/` contains contract sources and tools; it is not a runtime hop in the request path. `api/core/` and `api/ml/` each own OpenAPI source, route and component fragments, and a committed bundle. Root `scripts/` merges schema fragments. Generated Go output belongs to its consumer: the public handler under `backend/internal/adapter/primary/http/api/`, the internal ML client under `backend/internal/adapter/secondary/ml/api/`, and sqlc output under `backend/internal/adapter/secondary/postgres/sqlc/`. The first is transport code mounted in chi; the latter two are outbound adapters. `backend/cmd/app/main.go` remains a small process entry point; bootstrap owns dependency wiring and graceful shutdown.
|
|
|
|
## Target modules
|
|
|
|
| Module | Responsibility | Main data |
|
|
| --- | --- | --- |
|
|
| identity | Email, verification, sessions, roles | users, email_tokens, sessions, external_identities |
|
|
| candidate | Profile, contacts, consent, visibility | profiles, contacts, skills, consents, resume_versions |
|
|
| company | Company and its members | organizations, organization_representatives, memberships |
|
|
| assessment | Questionnaire, tasks, attempts, scoring, grade | questionnaires, task_templates, attempts, answers, grade_history |
|
|
| matching | Needs, filters, ranking, search versions | hiring_needs, search_runs, search_items |
|
|
| invitation | Offer and contact permission | invitations, invitation_events, contact_grants |
|
|
| document | Files, resume analysis, standard PDF | files, analysis_results, document_jobs |
|
|
| achievement | FSP link and achievement provenance | fsp_links, achievements, sync_runs |
|
|
| vacancy, later | Vacancies and voluntary applications | vacancies, applications |
|
|
|
|
The MVP uses one PostgreSQL database. Keep relational links and constraints explicit. JSONB can hold versioned questionnaire answers and ML results; it does not replace the data model. Skills and specialties use normalized references. Large PDFs stay outside PostgreSQL. Candidate category combines specialty and test-verified grade. Claimed and verified grades remain separate.
|
|
|
|
An achievement records its source, external ID, event date, receipt date, and trust status. Missing FSP history, a missing link, and a temporary sync error are distinct states. ML has no direct access to the business database.
|
|
|
|
## Target user flow
|
|
|
|
Candidate flow: verify email -> complete profile and consent -> answer questionnaire -> select expected grade -> take assessment -> receive a verified category -> publish profile.
|
|
|
|
Employer flow: verify email -> create company profile -> describe need -> confirm extracted skills -> choose filters -> review an explainable result set -> send a salary offer -> candidate accepts -> only that company can access contacts.
|
|
|
|
An invitation includes the employer, description, contact channel, both salary bounds, and RUB currency. Both salary values are required whole rubles in multiples of 1000 and must satisfy 0 < salary_from < salary_to, with a width (salary_to - salary_from) / ((salary_from + salary_to) / 2) from 10% to 40% inclusive (PRD FR13); the same rule applies to the salary range of a need. Show the pay period and tax basis (net or gross). vacancy_id is optional. Main transitions are draft -> delivered -> viewed -> accepted or declined; the internal sending step is never visible, a send answers with delivered, and direct acceptance from delivered is allowed. The candidate records viewed with an explicit view command; reading an invitation has no side effect. withdrawn (by the organization), expired (a server deadline), and cancelled_by_candidate are terminal states. Retries are idempotent, and transactions protect concurrent state changes. The draft part of this flow is implemented; see [Invitation drafts](#invitation-drafts).
|
|
|
|
A contact grant belongs to one candidate-company pair and is created after an accepted invitation or a candidate's own application. The server checks the user, company membership, grant, and current visibility on each read. Before a grant, employers receive no contacts, original PDF, messaging links, or contact fragments from resumes or ML.
|
|
|
|
The owner profile, search card, and authorized contacts use separate DTOs. The candidate can receive a complete PDF. A company export is built from its allowed view after another access check. A permanent public file URL does not replace authorized delivery. Revoked consent removes the profile from new and saved search results; it cannot retrieve information another party already received.
|
|
|
|
## Assessment and grade verification
|
|
|
|
Assessments use reviewed task families and a blueprint for each specialty and grade. The blueprint records competencies, difficulty, task count, and weights. Variants change the prompt and input while keeping the assessed skill; shuffling answer choices is insufficient. Go backend and React frontend at junior/middle level are the initial demo scope. Other specialties need a real task bank.
|
|
|
|
Fix the seed, version, and conditions before an attempt. Keep answers and keys on the server. Prefer automatically scored formats that do not execute candidate code in the MVP. Free-form answers can be an additional signal; LLM scoring is never the sole basis for a grade. Team pilots set thresholds, and a high average must not hide a critical-section failure.
|
|
|
|
Grade state rules:
|
|
|
|
- Before the first passing assessment, status is unverified and a claimed grade does not grant verified category access.
|
|
- A failed attempt never lowers an existing verified grade.
|
|
- After an initial failure, the candidate may choose a lower-level test; the system does not assign it automatically.
|
|
- A promotion after a successful qualification is allowed at most once per 90 days.
|
|
- The first lower-level test after failure is outside that interval. A retry of the same grade waits 30 days, and a candidate takes at most 3 attempts in any 180 days.
|
|
- A strong result may suggest a higher-level test. Keep the grade history available.
|
|
|
|
These intervals are the accepted initial policy, stored as demo version 1 of the [product policy](#product-policy-versions); its thresholds are uncalibrated and are not a validated psychometric model. Task rotation and attempt limits reduce the value of leaked answers but do not prove resistance to hints or LLMs. Difficulty comparability needs measurement.
|
|
|
|
### Assessment bank
|
|
|
|
Implemented as storage and a loader, not as a candidate-facing feature: migration `backend/db/migrations/00011_create_assessment_bank.sql`, queries in `backend/db/queries/assessment_bank.sql`, the domain types in `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), the `outbound.AssessmentBankRepository` port (`port/outbound/assessment_bank.go`, reachable through `UnitOfWork.AssessmentBank()`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/assessment_bank.go`, and the loader in `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Nothing in bootstrap or the HTTP API calls it yet, and no category is open.
|
|
|
|
- Family version. One `assessment_families` row is one version of one family (`family_key`, `version`): category, specialization (the domain inside the category), title, author (`ai:<name>` or `operator:<handle>`), reviewer (`operator:<handle>` or NULL), `review_status` (`pending`, `approved`, `rejected`), the seed generator, the answer key, the rubric, a content hash with its `hash_scheme`, a lifecycle (`draft`, `published`, `retired`), and the operators and times of publication and retirement. The reviewer is never the author, and a review is pending exactly while there is no reviewer (CHECK constraints; the domain applies the same rules). The reviewer in a bundle and the operator of a publication are declared values, not authenticated identities, until reviewer and operator accounts exist.
|
|
- Immutability. The content of a stored version never changes: the trigger `assessment_families_guard_update` refuses every UPDATE that changes a column other than the lifecycle columns (`lifecycle`, `published_at`, `published_by`, `retired_at`, `retired_by`), and `assessment_families_refuse_removal` refuses DELETE and TRUNCATE, all with SQLSTATE 23000 and the constraint name `assessment_families_immutable`, which the adapter maps to `outbound.ErrAssessmentFamilyImmutable`. The lifecycle moves only forward (draft, published, retired), the trigger sets the times and keeps the publisher through a retirement, and a version is published only with an approved review by a reviewer (`assessment_families_published_requires_review`). A change is a new version with the next number; the loader accepts only version 1 for a new family and the successor of the latest version otherwise. A pending draft is never approved in place: its review is recorded by importing a new version of the family that carries the review, and the pending version stays an unpublished draft. The domain recomputes the content hash when it reads a row and returns `ErrAssessmentFamilyIntegrity` for a row changed outside the application. The hash is the SHA-256 of a canonical JSON document that holds the content without the bundle name, ID, lifecycle, and publication fields. The `hash_scheme` column (a smallint with a CHECK of the known values, one of the immutable columns) names the layout: the domain verifies a row with the hash function of the scheme the row was stored with, so a later scheme (a new function and a new CHECK value, never an edit of scheme 1) verifies new rows without invalidating old ones, and a row with an unknown scheme is refused; tests verify a row with its own scheme and pin the scheme 1 hash of a fixed input. As for `policy_versions`, a role that owns the table can still disable the triggers.
|
|
- One published version per family. A partial unique index (`assessment_families_one_published_key`) allows at most one published version of a key. `Bank.PublishFamily` retires the published older version in the same transaction and refuses with `newer_version_published` when a newer version of the key exists in any state, a draft or a retired one included, so superseded content is never put back in the bank (earlier content is published again by importing it as a new version); `Bank.ActiveFamily` reads the single published version. Coverage counts each family once.
|
|
- Seed generator and variants. A generator names a registered algorithm with a versioned name (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `dependency_order.v1`), the ranges of its parameters, and a statement template. A seed selects a variant: the same version and seed always give the same statement and reference answer (the pseudo-random source is SplitMix64 written out in the domain, so variants stay reproducible across Go releases; golden tests pin one statement and answer per algorithm), and the rubric is a property of the family, so no seed changes it. The reference answer comes from the algorithm's solver, which has unit tests with hand-computed cases. The registry only grows: a changed algorithm gets a new name, because stored versions refer to the old one.
|
|
- Statement templates. A template is plain text with `{{.name}}` placeholders and nothing else: the text/template parser reads it without functions, and a whitelist walk refuses every node except text and a single field action (so `define`, `template`, `block`, `range`, `with`, `if`, variables, pipelines, and calls such as `printf` are refused). The loader renders the placeholders itself, never runs the template engine, and caps the template at 2000 bytes and the rendered statement at 8 KiB. Every placeholder must belong to the algorithm, and the template must contain the placeholders the answer depends on (the input data and the answer-relevant parameters), so a statement always shows the input. A bundle is validated fully at import, with probe renders at the lowest parameter values and, for eight seeds each, at the highest values (the largest inputs) and at drawn values, so a template close to the size cap cannot pass on one lucky seed; reading a stored row does not repeat the probes, because the content hash proves the content is the one that passed them. Titles, templates, and rubric texts refuse control characters, Unicode format characters (for example bidirectional overrides), and the line and paragraph separators U+2028 and U+2029; the title CHECK constraint also refuses the common ones.
|
|
- Rubric. A rubric holds a principle and a list of criteria. It has no points, weights, or pass mark; how criteria become a grade is not decided in the bank.
|
|
- Lifecycle and the loader. `Bank.ImportBundle` stores every family of a bundle as a draft in one transaction and never publishes, whatever the review says; importing the same bundle again, also concurrently, reports the versions as unchanged. `Bank.PublishFamily` and `Bank.RetireFamily` take the operator, and refuse with a reason (`reviewer_missing`, `review_not_approved`, `not_draft`, `not_published`, `newer_version_published`); the refusal is a `*domain.AssessmentRefusalError` that carries the reason, and the sentinels of a race that the database decided (a lifecycle step that lost to another, a missing approved review, insufficient coverage) become the same refusals. Publishing, retiring, and opening take a transaction-scoped advisory lock of the category first, so they run one after another per category; `LockCategory` works only inside a transaction (the repository of a unit of work takes it, the standalone store returns `ErrAssessmentLockOutsideTransaction`).
|
|
- Category availability. `Bank.OpenCategory` records an opening in `assessment_category_openings` under a referenced policy version (`policy_versions.id`); it refuses with `grading_policy_missing` for a missing or unknown reference and with `grading_policy_not_current` unless the version is the one of the `product` family in force now, judged against the database clock of the same transaction (`clock_timestamp()`), the clock that stamps the effective time of a policy version, so the bank defines no thresholds of its own and no application clock enters the decision. The number of distinct published families that a category needs is read from that policy: `RequiredPublishedAssessmentFamilies` returns `assessment.stop_rule.max_scored_items` plus `assessment.stop_rule.seed_items`. The owner accepted this rule as a product decision on 2026-10-06. The reason: one family gives at most one item to an attempt, so a full adaptive attempt, which can run to the maximum of scored items and also carries the seed items, cannot run out of families. The insert trigger derives the same number from the stored policy document itself (the same two JSON paths; an integration test keeps the SQL and the domain equal) and checks both values as plain non-negative integers of at most four digits before the cast, so a malformed document written around the application raises the `assessment_category_openings_policy_thresholds` refusal instead of a cast error. The trigger also counts the published families, and the CHECK constraint refuses the row when they are fewer, so a call written around the usecase cannot open a category with a lower requirement. The opening stores the policy version, the operator (`operator:<handle>`), and the required and counted families, and is never edited. Availability is live: `Bank.CategoryAvailability` returns the current opening only while the published families counted now still reach the opening's requirement, and otherwise refuses with `coverage_insufficient` (or `ErrAssessmentCategoryNotOpen` without an opening), so a retirement can close a category. It also refuses with `grading_policy_not_current` when the opening's policy version is no longer the one in force, so a policy change requires a new opening. The table checks the policy reference in the trigger instead of a foreign key, because PostgreSQL refuses TRUNCATE of a referenced table before the `policy_versions` trigger can refuse it with its own error. `ListFamilies` pages by (key, version) cursor with a hard limit of 200.
|
|
- Demo bundle. `backend/testdata/assessment/backend_demo_bundle.json` holds four original practice problems for the category `backend`. They are an AI-generated draft (author `ai:claude-draft`) with a pending review and no reviewer, so the loader imports them as drafts, publication is refused, and the category stays closed. No human has reviewed the statements, solutions, rubrics, or difficulty; the bundle makes no validity or calibration claim. A real review produces a new version of the families that carries the approval.
|
|
- Not implemented: authorship and review of a real task bank, blueprints per specialty and grade, selection of tasks for an attempt, the storage of attempts and answers, grading, an HTTP or admin interface, authenticated reviewer and operator identities, and a wiring of the loader in bootstrap.
|
|
|
|
### Assessment signals and the review band
|
|
|
|
Implemented as server-side signals of a real attempt (root or corrective), a review band computed by a scheduled job under the policy version pinned to the attempt, and an operator-only reader. The band is a hint for a manual check by a person. It does not change the result, the category, or a quota; no candidate or employer operation carries it, and the public contract has no field for it (a test walks every operation, request, response, and header to check this). Until staff roles exist, the only reader is the local command `assessment-review`, which records each read ([DEPLOY.md](DEPLOY.md#assessment-review-band)). Browser signals are described separately by the signal receipt contract; this section covers what the server observes itself.
|
|
|
|
Code: migration `backend/db/migrations/00033_create_assessment_signal_review.sql`, queries `backend/db/queries/assessment_signal_review.sql`, the policy section and band rules in `backend/internal/domain/` (`assessment_signal_policy.go`, `assessment_signal_review.go`), the observer, the review job, and `ReviewOperator` in `backend/internal/usecase/assessment/signal_review.go`, the repository in `backend/internal/adapter/secondary/postgres/assessment_signal_review.go`, and the command in `backend/cmd/assessment-review/`.
|
|
|
|
- Facts. `assessment_answer_observations` has one row per accepted answer: the family, the seed, the answer format, the server time from the last activity of the attempt (the previous answer or the start of the current work session) to the accepted answer, whether that time starts at the previous answer, and a keyed answer fingerprint. `assessment_attempt_origin_marks` has a row when the login session or the client network of an accepted answer or signal batch differs from the last row (digests of both), so the list stays short however many requests arrive. The browser events of the signal receipt contract only add totals (focus loss time, clipboard events, fullscreen exits). Rows are append-only, removed only by the cascade from the attempt or the account, and written in the same transaction as the answer or the batch, which already holds the attempt row lock. Two maintained counters, `assessment_answer_fingerprint_holders` (answers per family version, key generation, and fingerprint) and `assessment_answer_family_totals` (answers per family version and key generation), are increased by a trigger in the transaction of each observation insert; they only grow, so an answer removed with an account stays counted, and they are derived caches without foreign keys. A transaction touches one row of each, always in the same order.
|
|
- No answer text, keyed digests only. The new tables store no answer text; the raw answer already exists in `assessment_attempt_items` and is untouched. Fingerprints and digests are HMAC-SHA-256 values under purpose keys derived from `IDENTITY_KEY_SECRET` with their own domain labels (`Keyring.AssessmentAnswerFingerprint`, `AssessmentSessionDigest`, `AssessmentNetworkDigest`); no new secret exists. Each stored value carries a `key_version` (now 1) and only values of one generation are compared, so a future key rotation is an explicit step. The answer fingerprint covers the family version and the canonical answer and is the same for every candidate and seed. The session and network digests also bind the attempt, so they cannot be linked between attempts. The HTTP adapter passes the session ID and the limiter key of the client address (an IPv6 address reduced to its /64) to the usecase, which hashes them; no address, session ID, token, or answer text is logged or stored. The digests live as long as the attempt (the retention period is an open question). Changing `IDENTITY_KEY_SECRET` makes old and new fingerprints incomparable.
|
|
- Server signals. Response time: an answer faster than the per-format floor of the policy is fast, and within one format an answer more than the policy ratio below the median of the attempt is an anomalous deviation (only the fast side; a slow answer is not suspicious, and a format needs enough answers of its own). One answer counts once: an answer under its floor is fast and not also a deviation. The first item of a work session is measured from the session start, which only bounds when the item was shown, so it is excluded from both. Parallel sessions: requests that return to an earlier login session after another session was used (a single move to a new session is not counted). Networks: the number of distinct client networks beyond the first, so a move to another network and back counts once. Parallel sessions and extra networks are weak and correlated (a phone and a laptop produce both), so they form one group: alone it reaches attention at most, and review only together with a strong signal (fast, deviating, or duplicate answers) at attention or above. Client time only complements server time: it is never the source of a response time, and client signals can raise a normal band to attention but never to review.
|
|
- Identical answers of different candidates, compared pairwise. For one attempt the comparison looks at every other attempt separately: matched answers are equal fingerprints of the same family version and key generation, given by another candidate to a different seed variant, so an expected agreement on one seed is not a signal and a candidate never matches their own attempt. A matched answer carries -log2 of the share of answers that hold that fingerprint among the answers of the family version and key generation, read from the maintained counters (so a rotation does not skew the share), between zero and the cap of its format (`duplicate_integer_cap_bits`, `duplicate_sequence_cap_bits`). A popular value, such as the correct answer of a variant, therefore carries little, and so does a population of a few attempts. The bits of one pair add up, the strongest pair decides, and `duplicate_bits_attention` and `duplicate_bits_review` are thresholds on that sum. The list of pairs is bounded and never leaves the usecase; nothing identifies the other attempt or candidate in any output, and the operator output holds counts only.
|
|
- Why the demo thresholds are 48 and 64 bits, and what the figure means. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` samples 4000 seeds of each of the four demo families (the three integer families have 36 to 47 distinct answers, the dependency order about 2250), builds the distribution of shared values and their bits, and computes the probability that one pair of honest candidates who answer a 23-item attempt correctly reaches each threshold. Multiplied by 10,000 rivals (union bound), the per-attempt false flag rate is about 4e-5 for attention and 3e-9 for review, against test targets of 1e-3 and 1e-8. The model uses the distribution of reference answers: it does not model the distribution of wrong answers or correlated mistakes (candidates who make the same common error, or a shared tutorial), which can make honest coincidences more likely than computed. These are demo values pending calibration on a real bank, with four AI-drafted families. In the other direction, `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` calculates how many answers per family a copied pair needs before the demo thresholds flag it, when the pair copies every answer and nobody else holds those values: for an attempt of 13 items, attention from 26 answers per family and review from 61; for 23 items, from 9 and from 14. A stand with fewer attempts flags nothing by design. To try the feature on a small stand, publish a policy version with lower thresholds in `assessment.signals` (the integration tests do this with 4 and 6 bits); the demo policy is not changed for that.
|
|
- Policy. The optional section `assessment.signals` of a schema 2 policy document holds every threshold (`domain.AssessmentSignalPolicy`); a version without it computes no band. `DemoProductPolicyV3` is `DemoProductPolicyV2` plus `DemoAssessmentSignalPolicy`; `DemoProductPolicyV1` and `DemoProductPolicyV2` and the startup seed are unchanged, and a stored version is never rewritten. The band uses the thresholds of the product policy version in `assessment_attempts.product_policy_version_id`, so a policy published later does not change an attempt in progress or a stored review; `assessment_attempt_reviews.policy_version_id` records the version, and a trigger refuses to change it. A matched attempt is re-evaluated under its own pinned version; pairs are selected with the attention level of the evaluating attempt, so across versions with different levels a pair can be missed on the side with the lower level.
|
|
- When and how. The review never runs in a candidate's transaction. The first accepted answer schedules the job `assessment.signal_review` with the key `<attempt>:deadline`, due one minute after the deadline of the attempt (so an answer committed right at the deadline is in its facts), and finalization schedules `<attempt>:ended`, due at once; both are inserts into `scheduled_jobs` in the transaction of the answer or the finalization, and repeats do nothing. The deadline job also covers an attempt that expires or is abandoned, however and whenever its state changes. A review is a point-in-time evaluation: it describes the facts committed when its job ran, and the job at the deadline runs it again for a finalized attempt, which picks up later matches. The job computes the review of its attempt and refreshes the review of every other attempt that has ended (terminal state or past its deadline) and shares answers with it at the attention level or above, at most 50 per job; a ring of more than 50 attempts that share answers is covered because each member runs its own deadline job and sees the others. An attempt that is still running is flagged by its own job when it ends and sees the other facts then. Writers are ordered by a transaction-scoped advisory lock per review: the job locks the review of every attempt it will write, in ascending attempt order, before it reads any fact, so the later of two jobs over one attempt waits and then reads what the earlier committed (no lost update, and no lock cycle). The times of a review come from the database clock inside the upsert and the update time never falls behind the stored times. Nothing else is locked: the facts are append-only and a job is scheduled after its facts are committed. A failure is retried by the runner with backoff and can never block or change a result; without the worker (`JOBS_ENABLED=false`) reviews wait with their jobs. The only review statement in a candidate's transaction is the insert of the job (and the two counter updates of the answer). The job logs one line with the number of reviews it wrote and its duration, and no answer, address, or candidate. Applicability bound: the share is read from the counters in constant time, but the comparison joins the answers of the attempt with the answers that hold the same values, so its cost grows with the number of holders of popular values, at most 23 items times the holders of each; it is fine for background jobs on populations of up to about 100,000 answers per family and needs sampling or a cap above that.
|
|
- Limits. Browser signals can be forged or suppressed, so they are a hint only. A helper such as an LLM on another device is not visible. False positives are possible: a shared or changing network (mobile data, NAT), a reload, two tabs, copying the task text, and coinciding answers of a small answer space. The retention period of these facts, whether collecting them needs a separate consent beyond the notice, and who calibrates the thresholds are not decided.
|
|
|
|
### Skill evidence
|
|
|
|
Implemented as a stored projection of the immutable assessment results, with two reads: the candidate's own list and the permitted projection of a currently visible card. The match search reads the organization projection (see [Matching and explanations](#matching-and-explanations)); no percentile reads it yet.
|
|
|
|
Code: migration `backend/db/migrations/00035_create_skill_evidence.sql`, queries `backend/db/queries/evidence.sql`, the model in `backend/internal/domain/evidence.go`, the port `port/outbound/evidence.go` (`UnitOfWork.Evidence()`), the adapter `adapter/secondary/postgres/evidence.go`, the usecase `backend/internal/usecase/evidence/read.go`, the handler `adapter/primary/http/v1/evidence.go`, and the operations `ListMyEvidence` and `GetOrganizationCandidateEvidence` ([api/README.en.md](../../api/README.en.md#skill-evidence)).
|
|
|
|
- One event is one fact. `skill_evidence_facts` has one row per source event (`UNIQUE (source_type, event_id)`); `skill_evidence_skills` holds the skills of that event as tags (primary key `(fact_id, skill_code)`, a closed set of the nine specialization codes and the four technology codes of the card). A second tag adds a tag, never a fact, so repeated tags cannot multiply a contribution. A fact without a skill cannot be committed (a deferred constraint trigger), tags, once stored, are never rewritten or removed, and a tag joins a fact only in the transaction that created it (`created_txid` and the trigger `skill_evidence_skills_require_new_fact`), so a stored fact is never widened afterwards.
|
|
- A fact keeps its source, event, result, attribution, date, visibility, and trust, and tells a claim from a measurement. `kind` is `claim` (trust 0, a statement that nothing confirmed separately) or `measurement` (trust 1 to 3, an observed result); a CHECK ties each kind to its levels. Only measurements are written today, so no claim is stored and the profile claims (trust 0) are not listed. `source_type` is `assessment_result` and the event and the result are the attempt, because a result is keyed by its attempt (`result_id` is a foreign key to `assessment_attempt_results` with the owner, and a cascade removes the fact with its result or account). `attribution` is `personal` (the team values of the PRD are reserved by the CHECK). The result part is the grade that was passed, the basis (`synthetic_demo`), and the calibration (`uncalibrated`), copied from the category decision of the result: a demonstration category is shown as one.
|
|
- Trust 1. An online assessment is unproctored and nothing confirms who answered, so the projection writes trust 1 (the PRD level without a reliable confirmation of the identity or authorship). A CHECK allows only 1 or 2 for this source, never the in-person level 3; 2 is reserved for a result tied to a confirmed identity, which no flow produces yet. `domain.EvidenceTrustOnlineUnconfirmed` and the SQL value are kept equal by the integration test.
|
|
- Which results qualify. One SQL predicate (`skill_evidence_result_qualifies`) says that a result is evidence: a real result (`root` or `corrective`) of the basic mode, version 2, with the outcome `confirmed`, and a category decision with the status `assigned` or `unchanged`, that is, a reviewed synthetic source. A result that passed but had no reviewed source (`not_eligible`, for example with the demonstration gate off) is not evidence, a failed attempt is not evidence and is never shown as a failure, and an express training run (`demo_express`, a version 1 result of the mode `demo_express`) is never evidence. A lower passing result under a higher category (`unchanged`) is a fact of its own: the grade was passed, and the category stays.
|
|
- Why a stored projection written by the database, not a derivation on read. Decision: a trigger on `assessment_attempt_results` calls `skill_evidence_project_assessment_result` after the insert of a result, in the transaction that finalizes the attempt, and the migration projects the results that already exist with the same function. Reasons: the atomicity with the result and the category holds without a change to the finalization code; no write path (a command, a repair, a future import) can store a qualifying result and forget its evidence, or the reverse; a fact needs state that a derivation cannot carry (the candidate's visibility, tags from other events); and every read touches only the projection, so no query of the evidence names a result, an answer, an attempt, or a review (a test reads the query files and fails on it). The cost: the rule lives in SQL as the category guards do, the projection must be rebuilt by the function if the rule changes (the function is idempotent, and an integration test truncates the projection and rebuilds it), and the facts duplicate three values of the result. A guard trigger refuses a fact whose result does not qualify or does not match the fact, even through a direct write, and the table refuses every change but `visibility`. Rolling the migration back drops the projection, which is derived, and applying the migration again rebuilds it; but the rollback refuses (`skill_evidence_retained`) while any fact is hidden, because hiding is the candidate's decision and no result can bring it back. Known risks: a trigger failure rolls the finalization back with it, which is the intended atomicity (a result without its fact is never stored); and a real version 2 result whose specialization is outside the closed skill list would fail the backfill of the migration and the trigger, so a new specialization needs a change of the list in the same migration that admits it.
|
|
- The candidate reads `GET /api/v1/me/evidence`: own facts only, newest first, the hidden ones with `visibility` `hidden`, a cursor bound to the candidate (the cursor of the privacy lists), `Cache-Control: no-store`. The fact names the result that the candidate can open at `GetMyAssessmentResult`.
|
|
- The organization reads `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`. The evidence is a section of the card, so the read runs the checks of the card read in one transaction: verified employer, active membership, effective C2 publication, the hiding of this organization, the minimum cohort, and the card must show at least one category after the cohort rules (`candidateview.Service.AuthorizeCategoriesSection`, which returns the categories of the card, each with its grade). Then the statement `ListOrganizationVisibleEvidence` repeats the barrier: it selects from `candidate_effective_publications`, excludes the candidates that hide the organization with `NOT EXISTS`, requires the `categories` field in the published fields, and returns only visible measurements. It returns one fact for each category of the card: the earliest fact that passed exactly the confirmed grade of that category, so a lower grade or a retake adds nothing, and only the skill of the category, never the other tags. A closed or revoked publication, a hidden organization, an unknown handle, a suppressed card, and a card without categories answer one 404; a hidden fact gives an empty list, not an error. The answer is an allowlist: the skill, the passed grade, the trust level, the year of the event (`observed_year`), and the basis and calibration of the method (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and tell the organization that the fact is a demonstration, not a validated measurement (they add no fingerprint). It has no identifier of the fact, the event, the result, or the candidate, no month or exact time, no source, and never an answer, score, item, failure, signal, or review band. What can and cannot be linked: no key joins the answer to a person, but it is not unlinkable. The skill, grade, trust, and year, together with the other values of the card, can narrow a small pool of candidates, and the minimum cohort of the card does not cover the year. The read consumes the card-view quota under the distinct-card rule and is recorded in the access history with the field `categories`, so the candidate sees it.
|
|
- Scope of the consent C2. Publishing the `categories` field now sends an organization the confirmed category and one supporting assessment fact for it (skill, grade, trust level, year, and the demonstration labels). The candidate sees the same section in `GetMyCardPreview` (`evidence`), which applies no organization or cohort, so an organization can receive less. The C2 consent text was written before this section existed, and whether it needs a new version for it is a decision for the owner and the lawyer; this change does not touch the consent texts.
|
|
- Express and failure. Reading the evidence before and after an express run shows the same list, the database refuses a fact whose result is an express run or a failed attempt, and an express run is not in the category, hence not in the card cohort. There is no percentile or ranking cohort in this release; when they appear they must read the same predicate.
|
|
- Contract checks. `TestEvidenceOperationsFollowTheConventions`, `TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements`, `TestNoOrganizationOperationReachesRawAssessmentData`, and `TestEvidenceWalkReachesTheEvidenceFamily` (Go) and `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) walk every organization operation and the candidate list through all references and fail on an assessment, signal, or review schema, or on a raw answer, score, or failure property.
|
|
- Not implemented: an operation to hide or show a fact (the column and the guard exist; no HTTP operation changes it), claims from the profile as facts, facts from FSP or other sources, revocation of a source, a trust level above 1, the use of evidence in the Passport PDF, and retention. Whether the evidence should need its own card field instead of `categories` is open.
|
|
|
|
## Matching and explanations
|
|
|
|
Implemented as a deterministic search without ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. There is no new table, migration, or query file: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule.
|
|
|
|
- Access before ranking. The search is one transaction. The owner role is checked under the membership lock before any card is read. `ListVisibleCards` then runs the checks of a card read: verified employer, then `ListVisibleCandidateViewSources`, which selects from `candidate_effective_publications` (published and backed by an unrevoked C2) and excludes the candidates that hide the reading organization with `NOT EXISTS` over `candidate_hidden_organizations`; then the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five. The list is therefore exactly the set of handles that `GetOrganizationCandidateCard` opens at that moment: a card that the cohort rules suppress is not searched, a revoked C2, a closed publication, or a hidden organization takes effect on the next request, and nothing is cached or stored. The permitted evidence is read only through the organization-safe batch query `ListOrganizationVisibleEvidenceBatch` (one statement for the whole candidate set, with the barriers of the single read: the effective publication view, `NOT EXISTS` over the hiding, the `categories` field, visible measurements), and only when the request names skills. The locks are those of the card read and nothing else is locked; the writes of the search are limited to the candidates it returns.
|
|
- Owner only. For the MVP milestone the active owner of the organization searches. The HTTP boundary refuses every other role (`ownerCompanyOperations`), and the usecase repeats the role check under the membership lock, so a membership alone grants nothing. The full role and assignment matrix is later work and must not widen rights by one membership.
|
|
- Charged like card reads. A search returns card content (the confirmed category with its strength, the declared grade, the stack, the experience band, the work formats, and the explanation), so it passes through the same allowance as a card read. The whole visible bank is ranked, and then each group is cut to `max_results_per_group` of the policy version (demo value 10, so at most 30 reveals for one search, below the 50 distinct card views per day of tier E0); no total is returned. Walking the output in the order `main`, `near`, `unconfirmed`, each newly revealed candidate is reserved through the company quota port (`candidateview.SearchViews.Reserve`, the same `ReserveCardView` as a card read: idempotent per organization and candidate inside the window, so repeating the search or opening the card afterwards does not charge twice), and the candidate's access history gets one `card_viewed` entry per search with the fields actually returned (`SearchViews.Record`), all in the transaction of the search. When the allowance ends, the output stops at the first refusal: the entries already paid for are returned, `truncated` is true, nothing is written for the rest, and there is no error. `truncated` is also true when a group exceeded its limit; it carries no count. Opening a card is still the read for the full card.
|
|
- One entry per candidate specialization, built from the card the organization is allowed to see. A specialization is confirmed only when the card shows its category (`categories` published and not generalized away); a role that the self-assessment lists as unconfirmed is an unconfirmed entry; a role marked confirmed whose category the card does not show gives no entry, because a result cannot claim a confirmation the candidate did not publish. The same handle can therefore be confirmed in Backend and unconfirmed in Networks, and a Backend confirmation never changes the Networks entry. The status of an entry follows the specialization of the request: a need with a confirmed specialization and a `specialization` filter both restrict it, and two different values leave nothing. A need without a confirmed specialization searches all of them and returns each specialization separately.
|
|
- Filters, all applied before scoring. `confirmed_grade`, `confirmed_category`, and `confirmation_status: confirmed` keep only confirmed entries; a declared grade never satisfies them. `declared_grade` is a separate claim. `stack` requires every named tag in the card and also counts as a required skill of the request. `conditions.work_formats` needs one common format, and `conditions.salary_compatibility` needs the same value; an unknown card value never satisfies a condition. An unconfirmed category alone hides nothing: without a confirmed filter the declared specializations are listed.
|
|
- Requested skills. The skills of the Cov come from the confirmed required (weight 2) and desired (weight 1) skills of the need snapshot, with the tags of the `stack` filter as required. A code is counted once however often it is repeated. A skill without a taxonomy code has no reviewed mapping, matches nothing, and is a gap. An empty request uses the neutral Cov 0.5 instead of dividing by zero. The need is read by `requirements_version` (`GetVersion`); a general version that only changed the title is not a requirements snapshot and answers 404, and the snapshot of an older requirements version stays searchable and unchanged.
|
|
- Evidence of a skill. Each requested skill takes the best product of the trust, attribution, and relation coefficients over the permitted evidence, not their sum. The evidence is the stated stack tags of the card (trust 0, a claim) and, for a confirmed entry, the one assessment fact that supports its category (trust 1, personal). The relation is exact for the same code, broader for a specialization over a technology, and narrower the other way, by the `skill_taxonomy` of the policy version (demo: `backend` over `docker`, `go`, `kafka`, `postgresql`; `devops_sre` over `docker`); a version without a taxonomy relates only equal codes, so the version fully determines the result. The taxonomy is a demonstration mapping, not a measured one. An online Backend result is worth 0.6 * 1.0 * 0.4 = 0.24 for a requested Go and a stated Go tag 0.25; the near threshold is 0.25, so a candidate whose only evidence for a required technology is a Backend assessment is always in `near` for it, and a stated tag alone is enough to be in `main`. That consequence of the PRD values is an owner question. Repeating a tag or a skill adds nothing.
|
|
- Components and groups. `Cov` is the weighted mean of the contributions; `Dom = 0.5` (the anonymous card carries no domain) and `Sem = 0.5` for every entry (no ML), both named in `unknown_flags`; `T = 0.5` with a null percentile and the flag `cohort_below_30`, which the search proves instead of declaring: it counts the candidates who hold each returned category from a source other than a synthetic demonstration (`CountRealComparableCategories`, counts only) and compares the count with `percentile_min_cohort`; today the count is 0 because every stored category is a synthetic demonstration, which is never mixed with real results. A real cohort at the minimum would need the theta of its members, which the organization-safe projection does not carry, so the search never fails for it: T stays the neutral 0.5, the percentile stays null, the reason becomes `percentile_not_computed` instead of `cohort_below_30`, and the search logs one warning for each such category. Only the categories of the entries that passed the filters are counted; `V = 0` because no competition data exists, which is neither a penalty nor an unknown; `Fr = Rsp = 0.5` with the flags `no_freshness_history` and `no_response_history`. A confirmed entry with a required skill below the near threshold (0.25) is in `near`, otherwise in `main`; an unconfirmed entry is in `unconfirmed` with only Fit and Coverage, computed by a separate path that never calculates theta, T, P, a percentile, or S. The absence of FSP is not scored anywhere.
|
|
- Order and rounding. Scores are integers in micro units (six decimals), the shares are basis points, and the products are exact integers, so the same data and policy give the same order on every platform. `main` and `near` sort by S, then Cov (both descending), then the internal candidate identifier ascending (then the specialization code, which only separates two entries of one candidate); `unconfirmed` sorts by Fit, then Cov, then the identifier. The identifier never leaves the server, and the groups are not merged on one scale.
|
|
- Explanation. The summary and the flags are built from the same computed contributions: per skill group `supports` (every skill carried by a measurement at or above the threshold), `declared_only` (only stated tags), `partial` (a mix, or measurements below the threshold), or `gap` (nothing), plus the confirmed category, the declared grade, the work-format match against the need or the filter, and the salary compatibility. It uses bounded codes only, never free text, a contact, a candidate location, a salary value or minimum, a failed attempt, or a reason for withheld data. An unknown component appears only in `unknown_flags`.
|
|
- Policy. The search reads the effective `product` policy at the application time and its `matching` section. A policy without the section fails closed with an internal error (the ProblemCode enum has no code for a temporarily unavailable dependency, and none is added); the error log says that the effective product policy has no matching section and names the `policy-publish` operator command, the backend logs a warning at startup while the section is missing, and [DEPLOY.md](DEPLOY.md#match-search-policy-on-a-stand) describes the command. The response does not name the policy version, and no search is stored.
|
|
- Concurrency. The reservations take the exclusive organization lock of the company quota port. A membership check before them holds only a share lock on the same row, and two searches of one organization would deadlock on the upgrade, so the search takes the organization lock first (`CompanyQuotaRepository.LockOrganization`, the documented order; it is FOR NO KEY UPDATE, so readers queue behind each other but the foreign-key lock of a candidate's own hide, which holds the candidate row and then needs the organization row, is not blocked, and the reservation itself still takes FOR UPDATE in the same transaction) and the charges of one organization are serialized. A change of the visible cohort while it is being locked (`ErrConcurrentVisibilityChange`) repeats the whole search up to three times, and its writes roll back with the failed attempt. The card read (`GetOrganizationCard`) and the evidence section (`AuthorizeCategoriesSection`) take the same exclusive lock first, before any share lock, for the same reason: before this order two simultaneous card reads of one organization deadlocked (SQLSTATE 40P01). `TestMatchSearchOverHTTP` runs concurrent card reads, evidence reads, and searches of one organization and checks for no deadlock and one quota row for each candidate.
|
|
- Accepted residual risks. `truncated` is one bit about the size of the visible bank (it says that more than the limit or the allowance exists) and the response time grows with the bank, so both leak a coarse size to the owner. The bit is bounded by the group limit and no count is returned; the risk is accepted for the demonstration and is listed with the owner questions.
|
|
- Checks. `internal/usecase/matching` unit tests (formulas with hand-computed values, ties and ordering, filters, explanation, the cut and the charge of the output), `internal/domain/policy_matching_test.go` (document round trip, strictness, validation), `v1/matches_test.go` (mapping and problems), and the integration test `TestMatchSearchOverHTTP` against PostgreSQL: hidden candidates and two organizations, a need and its edited requirements, repeated identical responses, Backend confirmed and Networks unconfirmed for one handle, a profile published without a grade through the real profile, consent, and publication operations and removed by a C2 revocation, a candidate alone in its cohort, no contact or identifier in the body, the charge and the access history of a search, an organization with an allowance smaller than its bank, the group limit, the batch evidence read, two concurrent searches under one allowance, the demo group limit, the policy taxonomy, the denials, and the policy without the section.
|
|
|
|
Not implemented: the percentile and a real T (they need the theta of a comparable real cohort of at least 30 people); the competition value V and the FSP data; the domain of a candidate; freshness and responsiveness histories; semantic similarity and the ML fallback flag beyond the neutral value; the stored `search_run` snapshots, refinement, comparison, and the shortlist; paging beyond the group limit; and the use of the grade of a need as a filter. Sending an invitation from a search result is not implemented either, so the revocation of C2 after an invitation is not checked here; the draft of an invitation resolves a handle of the search result through the same visibility barrier (see [Invitation drafts](#invitation-drafts)).
|
|
|
|
Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent. This is the first model, not an optimized or measured ranking: the plan compares keyword search, the verified-skill baseline, and an ML variant, adds a semantic signal only after an experiment, and never treats its score as a probability of hiring success.
|
|
|
|
Store each search as a search_run with its company, original need, filters, ranking version, and parent version. Refinement creates another snapshot. search_items stores order, scores, and profile versions without contacts. An old snapshot does not preserve access: hidden or removed profiles disappear, stale ranking is marked, and retention is bounded. This is planned; the implemented search stores nothing.
|
|
|
|
## ML, documents, and background jobs
|
|
|
|
Planned ML operations are resume analysis, need analysis, and, after the baseline, embeddings and limited reranking. Go sends only allowed inputs and a short candidate list. Responses are limited to known IDs and validated against schema and version. ML failure falls back to the baseline. Models cannot set categories or expose contacts.
|
|
|
|
Planned PDF flow: limit size, page count, and upload rate; validate file type and owner; save a source version; create a job in the same transaction; extract text in an isolated resource-limited environment; mask contacts; request a structured result; validate its size and versions; show proposed fields for candidate approval. A scan without a text layer reports that state and offers manual entry; OCR is a separate extension. Never log full resume text or traces.
|
|
|
|
Resume text is untrusted data, not an instruction to tools. ML does not follow arbitrary links, run commands, or verify whether employment claims are true. Each proposed field records its evidence and limitations.
|
|
|
|
A standardized PDF is required in the product even when profile entry is manual. PDFRenderer consumes structured profile data. The planned approach is controlled HTML and isolated headless Chromium with Cyrillic fonts, no external network fetches, and no user-supplied HTML.
|
|
|
|
Jobs that only need to run at a due time use the implemented runtime in [Scheduled jobs](#scheduled-jobs). Future ML and document jobs, which a user waits for, use queued, running, succeeded, failed, and cancelled states, an attempt limit, available_at, lease/heartbeat, and a safe error code. Claims are atomic. An expired lease permits retries; operation key, document version, and lease token prevent stale workers from overwriting newer results. Computation may repeat; a business effect must not. Retries are bounded and use backoff.
|
|
|
|
Long operations return 202 and a job ID. The UI polls with a widening interval and stops after completion or page exit. The browser never calls ML directly. Routine tests do not download a model or require GPU. Model, license, inference budget, and production latency are unselected.
|
|
|
|
## Identity, FSP, and privacy
|
|
|
|
The initial product plan uses email/password, email verification, and server-side PostgreSQL sessions. Browser cookies are Secure, HttpOnly, and SameSite; mutating requests use CSRF protection. Hash passwords with a suitable KDF. Tokens are random and expire; store their hashes. Require email verification before publishing a candidate or sending invitations.
|
|
|
|
Future FSP identity linking requires provider verification. A manually entered identifier or matching email is not enough to merge accounts. The brief supplies no real FSP API, so development starts with a fixture provider and a project-owned DTO. If organizers provide Keycloak/OIDC, add Authorization Code + PKCE and validate issuer, state, nonce, audience, and redirect URI. Lincodex still owns roles and contact grants.
|
|
|
|
The brief references Russian Federal Law 152-FZ. The system design calls for separate processing/publication consents, revocation, transfer controls for ML, and retention/deletion periods. Architecture documentation does not prove legal compliance. Agree on data handling before using real personal data; use synthetic profiles for the demo.
|
|
|
|
### Identity storage
|
|
|
|
Identity storage is implemented in migration `backend/db/migrations/00002_create_identity_tables.sql`, the queries in `backend/db/queries/identity.sql`, the domain types, outbound ports, and the PostgreSQL adapter. The backend API implements registration, verification resend, `ConfirmEmail`, login, and basic current-session operations. The frontend registration and confirmation screens are implemented; see the [API contract](../../api/README.en.md#identity-sessions-cookie-and-csrf).
|
|
|
|
- `users`: UUIDv7 `id`; `email`, the delivery form (trimmed ASCII, letter case as typed, returned as `Account.email`), and `email_normalized`, the unique comparison key (the same address with A-Z lowercased); `password_hash`, an Argon2id v19 PHC string; `scenario` and `onboarding_step` with a CHECK that the step belongs to the scenario; nullable `email_verified_at`; `registration_version`; `last_registered_at` with a partial index over unverified accounts for the planned 7-day cleanup; the optimistic `version`; `created_at` and `updated_at`. The delivery form is kept because RFC 5321 allows a case-sensitive local part: mail goes to the address as typed, while uniqueness ignores letter case.
|
|
- `email_tokens`: `token_hash` (SHA-256, 32-byte `bytea`, unique), `purpose` (`email_verification`; a CHECK lists allowed purposes, so password reset can be added later), `user_id`, the `registration_version` the token is bound to, `created_at`, `expires_at`, `consumed_at`, and `invalidated_at`. Migration 00014 adds `pending_password_hash`, `pending_scenario`, and `pending_onboarding_step`, so each token carries its registration data. A CHECK allows at most one of consumed and invalidated.
|
|
- `sessions`: a UUIDv7 `id` that never leaves the server, `token_hash` (SHA-256 of the cookie value, unique), `user_id`, `created_at`, `last_seen_at`, the absolute `expires_at`, and `revoked_at`. No IP address or user agent is stored.
|
|
- Tokens and sessions reference `users` with `ON DELETE CASCADE`. Consent records reference it with `ON DELETE RESTRICT` instead; see [Consent ledger](#consent-ledger). CHECK constraints repeat the domain rules as a backstop: the ASCII address and its key, the PHC format, and timestamps (verification, consumption, invalidation, and revocation) not earlier than `created_at`.
|
|
|
|
Decisions:
|
|
|
|
- Email addresses are ASCII only, because the mailer has no SMTPUTF8 support. `domain.NewEmailAddress` rejects any non-ASCII character, including homoglyphs and fullwidth forms, with `ErrInvalidEmailAddress`, which the registration handler answers with 400 `validation_failed` whether or not an account exists. Internationalized domains are accepted only in their punycode form (`xn--...`). The key lowercases A-Z only; the database checks it with `translate()`, which does not depend on the collation, unlike `lower()`. Unicode addresses are future work: they need IDNA ToASCII for the domain, a rule for Unicode local parts, and SMTPUTF8 delivery. Rows are read back with `domain.RestoreEmailAddress`, which checks only that the address and key match, so a stricter rule later does not make existing accounts unreadable.
|
|
- The database stores hashes, never passwords or raw tokens. A token carries 256 bits from crypto/rand, so an unsalted SHA-256 cannot be reversed by guessing and a lookup stays one index probe; passwords need the slow Argon2id KDF instead. `bytea` keeps the digest at half the size of hex text, with an exact length CHECK and no letter-case variants. `domain.SecretToken`, `domain.PasswordHash`, and `domain.EmailAddress` redact themselves in `fmt` (every verb) and `slog` output, so printing a `domain.User` shows neither the address nor the hash; explicit accessors return the real values. Unmapped PostgreSQL errors from the identity repositories keep only the SQLSTATE and the constraint name, because the message and detail can quote row values.
|
|
- Enum-like columns are text with CHECK constraints rather than PostgreSQL enum types. A new scenario, step, or purpose replaces one constraint in a reversible migration; an enum value cannot be removed and cannot be used in the transaction that adds it.
|
|
- Every stored time comes from the application clock that the caller passes, so deadlines and the checks against them use one clock. Repositories reject the zero time.
|
|
- There is no CSRF column. `GetCurrentSession` returns the token after a reload: the server derives it with domain-separated HMAC-SHA-256 from the cookie token and `IDENTITY_KEY_SECRET`, so it needs no database storage. Comparison is constant-time; the session token itself is stored in the database only as a SHA-256 hash.
|
|
|
|
What the ports guarantee:
|
|
|
|
- `UserRepository.Create` returns `ErrEmailTaken` for a duplicate key. `UpdateRegistration` stores the result of `domain.User.ReRegister` only when the stored `version` matches and the email is unverified; the same statement advances `version` and `registration_version` by one, so no caller chooses the registration version, and deletes the registration C1 of the earlier registrant (see [Consent ledger](#consent-ledger)). `MarkEmailVerified` applies only to an unverified account with the given registration version. Both return `ErrUserVersionConflict` otherwise.
|
|
- `EmailTokenRepository.Consume` is one `UPDATE ... RETURNING` that requires an unconsumed, uninvalidated, unexpired token. Concurrent callers queue on the token row lock; under READ COMMITTED each waiter re-checks the row after the holder finishes, so exactly one succeeds and, if the holder rolls back, a waiter can still succeed. A miss is reported as `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (replaced, or issued for an earlier registration version), or `ErrEmailTokenExpired`. `InvalidateActive` marks every earlier token of a user and purpose.
|
|
- Consume compares the token's registration version with the account only as its statement reads the account, without locking it, so it cannot see a re-registration that commits right after it. The binding of a token to the current registration therefore holds only when a confirmation calls `MarkEmailVerified(token.UserID, token.RegistrationVersion)` in the same transaction and rolls back on `ErrUserVersionConflict`; the rollback also restores the token, which is then superseded. The confirmation usecase maps that outcome to `verification_token_invalid`.
|
|
- `SessionRepository.FindActive` and `Touch` take the idle timeout from the caller and accept only an unrevoked session before its absolute deadline and within the idle timeout. `Touch` coalesces writes with a cutoff equal to the smaller of one minute and half the idle timeout, so frequent requests do not rewrite the row and even the shortest supported idle timeout can be extended; it never moves `last_seen_at` back or revives an ended session. `Revoke` and `RevokeAllForUser` set `revoked_at`.
|
|
- `DeleteUnverifiedRegisteredBefore` deletes one batch of unverified accounts, oldest first, and never waits for a lock. It locks the candidate accounts, their tokens, their sessions, their mail requests, their mail deliveries, and their consent records with `FOR UPDATE SKIP LOCKED` and skips every account whose row, or any token, session, mail request, delivery, or consent row, is locked by another transaction, such as a re-registration, a resend, a confirmation, the delivery consumer, or a delivery worker; skipped accounts stay for the next run. The mail requests, deliveries, and attempts go with the account by cascade; the consent records, which restrict the delete, are deleted explicitly in the same statement.
|
|
- `postgres.IdentityStore` runs the same repositories outside a transaction. Called with a context from a `Transactor` callback, it returns `ErrNestedTransaction` instead of committing on a separate connection.
|
|
- Unique and foreign key violations map to `ErrEmailTaken`, `ErrTokenHashConflict`, and `ErrUserNotFound` by SQLSTATE and constraint name, never by error text.
|
|
- Lock order: an operation that changes both an account and its tokens locks the tokens first. A confirmation consumes the token and then verifies the account, so a re-registration or resend calls `InvalidateActive` before it updates the account or inserts a token; the opposite order can deadlock. The cleanup is the only exception: it locks the account before the tokens and sessions, which is safe because each of those locks uses SKIP LOCKED and never waits. A deadlock (SQLSTATE 40P01) or serialization failure (40001) that still happens is reported by `Transactor.WithinTransaction` and the identity repositories as `outbound.ErrTransactionConflict`; nothing was committed, and the usecase or job may retry the whole operation with backoff while staying idempotent.
|
|
|
|
### Password hashing
|
|
|
|
Implemented and tested: registration and login use the hasher created from configuration.
|
|
|
|
- `domain.Password` holds the password normalized to Unicode NFKC. `domain.NewPassword` applies the registration policy, 15 to 128 code points after normalization; `domain.ParseLoginPassword` accepts 1 to 128. Before normalizing, both reject raw input over 512 bytes (128 code points of at most 4 UTF-8 bytes, so every value the contract schema accepts fits) and invalid UTF-8. These checks run before any hashing and fail with `domain.ErrInvalidPassword`, naming the rule but never the value. The blocklist of common or breached passwords is a separate planned check.
|
|
- The `outbound.PasswordHasher` port (`port/outbound/password.go`) has `Hash`, `Verify`, and `VerifyDummy`; the `adapter/secondary/argon2id` adapter implements it with `golang.org/x/crypto/argon2`. New hashes use Argon2id v19 with m=65536 KiB, t=3, p=4 (the second recommended option of RFC 9106, above the OWASP baseline of 19 MiB, t=2, p=1), a 16-byte salt from crypto/rand, and a 32-byte key, encoded as `$argon2id$v=19$m=65536,t=3,p=4$<salt>$<key>` in unpadded base64, the format that `domain.NewPasswordHash` and the `users_password_hash_format` CHECK accept. One hash took about 26 to 33 ms on an Apple M5 development machine (`BenchmarkHashRecommendedParameters`, also with one CPU); this is not a production latency figure.
|
|
- Memory budget: derivations share a weighted semaphore (`golang.org/x/sync/semaphore`) of `PASSWORD_HASH_CONCURRENCY` times 64 MiB, and each holds its own memory parameter while it runs. The setting accepts 1 to 4; when unset it is the smaller of 2 and GOMAXPROCS, which Go derives from the container CPU limit. Compose passes `PASSWORD_HASH_CONCURRENCY=1` for the 1-CPU backend container, so hashes run one at a time with 64 MiB live; the maximum of 4 needs 256 MiB. Memory of a finished derivation is garbage until the next collection; `GOMEMLIMIT=600MiB` in Compose makes the collector reclaim it before the heap reaches about 78% of the 768 MiB container limit, and the rest is left for stacks and non-heap memory. Waiting calls queue in FIFO order, bounded only by their request context; identity HTTP limits are described in the server-side sessions section.
|
|
- `Verify` parses the stored PHC string strictly and recomputes the key with the stored parameters, salt, and key length, then compares in constant time. A wrong password returns `outbound.ErrPasswordMismatch`. A malformed hash, or one outside the stored-hash bounds (memory from 8 KiB per lane to 128 MiB and within the hashing budget, 1 to 16 passes, 1 to 16 lanes, a salt of 8 to 64 bytes, a digest of 16 to 64 bytes), returns `outbound.ErrPasswordHashCorrupt` without any derivation, so a crafted row cannot demand unbounded memory or time. `ErrPasswordHashCorrupt` wraps `domain.ErrInvalidPasswordHash`, which the repository returns for a stored hash that fails `domain.NewPasswordHash`. On a match `needsRehash` reports parameters, salt, or key length that differ from the current ones; login does not yet update such hashes automatically.
|
|
- `VerifyDummy` runs `Verify` against a hash with the current parameters, a random salt, and a random digest, and returns `ErrPasswordMismatch` (or the context error). Login calls it for an unknown email and an invalid stored hash, so those branches also perform a full Argon2id verification.
|
|
- Login answers `invalid_credentials` for an unknown email, a wrong password, and an invalid stored hash (`errors.Is(err, domain.ErrInvalidPasswordHash)`, from the repository or from `Verify`); for an invalid hash it also logs an error and calls `VerifyDummy`. A valid password for an unverified account answers `email_not_verified` and creates no session. Verification time is not uniform: unknown emails and corrupt hashes run `VerifyDummy`, while stored hashes with different Argon2id parameters take different amounts of time.
|
|
- `identity.Credentials.HashNewPassword` validates a new password and only then hashes it; registration calls it on every branch before looking up the email.
|
|
- Errors and logs never contain the password or the hash. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken`, and `domain.EmailAddress` redact themselves in `fmt`, `slog`, and JSON output, and keep their value behind a pointer, so printing an enclosing struct, even through an unexported field, shows only an address.
|
|
|
|
### Server-side sessions
|
|
|
|
Login, current-session and current-account reads, and logout are implemented in the backend. Every contract-protected operation passes through the session boundary, which resolves a verified principal from an active PostgreSQL session; consent and organization handlers implement their documented operations. Contract operations without an implemented business handler answer 501 after security and request validation. Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`) requires the sole `Origin` value to exactly match `APP_PUBLIC_URL`. Protected unsafe operations also require the session-bound `X-CSRF-Token`. Origin is checked at the HTTP boundary and does not trust `Host` or forwarded headers. The CSRF value is a domain-separated HMAC-SHA-256 derived from the session token, bound to that token, and compared in constant time. `GetCurrentSession` returns it again after a page reload. GET `/api/v1/identity/sessions/current` returns the current session and account, GET `/api/v1/identity/me` returns the current account, and DELETE `/api/v1/identity/sessions/current` revokes the session. Guests and unverified sessions answer 401; a valid session with missing or wrong Origin or CSRF on a protected unsafe operation answers 403 `csrf_check_failed`.
|
|
|
|
The cookie is named `__Host-lincodex_session` and has `Path=/`, `Secure`, `HttpOnly`, and `SameSite=Strict`, with no `Domain`; `Expires` and `Max-Age` point to the absolute session expiry. PostgreSQL stores only the SHA-256 hash of the random cookie token, never its value; IP addresses and user agents are not stored. `IDENTITY_SESSION_IDLE_TIMEOUT` defaults to `24h` and accepts `1m` to `30d`; `IDENTITY_SESSION_ABSOLUTE_LIFETIME` defaults to `168h` and accepts `1m` to `365d`. The idle timeout cannot exceed the absolute lifetime; invalid values stop startup. Active requests extend the idle deadline, not the absolute deadline.
|
|
|
|
`IDENTITY_KEY_SECRET` must contain at least 32 bytes and stay the same across backend restarts and instances. It also derives the CSRF key with the purpose label `lincodex/identity/session-csrf/v1`; changing the shared secret invalidates old CSRF values but does not revoke PostgreSQL sessions, and `GetCurrentSession` returns the new value. After a successful password check, creation of a new session and revocation of an incoming active session commit in one transaction. A failed login does not revoke the old session. Logout clears an expired or revoked cookie; an Origin or CSRF failure neither revokes nor clears a valid session.
|
|
|
|
### Consent ledger
|
|
|
|
Consent storage, registration C1, and the settings read and mutation handlers are implemented: migration `backend/db/migrations/00009_create_consent_ledger.sql`, the deletion-request table in `00018_create_account_deletion_requests.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, ports in `backend/internal/port/outbound/consents.go`, and handlers in `backend/internal/adapter/primary/http/v1/consent.go` ([api/README.en.md](../../api/README.en.md#consents)). Public `GET /api/v1/identity/consent-texts/c1` returns only C1; verified sessions can read C1/C2/C3/C5 text and their own history, grant supported purposes, revoke consent, and request account deletion. Registration records C1 in the account creation or re-registration transaction; confirmation checks the C1 record for the token's registration version. The C4 invitation-acceptance handler and the account-deletion worker are not implemented.
|
|
|
|
The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation of one never changes another.
|
|
|
|
`consent_texts` holds the published texts: `purpose`, `version` (the contract's `ConsentTextVersion`), the exact `body`, `body_sha256` checked against the body by a CHECK, `kind` (`demo` for synthetic texts without a legal review, `operator` for texts of the actual operator), and `published_at`. The current text of a purpose is the latest publication not after the grant time. Texts are immutable: a trigger refuses UPDATE, DELETE, and TRUNCATE (`consent_texts_immutable`), and a changed text is a new version. The migration publishes demo version `cN-2026-10-01` of every purpose; the operator's texts arrive as new versions in a later migration before real data are accepted (PRD 7.3). Only the C4 text contains the placeholder `{organization}`; `ConsentText.RenderForOrganization` fills it in.
|
|
|
|
`consent_records` is the append-only ledger. One row per grant: UUIDv7 `id`, `subject_id`, `purpose`, `text_version`, `text_hash` (SHA-256 of exactly the text the subject saw, 32 bytes), `source` (`registration` for C1 only, `consent_settings` for C1-C3 and C5, `invitation_acceptance` for C4 only), `registration_version` for registration-source C1 only, `granted_at`, and the one-time revocation stamp `revoked_at` with `revocation_source` (`consent_settings` or `support_request`). A C4 row also has `organization_id`, `organization_name` (the name the shown text carried, a snapshot of 1-200 characters), the canonical `field_set` (one to four distinct `ContactFieldKind` values in ascending byte order), `invitation_id`, and `invitation_terms_version`; every other purpose must leave them NULL (`consent_records_c4_scope`). Request metadata such as IP addresses or user agents is not stored: the PRD asks for the version, hash, time, subject, and revocation event, and the extra data would be personal data without a purpose.
|
|
|
|
Decisions:
|
|
|
|
- Text binding. A foreign key on (`purpose`, `text_version`) refuses a version that was never published for the purpose, and a BEFORE INSERT trigger refuses a version published after the grant time (`consent_records_text_published`). For C1-C3 and C5 a second foreign key over a generated column requires `text_hash` to equal the hash of the published text. For C4 the same trigger requires `text_hash` to equal the SHA-256 of the published text with `organization_name` filled in (`consent_records_c4_text_hash`). The domain computes that hash itself in `domain.NewContactConsentGrant` from the published `ConsentText` and the name, so no caller supplies hash bytes and a client can invent neither a version nor a hash. The stored name is the snapshot that proves the shown text; a later rename of the organization does not change it, and the read model returns it as `ConsentOrganization.name`.
|
|
- History. The only UPDATE a trigger allows is the revocation stamp on an unrevoked row with every other column unchanged (`consent_records_immutable`). A newer text version is a new row next to the older one; a grant after a revocation is a new row. The state (`active`, `superseded`, `revoked`) is computed by the queries, never stored: among the unrevoked rows of a subject and purpose other than C4, the row granted last (by `granted_at`, then ID) is `active` and the others are `superseded`, whatever their versions. The ledger therefore accepts any published version, and the grant usecase `consent.Service` checks that the version is the current text before it calls `Grant`. A partial unique index keeps one unrevoked row per subject, purpose, and version, so a repeated or concurrent grant returns the existing record; a unique index on `invitation_id` keeps one C4 row per invitation, revoked or not, so a revoked C4 never comes back.
|
|
- Revocation. `ConsentLedger.Revoke` stamps every unrevoked row of the purpose, superseded rows included, and for C4 only those of one organization. A repeat finds nothing and keeps the first stamp. A revocation time before the grant time of a row, from clock skew between instances, is stamped at the grant time (`greatest`), so the `consent_records_revocation_stamp` CHECK stays a backstop. C1's `POST /api/v1/me/account-deletion-requests` stores one durable active request, revokes C1, and appends an outbox event in one transaction; repeating it returns the same request, and a later C1 grant does not cancel it. Account deletion is not synchronous. C2 revocation locks a publication only when it still references one of the records revoked in that transaction, then writes a privacy-history event atomically. The stored publication remains linked to that immutable C2 record; the read model hides its fields and reports the effective state as closed with reason `consent_revoked`, and a later C2 grant cannot reopen it. Repeating a revoke or revoking a later C2 record does not create another closure event for the old publication. C3 revocation does not block account or profile use; a separate manual-assessment request is planned but is not implemented. C4 revocation is scoped to the requested organization, and each bounded outbox intent contains organization and fields copied from the revoked records. C5 revocation makes `HasCurrentConsent` fail closed and writes a stop intent, but there is no external FSP adapter and no external deletion is claimed.
|
|
- Retention and deletion. PRD 7.3 plans to keep consents for three years, which can outlive the account, so `subject_id` references `users` with `ON DELETE RESTRICT`, and a BEFORE DELETE trigger refuses deleting a row whose subject is a confirmed account (`consent_records_retained`). Rows of an unconfirmed account may be deleted, because a registration that the email owner never confirmed is not evidence of anyone's consent: the unverified account cleanup deletes the rows of the accounts it removes in the same statement, and `UpdateRegistration` deletes the registration C1 of the account it re-registers (see below). TRUNCATE fires no row trigger and stays allowed for test isolation. The durable C1 request record and event are implemented, but the worker that performs account deletion and the policy for ledger retention after that deletion are not; the request does not delete an account or ledger by itself.
|
|
- Re-registration. An unverified account keeps its `users.id` when the same email registers again, so the earlier registrant's C1 would otherwise stand for the new one. The `UpdateUserRegistration` statement deletes the C1 rows with the source `registration` of the account it updates, and only when the update applies. This is a binding requirement for registration: the registration usecase calls `UpdateRegistration` and records the new C1 with `consent.Service.GrantAtRegistration`, strictly after `UpdateRegistration`, in the same transaction (see [Consent usecase](#consent-usecase)).
|
|
- C2 and the published field set. A C2 row proves the consent to the publication text, not which fields were published. The published field set and its changes are kept with their times and the C2 record behind each in the candidate visibility history (`candidate_publications` and `candidate_privacy_events`, see [Candidate visibility](#candidate-visibility)). Adding a field scope to C2 rows later is an additive migration and contract change.
|
|
- C4 in a business transaction. `UnitOfWork.ConsentLedger().GrantContact` takes a `domain.ContactConsentGrant`, which only `domain.NewContactConsentGrant` builds and which requires the C4 text, the organization and its name, a non-empty field set, the invitation, and its terms version; `domain.NewConsentGrant` refuses C4. The invitation-acceptance handler is not implemented. When it is added, it must call this port in the transaction that accepts the invitation and writes its audit event; a repeated acceptance must compare the existing scope, and an invitation whose C4 belongs to another subject must return `ErrConsentInvitationTaken`.
|
|
- Cleanup race. The cleanup checks consent rows in its statement snapshot. A consent committed for a candidate account after that snapshot but before the account lock fails the restricting foreign key at the end of the statement (SQLSTATE 23001); the adapter reports it as `ErrTransactionConflict`, nothing is deleted, and the next run sees the consent.
|
|
- Scoping. Every read and revocation takes the subject, and the contract operation takes it from the session, so the read model returns only the caller's own records. Errors of the adapter keep the SQLSTATE and constraint name only, and `domain.ConsentRecord`, `ConsentGrant`, `ContactConsentGrant`, and `ConsentRevocation` show no subject, organization, name, or fields in `fmt` and `slog` output.
|
|
|
|
Legal check items, not decided by this storage: deleting the C1 of never-confirmed accounts against the three-year retention of consents in PRD 7.3; whether C2 is a consent to the distribution of personal data under article 10.1 of 152-FZ, which requires its own consent with the categories of data and may need a field scope on the C2 record; and the operator texts that replace the demo texts.
|
|
|
|
What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWork` and as `postgres.ConsentStore` outside a transaction):
|
|
|
|
- `ConsentTexts().Get` and `Current` read published texts and verify the stored hash on every read.
|
|
- `ConsentLedger().Grant` and `GrantContact` return the new record with `created` true or the existing one with `created` false. An unknown subject returns `ErrUserNotFound`, an unknown version `ErrConsentTextNotFound`, a version published later `ErrConsentTextNotPublished`, and a hash that does not match the published text (for C4 with the stored name) `ErrConsentTextMismatch`; these come from the database and abort a surrounding transaction. A duplicate does not. A grant whose conflicting record was revoked between its two statements returns `ErrTransactionConflict`.
|
|
- `Revoke` returns the rows it stamped. `Current` returns the newest unrevoked C1-C3 or C5 record or `ErrConsentNotFound`; `CurrentContact` returns the unrevoked C4 records of one organization. `List` pages the subject's ledger newest first, optionally by state.
|
|
- `ConsentRevocationEffects.Apply` runs in the same `UnitOfWork` transaction as the ledger revocation. It closes the current publication's effective C2 access only when that publication references one of the revoked records, appends its privacy-history event once, and writes bounded outbox intents from the exact revoked records. A future C2/C4 grant adapter must bind each downstream grant to its source consent-record ID and synchronously close that old grant in this transaction; a later grant may open only a new record-bound grant, never reopen an old one. C5 readers and importers must check the current ledger and fail closed; an outbox message alone does not authorize access or prove that an external system deleted data.
|
|
|
|
### Consent usecase
|
|
|
|
`consent.Service` in `backend/internal/usecase/consent/` is wired through bootstrap and used by registration to check the text version and grant C1 in the create or re-registration transaction. It is built with `consent.NewService(transactor, clock)`, the `Transactor` and application clock the other usecases receive. A nil transactor or clock panics at construction.
|
|
|
|
- Entry points fix the source. `GrantAtRegistration` records C1 with source `registration`; settings grants record C1, C2, C3, or C5 with source `consent_settings`. `RevokeInSettingsInNewTransaction` stamps the subject-scoped ledger rows and applies the publication/history and outbox effects in the same transaction. `RequestAccountDeletionInNewTransaction` stores or returns the one active durable request, revokes C1, and appends its event atomically; a later C1 grant does not cancel that request. Neither operation accepts a source or time from the client. `GrantInSettingsInNewTransaction` and the mutation operations retry transaction conflicts up to three attempts with a short jittered wait, ending immediately when the context is canceled.
|
|
- Re-registration order. For an unverified account that registers again, call `GrantAtRegistration` strictly after `UserRepository.UpdateRegistration` in the same transaction. `UpdateRegistration` deletes the registration C1 of the earlier registrant, and a grant that ran before it would find that record, return it with `Created` false, and leave the account without any C1 once it is deleted. The integration test shows both orders.
|
|
- C1 registration version. Migration `00016_bind_registration_consent.sql` adds `registration_version` only to registration-source C1; other grants must leave it NULL. It backfills old C1 rows from the current account version without using tokens. Re-registration deletes the prior registration C1, so an older grant time or multiple active registration C1 rows for one account are inconsistent and stop the migration. The partial unique index `consent_records_registration_version_key` allows at most one unrevoked registration C1 for an account and version. The insert trigger fills the current version when an old backend omits it and rejects a mismatch from the new backend; the immutability trigger also protects the version during revocation.
|
|
- Version check before the email branch. `CheckTextVersion(ctx, repositories, purpose, version)` returns the current text when `version` is current and fails like a grant otherwise, without writing anything. The registration must call it with C1 and the submitted version before it branches on a new or an existing email; otherwise a stale version would be refused only for new addresses, and the difference would reveal which accounts exist.
|
|
- Current text only. A grant reads `ConsentTexts().Current` at the application time and refuses any other version with `*StaleConsentTextError`, which matches `ErrStaleConsentText` and carries the purpose, the requested version, and the current one, so a handler can map it to one problem code and show the new text. An older version, a version that is scheduled but not yet published, and a version that never existed are all stale. The ledger accepts any published version, so this check is what keeps a grant of an outdated text out. The check and the insert are not locked against a publication between them: texts are published by migrations, and a grant that named the current text when it was checked is valid.
|
|
- Server time. The input has no time field. The grant uses one reading of the injected clock for the check and for the record time; a client cannot choose the time. The database still refuses a version published after that time.
|
|
- Idempotency. A repeat of the same subject, purpose, and current version returns the existing unrevoked record with `Created` false, keeps its first time, stores nothing, and does not abort a surrounding transaction. A grant after a revocation is a new record. A repeat that names an older version after a newer text was published is stale, not a repeat: the subject has to see the new text, and the ledger keeps its one record.
|
|
- C4 only through its scope. `GrantInSettings` refuses C4 with `ErrScopedConsentRequired` before it reads anything. `GrantContact(ctx, repositories, input)` is the explicitly scoped operation for the invitation acceptance: the input carries the organization and the name shown, the field set, the invitation, the invitation terms version, and the C4 text version. It checks that the C4 text is current, lets `domain.NewContactConsentGrant` hash the text as shown, and calls `ConsentLedger().GrantContact` in the caller's transaction. A repeat of the same subject and invitation returns the existing record with `Created` false; the caller compares its scope. The text check comes first, so a repeat after a newer C4 text was published is stale; the acceptance that wants to answer such a repeat with the earlier result must find its existing record before it calls.
|
|
- C3 may be withheld. The purposes are independent: no grant requires, implies, or changes another, and no implemented account or profile operation requires active C3. A subject without C3 has no C3 record, and `Current` returns `ErrConsentNotFound`; this is not an account error. A separate manual-assessment request is planned, but its endpoint is not implemented.
|
|
- Revocation and deletion request. `RevokeInSettingsInNewTransaction` applies all consent effects inside the transaction that stamps the ledger; repeating an already completed revocation does not append another event. C1 deletion requests are durable and idempotent, but they do not synchronously delete the account or cancel on a later C1 grant.
|
|
- Errors keep their identity: a stale version, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (the purpose has no published text), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent`, and `domain.ErrInvalidConsentText`. `outbound.ErrTransactionConflict` is the one that needs action: the ledger returns it, without aborting the transaction, when the record of a repeat was revoked between its insert and its select. A caller inside a `UnitOfWork` must return it, roll the transaction back, and retry the whole operation; `GrantInSettingsInNewTransaction` does so itself. Mapping the other errors to problem codes belongs to the handlers.
|
|
- Demo texts need a release gate. The texts that the migration publishes have the kind `demo`: synthetic, without a legal review. Nothing in the usecase distinguishes them from texts of the operator, so a deployment that accepts real data would record consent to a demo text. Before real data are accepted (PRD 7.3), a release gate must check that the current text of every purpose has the kind `operator`; the owner is the release gate or consent revocation, and neither exists yet.
|
|
|
|
### Registration, email verification, and resend
|
|
|
|
Implemented: `RegisterAccount` and `ResendEmailVerification` are served by `backend/internal/usecase/identity/register.go` (`identity.Registration`) behind the handler `backend/internal/adapter/primary/http/v1/auth.go`. Without `DATABASE_URL` both answer 501 as before. The router mounts `middleware.ClientIP` with `TRUSTED_PROXY_CIDRS`.
|
|
|
|
One transaction. A new address creates the account (scenario and the first `onboarding_step` of the scenario), the C1 record (`GrantAtRegistration`, current text version and hash, source `registration`), the SHA-256 hash of a one-time token bound to the registration version, and the verification delivery (`ServiceMailer.EnqueueVerification`); the sending worker sends it later through the mail transport. C4 and every other purpose are never recorded: the body accepts only C1. Re-registration of an unverified address follows the lock order of the identity repositories (invalidate tokens, then `AdvanceRegistration`, then the new C1). An address that is already verified changes nothing and receives nothing: the "you already have an account" notice is not implemented, because any message to a verified address needs its own template and its own limit, and silence cannot reveal the account.
|
|
|
|
Pending credentials (pre-hijack protection). Every registration, the first and each repeat, stores its password hash, scenario, and first onboarding step on its own verification token (columns `pending_*` of `email_tokens`, migration 00014). A repeat registration of an unverified address never changes the credentials, scenario, or onboarding step of the `users` row: `UserRepository.AdvanceRegistration` only advances the registration version and the registration time (and discards the earlier registration C1), and the new token carries the new pending credentials. A resend copies the pending credentials of the newest token of the registration. The `password_hash`, `scenario`, and `onboarding_step` of an unverified account row are not authoritative until a verification applies the clicked token's pending data: they hold the first registrant's values only because the columns are mandatory, and no code may authenticate with them or trust them (see the comment on `domain.User`). Invalidating a token (`InvalidateActive`) clears its `pending_*` columns, and a CHECK constraint keeps an invalidated token from holding a pending hash. A resend that finds no pending credentials for the registration issues nothing.
|
|
|
|
Email confirmation (`ConfirmEmail`) is implemented. It requires the password saved with that token's registration and checks it against the pending hash. In one transaction the backend checks the current registration version and its C1 record, consumes the token, verifies the address, applies the token's password hash, scenario, and onboarding step to the account, clears `pending_*`, and records exactly one secret-free `identity.email_verified` event. Any refusal leaves the account and token unchanged. Unknown, used, replaced, or superseded tokens, a wrong password, and missing pending credentials answer `verification_token_invalid`; an expired token answers `verification_token_expired`. The Origin must match exactly `APP_PUBLIC_URL`. Confirmation does not create a session. The frontend confirmation screen is implemented and covered by the local registration browser flow.
|
|
|
|
Login accepts only a verified email and checks the account's stored password, never pending registration credentials. An unknown address, wrong password, and invalid stored hash receive the same `invalid_credentials`; unknown addresses and invalid hashes also run `VerifyDummy`, and an invalid stored hash is logged without the email or hash. A correct password for an unverified account answers `email_not_verified` and creates no session. Successful login creates a new session; if the request carried a valid session cookie, the backend revokes it and creates the new session in one transaction. Failed login does not revoke an existing session, and a malformed cookie cannot become a principal.
|
|
|
|
Order of checks in registration: validation of the whole body and the C1 text version, replay check, rate limit, password hash (on every branch, before the account is read), transaction. A validation error (400) never depends on the stored accounts and consumes no limit.
|
|
|
|
Idempotency. The key is scoped by `HMAC(secret, operation | key | normalized email)` and the request is fingerprinted by `HMAC(secret, canonical body)` (`identity.Keyring`, secret `IDENTITY_KEY_SECRET`; required; a development stand may set `IDENTITY_ALLOW_EPHEMERAL_KEY=true` to draw a random one per process, which loses records and counters on restart). The record lives in `idempotency_records` (migration 00014) for 24 hours and is written in the registration transaction, so a visible record always belongs to a committed registration. A retry with the same key and body replays the neutral 202 and consumes no limit; the same key with another body answers 422 `idempotency_key_reused`. A concurrent identical request waits on the row of the first and is then replayed, so this implementation never answers 409 `idempotency_in_progress`. Each registration purges up to 10 expired records, which keeps the table bounded without a job.
|
|
|
|
Rate limits (Redis, fixed windows, `outbound.RateLimiter`, `redis.Cache.Take`, one atomic Lua script per take). The counters are keyed by the HMAC of the normalized address and count every request whether or not an account exists, so a 429 reveals nothing about the account. Registration and every resend share the per-address counters: at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between two messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per window of 24 hours that starts with the first. Confirmation allows five attempts per token per hour. A per-client counter, `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour), applies to registration, confirmation, resend, and login; it is keyed by `middleware.LimiterKey` of `ClientAddr`, hashed with the secret, and is skipped when the address is unknown (a shared bucket would let one client lock out everyone). Login also uses `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (default 10 per hour) for normalized email, whether or not an account exists. Both configurable identity limits accept values from 1 to 10000. A rejected `Take` does not increase its own counter; if an earlier limit check passed, its counter already records the attempt even when the next check refuses it. A refusal answers 429 `rate_limited` with `Retry-After` in whole seconds rounded up. Counters are ephemeral: a Redis restart resets them, and the mail provider quota remains the last bound. A Redis failure answers 500 and never lets the request through. Neither address nor token is logged.
|
|
|
|
Token replacement policy. Every issue of a verification token (registration, re-registration, resend) first invalidates all unused verification tokens of the account and then stores the new one, so at most one link works at a time. A resend keeps the password, the scenario, the consent record, and the registration version; only the token changes. The message of an invalidated token is cancelled by the sending worker, so only the current link is delivered. The token lifetime comes from the product policy (`identity.verification_token_lifetime_hours`, 24 in the demo version), not from configuration.
|
|
|
|
Targeted lockout. Because the per-address counters count every request whether or not the account exists, anyone can use up the address's 5 messages per 24 hours and so block the owner's registration and resend for up to 24 hours without knowing the address's state. This is the price of answering 429 identically for every address; it is accepted as a known limitation of the anti-enumeration design. It is bounded (the per-client limit slows one source), and visible: `lincodex_identity_rate_limit_refusals_total{scope="address"}` rises. A large share of `scope="client"` refusals instead hints at a broken proxy chain (every client resolved to the proxy address); alert on the ratio of client to address refusals and check `TRUSTED_PROXY_CIDRS`. The label has two fixed values and never holds an address. No alerting rule is shipped yet.
|
|
|
|
Without a resolved client address (the `ClientIP` middleware did not run) the per-client limit is skipped and only the per-address limits apply: a shared "unknown" bucket would let one client lock out everyone, the worse failure. `IDENTITY_KEY_SECRET` is required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` lets a development stand draw a random one. The limiter keys carry a Redis hash tag (`{key}`), so the multi-key script is cluster safe.
|
|
|
|
Known limits. A resend for an unknown or verified address skips the token and message work, so its time differs from an unverified account by a few database statements; registration hides the difference behind the password hash. The password blocklist of the contract is not implemented yet; only the length rules of `domain.NewPassword` apply.
|
|
|
|
### Organizations and memberships
|
|
|
|
Organization creation, reads, and owner edits are implemented in `backend/internal/usecase/organization/`, `backend/internal/adapter/primary/http/v1/organization.go`, and `backend/internal/bootstrap/organization.go`. Storage and membership ports remain in `backend/internal/port/outbound/organizations.go` and the PostgreSQL adapter. Migration `00019_create_organization_creation_results.sql` preserves the original create result. General tenant context and the paginated directory of the current account's organizations are also implemented. See [backend documentation](../../backend/README.en.md#organizations) for behavior and validation.
|
|
|
|
The middleware in `backend/internal/adapter/primary/http/company_context.go` checks the verified employer account and active `owner` membership after session, CSRF, and parameter decoding, before the business handler or its 501 fallback. All 14 organization, need, and invitation operations are classified explicitly; a contract test requires new paths with `org_id` to be classified. Candidate-owned company hiding and C4 revocation retain their separate authorization. Request context is not cached and never replaces authorization repeated inside a business transaction. Other roles receive 403; foreign or ended memberships receive 404. `ListMyOrganizations` returns only the current employer's active memberships; a company appearing in that directory does not itself grant owner authority.
|
|
|
|
Tables:
|
|
|
|
- `organizations`: UUIDv7 `id` (the `org_id` of every organization path), `name` (1-200 characters, the bound of the consent snapshot), `description`, `sphere` (free text; the PRD has no taxonomy), four public contact columns (`contact_website`, `contact_email`, `contact_phone`, `contact_telegram`), the verification columns `verification_level`, `verification_basis`, and `verification_changed_at`, the profile `version`, and the times. Every text column has a CHECK for the same format and bounds as the contract (no surrounding whitespace, no control characters, `https` website without credentials).
|
|
- `organization_representatives`: `organization_id`, `ordinal` (0 to 9, so at most ten), `name`, and `job_title`; deleted with the organization row. The list is replaced as a whole with a profile update.
|
|
- `memberships`: UUIDv7 `id`, `organization_id`, `user_id`, `role`, `state`, and the times. `UNIQUE (user_id, organization_id)` allows one membership per pair in any state, and `UNIQUE (organization_id, id)` is the target of the composite foreign keys that later tables (the assignments of needs) use to bind a membership to its organization. Both foreign keys are `ON DELETE RESTRICT`.
|
|
|
|
Decisions:
|
|
|
|
- Active context. It is not a server-side session attribute. The organization is the `org_id` in the path, and the server derives the right from the active membership on every request, so a removal, a suspension, or a leave closes the next read with nothing to invalidate. `ListMyOrganizations` is the directory a client picks from; remembering the last choice is a browser convenience. The context comes only from the caller's active memberships, and a terminated membership closes reads at once. A switch clears the client's tenant queries.
|
|
- Role and state in the membership only. `OrganizationRole` is `owner`, `recruiter`, `hiring_manager`, or `technical_expert` (PRD 2.2, Q3, and the FR07 matrix), and `MembershipState` is `active`, `suspended`, `removed`, or `left`, each a CHECK constraint, not a PostgreSQL enum, so a later value is a constraint change in a migration. There is no `invited` state: PRD 6.4 lists `MemberInvite` as its own entity, an invitation to an email address that may have no account yet, and a membership row appears when its owner accepts it. `organizations` has no role, owner, or member column (an integration test reads the catalog to prove it), and `Organization`, `OrganizationCreate`, and `OrganizationUpdate` have no such field. Only the owner manages the company (`OrganizationRole.CanManageOrganization`); the rest of the matrix is applied by the operations it governs, and in the MVP the other roles grant nothing.
|
|
- Verification level. `verification_level` is `e0` to `e3` with `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), and one CHECK ties each level to its own bases. The columns are separate from the profile: `UpdateOrganizationProfile` never names them, `domain.NewOrganization` cannot choose a level and starts every organization at `e0` on `confirmed_email`, `Organization.ApplyProfile` keeps the verification, and the contract has no operation or request field that sets it. A test updates a profile after a process moved the level and checks that it stays. E1 to E3 are set by the verification processes that do not exist yet; the planned verification flow adds E0/E1 with evidence, a scope, and an append-only history, and it will update these columns together with its history row and must first write a history record from the current row of every existing organization (level, basis, and time as stored), so the history has no gap before its first process. `OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the quota tiers of the product policy and has none for `e3`, which the PRD gives a separate policy (quota enforcement reads the tier and must fail closed on an `e3` organization: no quota granted, the action refused, never a fallback to another tier).
|
|
- An organization has an owner. A deferred constraint trigger (`organizations_owner_required`, SQLSTATE 23514) refuses at commit an organization with no `owner` membership in the `active` state, so creating an organization without its owner fails whichever code inserted it, and `CreateWithOwner` stores the organization, its representatives, and the owner in one transaction. Removing or demoting the last owner later is a rule of the member management, not of this constraint, which would otherwise block a platform decision about an abusive organization.
|
|
- Update. `UpdateProfile` is one statement that applies only when the stored version equals the version the caller read, and advances it by one. The same statement requires an active membership of the actor with a manager role (the roles come from `domain.ManagerRoles`, not from SQL), so a membership that ended after the caller's read still stops the write. When the statement matches nothing, the adapter reads the membership to answer `ErrOrganizationNotFound` (unknown organization or no active membership), `ErrOrganizationManagerRequired`, or `ErrOrganizationVersionConflict`, in that order, so a stale version never tells an outsider anything. The representative list is then replaced in the same transaction under the row lock of the update. The statement locks the organization row (`FOR UPDATE`) and then the actor's membership row `FOR SHARE`, so a revocation that commits while the statement waits for the membership lock is re-evaluated and stops the write (an integration test holds a revocation open, queues the update behind it, and commits it). The lock order of every writer is organizations, then memberships: the member management, which changes a membership and the organization together, and the tenant repository must take the locks in that order, or two transactions can deadlock.
|
|
- Foreign keys and deletion. `memberships` restricts the deletion of an organization and of an account, so an account with memberships cannot be deleted until a procedure ends them, in the same way as the consent ledger restricts the account. The application never deletes an organization. The consent ledger does not reference `organizations` yet: `consent_records.organization_id` is still a plain column with the snapshot name beside it. Adding the foreign key now would force the consent ledger tests to create real organizations, and the `invitation_id` key needs real invitations; both arrive with the acceptance of an invitation, the first writer of C4 rows that name a real invitation. The invitation tables (migration 00037) and the needs reference organizations, accounts, and policy versions with `ON DELETE RESTRICT`, so an organization with needs or invitations stays undeletable, which is the intended protection of consent evidence (PRD 7.3).
|
|
- Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees: `OrganizationRepresentative` hides its fields behind a pointer and redacts itself in `fmt` and `slog` output, `Organization` logs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput`, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store of `CreateOrganization` keeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and remove it through bounded opportunistic cleanup after the replay window; physical deletion may happen later when create traffic resumes; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and its `representatives` may be absent. The open questions (the publication of representative names, a sphere taxonomy) and the blocking one, a limit of organizations per account, which the PRD does not set and without which an account can multiply quotas by creating organizations (organization creation and quota enforcement need the owner's decision, and the prepared mechanism is a 409 `state_conflict` on create), are in [api/README.en.md](../../api/README.en.md#organizations).
|
|
|
|
What the ports guarantee (`outbound.OrganizationRepositories`, available on `UnitOfWork` only, because a write needs the transaction):
|
|
|
|
- `Organizations().CreateWithOwner` stores the organization and its owner membership and validates that the owner is the active owner membership of that organization. An unknown account returns `ErrUserNotFound` and aborts the surrounding transaction.
|
|
- `GetForMember` reads the organization, its representatives (aggregated as JSON in the same statement), and the caller's active membership from one snapshot, and returns them or `ErrOrganizationNotFound` for an unknown organization, an account without a membership, and a `suspended`, `removed`, or `left` member alike. `ListForUser` pages the active organizations of one account, newest membership first, with the organization identifier as the tie-breaker. `UpdateProfile` is described above.
|
|
- `Memberships().Insert` returns `ErrMembershipExists` for a repeated pair in any state, `ErrOrganizationNotFound` for an unknown organization, and `ErrUserNotFound` for an unknown account; `Get` returns the membership in any state or `ErrMembershipNotFound`, and the caller checks `GrantsAccess`. There is no method that changes a role or a state yet.
|
|
|
|
### Candidate profile
|
|
|
|
Own `GetMyProfile` and `SaveMyProfile` operations are implemented through `backend/internal/usecase/profile/`, the transactional `CandidateProfileRepository` port, `backend/internal/adapter/secondary/postgres/candidate.go`, and `backend/internal/adapter/primary/http/v1/profile.go`. The use case rechecks the verified candidate account inside the transaction; the owner identifier comes only from the server session. Without DATABASE_URL, the operations retain their 501 fallback. Schemas and full-replacement rules live in `api/core/components/schemas/candidate_schemas.yml` and `api/core/routes/candidate_profile.yml`. No ML service, resume file, or FSP account is required.
|
|
|
|
Migration `00020_create_candidate_profile_history.sql` adds overlapping-period confirmations and version history. `experience_overlaps` lists intersections of inclusive calendar months. An explicit confirmation binds two indices to their exact dates in the current request and its `expected_version`; an earlier confirmation carries forward only for the same indices and dates. Editing an employer or description alone does not invalidate the confirmed periods. A stored unconfirmed overlap permits only an exact no-op; a changed profile requires confirmation or corrected dates.
|
|
|
|
The changed version, complete claim set, period confirmations, and private history snapshot commit in one transaction. Each snapshot is bounded to 256 KiB; a trigger refuses history UPDATE, and deleting the profile cascades to its history. There is no automatic retention expiry. A no-op creates no history. A successful save, including a no-op, advances only `candidate_profile` to `candidate_questionnaire`, leaving later steps unchanged. Confirmed categories currently remain empty until assessment-result reading is implemented and are never written by the profile form.
|
|
|
|
Tables:
|
|
|
|
- `candidate_profiles`: `user_id` (the primary key and a foreign key to `users` with `ON DELETE CASCADE`), `version` (positive; the first save creates version 1, and the contract's version 0 is the absence of a row), and times. The profile is personal data of the account and goes with it; retention rules are an open legal question.
|
|
- `candidate_profile_claims`: one row per stored claim - a single field (`full_name`, `contact_email`, `contact_phone`, `contact_telegram`, `terms_location`, `terms_relocation`, `terms_salary_minimum` at `ordinal` 0) or a list item (`stack` up to 30, `role` up to 9, `experience` up to 20, `soft_skill` up to 10, by position). Columns: `value` jsonb, `status` (`confirmed` or `extracted`), `origin` (`manual`, `extracted_from_resume`, `imported`), `trust_level`, `quote`, `extraction_version`, and `confirmed_at`. A field without a value has no row, so the contract's `unknown` is the absence of a row. The foreign key points at `candidate_profiles` with `ON DELETE CASCADE`.
|
|
|
|
Decisions:
|
|
|
|
- Claims, not columns. Every value has a status, a source, and a confirmation time, so one claims table replaces fifty columns; jsonb holds the shape of the value (a string, a boolean, or an object), and each kind has its own CHECK for the format and bounds of the contract (E.164 for the phone, the `@` of a Telegram name, a multiple of 1000 for the salary, `YYYY-MM` and the order of the period for experience, the known specialization and grade codes). The domain validates a value in full before it is written, and `RestoreCandidateProfileContent` applies the same rules on read, so a row changed outside the application is rejected.
|
|
- Trust level 0 in the schema. `trust_level` is stored in a column with `CHECK (trust_level = 0)`, and the insert statement supplies 0 itself and takes no level from the caller. A confirmed value requires `confirmed_at`, an unconfirmed suggestion does not and is always an import (`extraction_version` is not NULL); a manual value is always confirmed and carries no quote. Raising trust is a property of evidence, which is not stored here.
|
|
- No confirmed category. The tables have no column for a confirmed grade or a category, and the value of a role admits only the keys `specialization` and `self_assessed_grade`, so neither a form nor an import can write a confirmed category; it is derived from assessment results when read (`confirmed_categories`).
|
|
- No mandatory link to a file, ML, or FSP. The tables have no column or foreign key to a resume file, the object storage, ML, or an FSP account, and the only foreign keys point at `users` and `candidate_profiles`. A profile typed by hand is complete; a future import adds its own columns or tables additively (`TestCandidateProfileStorage` checks the set of columns and foreign keys).
|
|
- Version. `AdvanceCandidateProfileVersion` is one statement that advances the version only when the stored one equals the one the caller read; for a stale version no row returns, and the caller answers 412 `version_conflict`. The update time is `GREATEST(stored, application clock)`, so an instance clock that runs behind never violates the CHECK `candidate_profiles_updated_after_creation` (which would be a 500). Version monotonicity is enforced by these queries only: there is no trigger, so no other code may write `version`. `InsertCandidateProfile` with `ON CONFLICT DO NOTHING` tells a lost first save apart (concurrent first saves: one wins, the rest get a version conflict). Replacing the set of claims (delete all, insert the new ones) runs in one transaction with the version advance. `domain.CandidateProfile.Replace(input, expectedVersion, at)` fixes the order: a version above the current one is a conflict; body rules are 400; a decision `extracted` that depends on the stored claims, against a stale version, is `ErrCandidateProfileVersionConflict` rather than 400; a body that changes nothing does not advance the version; any other change over a stale version is a conflict.
|
|
- Consistent read. `ReadCandidateProfile` reads the profile row and every claim in one statement (a LEFT JOIN), that is, from one snapshot; two separate queries could return version N with the claims of N+1 when a save commits between them. The adapter must use only this query and never replace it with two; a write reads the profile in the same transaction as the replacement, and the version condition protects against a lost edit.
|
|
- Privacy. The values are personal data of the candidate: `ProfileClaim`, `ProfileExperience`, `ProfileSalaryMinimum`, `CandidateProfileContent`, and `CandidateProfile` hide themselves in `fmt` and `slog` output, `CandidateProfile` logs only the account identifier and the version, domain errors name the field and the rule but never the value, and metric labels are never taken from the profile. No query selects the profile of another account: every statement is scoped by `user_id`. The adapter must never log or wrap `pgconn.PgError.Detail` (it contains the failing row with names and phones) and reports only the SQLSTATE and the constraint name, as the organizations adapter does.
|
|
|
|
### Candidate visibility
|
|
|
|
Implemented as storage, domain, and the source contract: the migration `backend/db/migrations/00015_create_candidate_privacy.sql` (number 00014 belongs to the idempotency records of the registration task), the queries in `backend/db/queries/privacy.sql`, the domain types in `backend/internal/domain/visibility.go`, the schemas in `api/core/components/schemas/privacy_schemas.yml`, and nine operations of the tag `privacy` in `api/core/routes/candidate_privacy*.yml` under `/api/v1/me/privacy` ([api/README.en.md](../../api/README.en.md#candidate-visibility)). There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`RestorePublication`, `RestoreSearchStatus`) are ready and covered by an integration test.
|
|
|
|
Four independent pieces of state, each with its own table and its own version. No statement of one table writes another, and the consent C2 is neither copied nor replaced:
|
|
|
|
- `candidate_publications`: one row per candidate, created by the first explicit publication, so a new profile has no row and is closed. Columns: `state` (`published` or `closed`), `fields` (a canonical array of card field codes, empty exactly when closed), `consent_record_id`, `published_at`, `closed_at`, `version`, and times. The card field codes are a closed set (`categories`, `stack`, `experience`, `soft_skills`, `location`, `relocation`); the full name, a contact, and the lowest salary have no code, and the function `candidate_card_fields_are_canonical` with a CHECK refuses anything else, so no row can publish them.
|
|
- `candidate_search_statuses`: one row per candidate who ever set the status. `status` is `looking` or `not_looking`; `looking` stores `confirmed_at`, `lapses_at`, and `policy_version_id`, and `not_looking` stores none of them (a CHECK ties the three together). The only foreign key is `users`, and a trigger checks `policy_version_id` against `policy_versions` (SQLSTATE 23503, constraint name `candidate_search_statuses_policy_fkey`), because a real foreign key would make PostgreSQL refuse TRUNCATE of the immutable policy table before its own trigger could answer: the table has no consent column and no reference to the ledger, and a test reads the catalog to prove it.
|
|
- `candidate_hidden_organizations`: the primary key `(user_id, organization_id)` makes a hiding unique per candidate and organization; `organization_id` references `organizations` with `ON DELETE RESTRICT`. A BEFORE INSERT trigger (`candidate_hidden_organizations_enforce_limit`) bounds one candidate to 1000 records, serializing the inserts of one candidate through a no-key-update lock on the account row, and fails with SQLSTATE 23514 and the constraint name `candidate_hidden_organizations_limit`. The index on `(organization_id, user_id)` serves the organization side, which has to exclude hidden candidates without learning who hid it.
|
|
- `candidate_privacy_events`: the append-only history (a trigger refuses every UPDATE with `candidate_privacy_events_immutable`, and refuses DELETE only while the account is verified, with `candidate_privacy_events_retained`; TRUNCATE stays allowed for test isolation). It holds the kind, the time, the published field set and the C2 record of a publication event, and only the organization identifier for a hiding event (the candidate's read joins the current name, so the table holds no text about an organization); a CHECK fixes the shape of every kind. It never holds a profile value or a name. A trigger refuses DELETE while the account is confirmed (`candidate_privacy_events_retained`, the same condition as `consent_records_refuse_delete`, to be extended by the retention rule and the account deletion procedure), a trigger on `users` refuses deleting a confirmed account that has history with the same constraint name (the cascade runs after the account row is gone, so the row trigger alone cannot see it), and the account reference cascades, so the unverified account cleanup removes the rows of an account it deletes. The hide and unhide records are sensitive: they say which employer a candidate avoids.
|
|
|
|
Decisions:
|
|
|
|
- A profile is closed by default. Nothing in the account, the profile, the questionnaire, or an assessment creates a row, and the integration test saves a profile and checks that all four tables stay empty. The domain reads a missing row as version 0, closed with the reason `never_published`, not looking, and hiding nobody.
|
|
- C2 stays in the consent ledger; the publication references it. Duplicating the consent state would let two tables disagree about whether a candidate agreed. `candidate_publications` therefore holds only what the ledger deliberately does not carry (which fields and when) and a reference to the C2 record behind them. The composite foreign key `(consent_record_id, user_id, consent_purpose)` over the unique index `consent_records_id_subject_purpose_key` (added by this migration; the record id is already unique, so it restricts nothing) accepts only a C2 record of the same account, and a record that a publication refers to cannot be deleted. The effective state is computed: `ReadCandidatePublication` joins the revocation stamp of the record in one statement, and the card is `published` only while the stored state is `published` and the record is unrevoked. A revocation of C2 closes the card at once without any write here, and a later C2 grant opens nothing: the publication stays bound to the revoked record, so the candidate publishes again explicitly and the new publication binds to the new record. The body of the publish operation carries no consent identifier; the usecase binds the account's current unrevoked C2 record in the same transaction as the write, and it MUST take it with the port method that issues `LockCurrentC2Record` (`SELECT ... FOR SHARE`), not with `ConsentLedger().Current`, otherwise the race with a revocation returns, and without one answers 409 `state_conflict`.
|
|
- The search status is not a consent. It has its own table, its own version, and no reference to the ledger, and `domain.SearchStatus` knows neither the publication nor the hidden organizations, so applying a status cannot change them. The integration test sets, confirms, and clears the status in a fixture and compares the raw rows of the consent ledger, the publication, and the hidden organizations before and after: they are equal.
|
|
- The lapse of `looking` comes from the versioned policy and only narrows. The 30 days are `search_status.searching_confirmation_interval_days` of the effective `product` policy version (demo version 1: 30), so the owner changes them by publishing a new policy version, not by a constant or configuration. A confirmation fixes `lapses_at` and stores `policy_version_id`, so a later policy change moves no stored time and every row names the policy it was made under, as the policy section requires. The lapse itself is computed (`SearchStatus.Effective(now)` is `looking` only while `now` is before `lapses_at`) and never written: no process, job, or clock skew can turn an expired status into anything more public, the stored row keeps what the candidate said, and the read model shows `value` `not_looking` with `lapsed` true. The candidate confirms again with `looking`, which replaces `confirmed_at`. A reminder before the lapse is a planned notification, not part of this task.
|
|
- Versions. Each setting has its own `version` (0 is the absence of a row), checked in the statement like the profile: `UpdateCandidatePublication` and `UpdateCandidateSearchStatus` change a row only when the stored version equals the one the caller read, and no row returns for a stale one (412 `version_conflict`). The domain order is the contract's: a version above the current one is a conflict, an unchanged effective setting is a success even over a stale version, any other change over a stale version is a conflict, and a publication needs an active C2. Because the settings are independent, a change of one never makes another stale.
|
|
- Hidden organizations belong to the candidate and are safe against enumeration. The record is the candidate's: no organization-visible query selects it, and an organization cannot tell a hidden candidate from an unpublished one. Hiding by identifier must not become a way to ask whether an organization exists. The foreign key refuses an unknown organization (SQLSTATE 23503), and the usecase must answer that exactly like an organization the candidate cannot see: the same 404 `not_found` with the same body, without a different timing or code. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup lists (planned, an open question), so a hiding reveals nothing the candidate could not already read. Lifting a hiding is a DELETE that answers 204 for any well-formed identifier, so it reveals nothing at all, and its history event is written only when a row was deleted. The identifiers are random UUIDv7 values, and the general rate limit covers the probing that remains.
|
|
- Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke the grant with the reason `visibility_closed` in the same transaction as the change (the invitation contract fixes the reason). That belongs to the usecases that do not exist yet; this task stores the settings and defines the contract. The search status never closes a grant.
|
|
- History instead of a field scope. The C2 record proves the consent to the publication text, and `candidate_privacy_events` keeps what the consent ledger note asked for: the published field set and its changes with their times and the C2 record behind each. A revocation of C2 and a lapse are computed, not events. Whether C2 needs its own field scope as a consent under article 10.1 of 152-FZ is still a legal question (see the consent ledger).
|
|
- Privacy. The tables hold identifiers, card field codes, and times; no profile value, name, contact, or file (a test lists the columns). `Publication`, `SearchStatus`, `HiddenOrganization`, and `PrivacyEvent` log only identifiers, versions, and kinds. No query selects another account's row: every statement is scoped by `user_id`. The adapter must report only the SQLSTATE and the constraint name, as the others do.
|
|
|
|
- One structural barrier for organization-facing reads. The view `candidate_effective_publications` is published AND backed by an unrevoked C2 record. Every read on behalf of an organization (the search, the card, the contact read) must select from this view and add `NOT EXISTS` over `candidate_hidden_organizations` for the reading organization, as `ReadPublicationVisibleToOrganization` does; no row means "nothing to read" whichever reason applies, so an organization cannot tell a hidden candidate from an unpublished one. Reading `candidate_publications` directly is reserved for the candidate's own settings queries, and `backend/db/privacy_queries_test.go` fails when any other query in `db/queries` names the table.
|
|
- Closing over a revoked C2. A closing sent over a stored `published` row whose C2 was revoked is a real change: the row is normalized to `closed`, `publication_closed` is recorded, and the contact grants are revoked with `visibility_closed` like for any closing. Only a stored `closed` row makes a closing a repeat. The C2 revocation path must itself close the stored publication and revoke the contact grants of the account in its own transaction; the computed state closes the card at once, but it does not revoke grants.
|
|
- Publish and revoke race. The publish transaction takes the current C2 with `LockCurrentC2Record` (`SELECT ... FOR SHARE`) and writes the publication under that lock, then re-reads the effective state with `ReadCandidatePublication` in the same transaction to build its response. The revocation stamp is an UPDATE of the same row, so it either commits first (the lock returns no row and the publication is refused with 409) or waits until the publication commits and closes the card right after; an integration test holds the lock and proves both orders.
|
|
- Verified email. Publishing, hiding, and the history exist only for accounts with a verified email (a usecase requirement). The unverified account cleanup (`DeleteUnverifiedUsersRegisteredBefore`) deletes its consent records explicitly and would meet the restricting reference of a publication to its C2 record, so that no unconfirmed account holds a publication is a usecase requirement, not a physical impossibility: the cleanup also works over an unverified account that does hold a C2, a publication, and history, and over a C2 revoked and granted again (an integration scenario verifies it, and it depends on the order in which the data-modifying statements of the cleanup apply). Hiding records and history cascade.
|
|
- Two kinds of 409 `state_conflict` are told apart by `errors[]`: `{in: body, pointer: /state, code: consent_required}` for a publication without an active C2, and `{in: path, pointer: /org_id, code: limit_reached}` for the 1001st hidden organization. The hiding limit is enforced by the trigger under a lock on the account row; when an insertion fails with SQLSTATE 23514 and `candidate_hidden_organizations_limit`, the adapter must re-read the pair before answering 409, because a concurrent PUT of the same pair at 999 records can have created it, and the idempotent answer is 200; an integration test fires eight concurrent insertions at 999 records and expects exactly one success.
|
|
- A new card field is a contract change and a migration. The codes are listed in the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables, as well as in the `CardField` enum, `domain.CardField`, and the card builder.
|
|
|
|
Content of the card (hard requirements for its builder):
|
|
|
|
- Only values that the candidate confirmed ever reach the card; an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.
|
|
- A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped, never published. `domain.CardTextLooksLikeContact` is the check the builder must apply to every free text; it errs on the side of dropping.
|
|
- Quasi-identifiers (a rare combination of location, stack, and experience) and the generalization of rare features are an acceptance criterion for the card builder, not decided here (see the open question in the API README).
|
|
|
|
The anonymous card for organizations is not built here: `AnonymousCardContent` is the closed set of properties that a published card can hold (confirmed categories, stack, total months of experience, soft skills, location, relocation), with no name, contact, employer, salary, or identifier, and a contract test walks the references of the card and the preview and fails on any profile, contact, consent, or organization schema. The card of an organization's search result must reuse it. `GetMyCardPreview` and `ListMyCardAccessHistory` are contract-only: the preview needs the profile, the confirmed categories, and the publication read together, and the access records are written by the search and contact-read tasks, so the table for them comes with those tasks.
|
|
|
|
### Invitation drafts
|
|
|
|
Implemented: the organization side of the invitation draft, that is `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). A draft is invisible to the candidate and produces no inbox row, no event, and no quota charge. Sending, withdrawal, the salary raise, the contact read, and every candidate operation of the invitation tag still answer 501 after the common checks. Code: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, the PostgreSQL adapter `adapter/secondary/postgres/invitations.go` with `db/queries/invitations.sql`, and migration `00037_create_invitations.sql`.
|
|
|
|
Tables:
|
|
|
|
- `invitations`: UUIDv7 `id`, `organization_id`, the internal `candidate_id` (never serialized, logged, or printed), the optional need link (`need_id` with `need_requirements_version`, bound by composite foreign keys to a stored version of a need of the same organization), `state` (all fourteen states of the contract, so the later operations need no constraint change), `expiry_reason`, `version`, `terms_version`, `response_period_days` (3, 7, or 14), `policy_version_id` (the product policy version that allowed the period), `response_deadline_at`, `salary_raise_used`, `created_by`, and `created_at`, `updated_at`, `delivered_at`, `viewed_at`, `responded_at`. CHECK constraints tie the deadline to the delivery (both set or both null), keep a draft free of delivery, view, answer, and raise, and tie the expiry reason to the state. A trigger keeps the identity columns, makes every UPDATE advance `version` by exactly one and `terms_version` by at most one, and refuses to undo a raise or to move the delivery, the deadline, or the period after a delivery. A second trigger refuses DELETE. The foreign keys to organizations, accounts, and policy versions are `ON DELETE RESTRICT`, so an account with invitations is undeletable until a deletion procedure settles them.
|
|
- `invitation_terms_versions`: `(invitation_id, version)`, the terms as a JSONB snapshot, and the salary again in typed columns (`salary_from`, `salary_to`, `salary_currency`, `salary_period`, `salary_tax_basis`). Constraints repeat the money rules in integers: both bounds from 1000 to 100 000 000 rubles in steps of 1000, `salary_from < salary_to`, `20 * (B - A) >= A + B` and `5 * (B - A) <= A + B` (a width of 10% to 40% of the midpoint), RUB, month, and `net` or `gross`. The snapshot must hold all twelve terms and its salary must equal the typed columns. A trigger refuses UPDATE and DELETE: a version of the terms is immutable, and a change appends the next version. The invitation points at its current version by a deferred composite foreign key, so the first version is inserted in the same transaction.
|
|
- `invitation_events`: one audit event for each committed invitation version (`UNIQUE (invitation_id, version)`) with the kind (`draft_created` or `draft_updated`), the version and terms version, the actor, the parts that changed (`terms`, `need`, `response_period_days`), and the time. It holds no content and is append-only.
|
|
- `invitation_creation_results`: the original response of an idempotent create, bound to the generic idempotency record and removed with it. It holds the terms, the alias, and no candidate identifier.
|
|
|
|
Decisions:
|
|
|
|
- Money. Amounts are whole rubles in `bigint`, as in the contract: there are no minor units and no floating-point column or comparison. `domain.SalaryRange.Validate` is the single implementation of the rule for needs and invitations; it checks the bounds, the step, the currency, the period, the base, `A < B`, and the width with the integer pair above. A violation of the order or the width is attributed to `salary_to`. The database repeats the rule, so another writer cannot store a range the API would refuse.
|
|
- Terms are complete from the first draft. `InvitationTerms.Validate` repeats the schema rules a stored value must also satisfy and adds the cross-field rules: a place of work for the `office` or `hybrid` format, a technology that is not repeated ignoring letter case, and a package in which every condition is either provided with a description or explicitly not provided. Text fields reject control characters, including NUL, which JSONB cannot store. A stored snapshot is decoded strictly and validated again on every read.
|
|
- The candidate. A draft names the candidate only by the card handle. `candidateview.Service.ResolveCandidateHandle` resolves it in the create transaction with the checks of a card read: the active membership, the effective C2 publication, the hiding of this organization, the locks of the visible cohort, and the minimum cohort of five. An unknown handle, a handle of another organization, a candidate who revoked C2 or hid the profile from the organization, and a card that the cohort rules suppress all fail with the same 400 at `/candidate_handle`. The resolution charges no card-view quota and writes no access history, because it returns an identifier to the server only and shows no card content. Responses derive the alias again with the key of the cards, so the handle of an invitation is the handle of the card; the same candidate has another alias in every organization.
|
|
- Owner only. The HTTP boundary lists the operations in `ownerCompanyOperations`, and the usecase repeats the check in its transaction: a verified employer account with an active `owner` membership. Another role gets 403; an outsider, an unknown organization, an unknown invitation, and an invitation of another organization get the same 404. A membership alone grants nothing.
|
|
- Idempotent create. The scope of `Idempotency-Key` is the operation, the key, the account, and the organization; the fingerprint is that of the canonical request body. The original 201 is stored in `invitation_creation_results` and replayed for 24 hours, even after the draft changed or the candidate stopped being visible. A different body under the same key gives 422 `idempotency_key_reused`. Every failure rolls the whole transaction back, so a 400 is never stored.
|
|
- Update. The body replaces the fields it sets, and `terms` is always replaced as a whole. The order is the one of the contract: a body that changes nothing returns the current invitation with 200 even when the version is stale, then the version (412 `version_conflict`), then the state (409 `state_conflict`, only a draft changes), then the rules (400 with a pointer). A change of the terms appends the next terms version; a change of the period or the need keeps it. A new period is checked against the policy in force and records its version.
|
|
- Response period. The options and the default come from the `invitations` section of the effective product policy (3, 7, 14; default 7), and the draft stores the version it used.
|
|
- Locks. A create and an update both take the exclusive organization lock first (`CompanyQuotaRepository.LockOrganization`), like a card read and a search, and only then the share lock of the membership check, the cohort locks of a create, or the invitation row lock of an update, so commands of one organization queue instead of deadlocking on a lock upgrade, and a later command that also charges the organization, such as sending, keeps the same order. An update locks the invitation row with a statement of its own (`LockInvitation`) and reads it afterwards: a locking read joined to the terms table would, after waiting for a concurrent commit, pair the new `terms_version` with the terms row it fetched before the wait and find nothing. A create repeats a bounded number of times when the visible cohort changed while it was locked.
|
|
- The indicator. `salary_fit` is always `not_available` and `contact_access` is `not_granted` with no fields. The indicator needs the candidate's minimum, and computing it before the limit of three settings a day and the seven-day withholding exist would let an organization probe the minimum by editing a draft, so neither is computed or enforced yet.
|
|
|
|
How the later operations plug in: sending must resolve the candidate through the same visibility barrier again, because a draft keeps its candidate after a C2 revocation or a hiding, and then moves the draft to `delivered` by one UPDATE of `state`, `delivered_at`, `response_deadline_at`, and `version`, appends an audit event for that version, and writes the `invitation.delivered` outbox event whose inbox resolver for the source `invitation` is the existing plug-in point of [Internal notifications](#internal-notifications); the candidate's inbox reads `invitations` by `candidate_id` and `delivered_at`, and the pair rules read the index on the organization and the candidate. The contact grant, the C4 key to `invitations`, and the keys of the consent ledger to `organizations` and `invitations` arrive with the acceptance, the first writer of C4 rows that name a real invitation.
|
|
|
|
Not implemented: the salary limit and the withheld counter, the indicator against the candidate's minimum, the quota charge and the limit of pending invitations per need, the sending, the raise, the withdrawal, the candidate side, the card of the organization for the candidate, the reading of earlier terms versions, and the handling of invitations when an account is deleted. The role and assignment matrix beyond the owner is planned.
|
|
|
|
Tests: `domain/salary_range_test.go` and `domain/invitation_test.go` (exact width at 10% and 40%, steps, caps, terms rules with pointers, versions, immutability of earlier values, redaction), `usecase/invitation/service_test.go` (owner policy, handle refusals, order of checks, replay, rollback, versions), `adapter/primary/http/v1/invitation_test.go` (mapping, no candidate field, failure statuses, cursor), and the integration tests `TestOrganizationInvitationDraftsOverHTTP`, `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations`, and `TestInvitationMigrationRollbackKeepsStoredInvitations` against a real PostgreSQL.
|
|
|
|
## Frontend
|
|
|
|
The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need.
|
|
|
|
The shared API wrapper owns base URL, cookies, AbortSignal, and error parsing. MSW is for development and tests; it is not a real integration check. Logout/account switch clears private query cache. Screens need loading, empty, error, retry, and forbidden states.
|
|
|
|
The target screen stack is React Router, TanStack Query, React Hook Form, and Zod, with CSS Modules and CSS variables. Radix UI can be added for complex accessible menus and dialogs. Add Next.js only for a demonstrated SSR or indexable-catalog need; Bun does not replace the selected stable Node and pnpm setup. Vite builds static assets served by Nginx, so production does not need a Node frontend process. These are target choices, not a claim that product libraries are already wired into the scaffold.
|
|
|
|
## Future extensions
|
|
|
|
Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node. The outbox table, its transactional writer, the relay, and the consumer runtime are implemented (see "Transactional outbox", "Outbox relay", and "Event consumers" above); one product consumer, `notification_delivery`, is registered; further consumers and additional topics are planned. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI.
|
|
|
|
k3s is outside the critical path. Consider it only with an operated cluster or measured multi-node need. A single-node cluster does not provide HA. A transition needs probes and resource limits, secrets, storage backup, ingress, and verified NetworkPolicy.
|
|
|
|
Vacancies and voluntary applications, recurring assessments, employer complaints/verification, ATS adapters, and deeper matching are future scope. Employer verification and ATS integration are not implemented or required for the first prototype.
|
|
|
|
## First product API slice
|
|
|
|
| Group | Initial target |
|
|
| --- | --- |
|
|
| identity | register, verify/resend email, login, logout, me; password reset can wait until the final phase |
|
|
| candidate | own profile, questionnaire, consent, publish and hide |
|
|
| documents | resume upload, analysis request, job status, confirmation of proposed fields, PDF retrieval |
|
|
| assessment | available tests, attempt start, answer save, submit, history, and eligibility |
|
|
| company | company profile and current user membership |
|
|
| matching | need, confirmation of extracted fields, search create/refine/read |
|
|
| invitation | send, list, view, accept/decline, withdraw, and authorized contact access |
|
|
| achievement | FSP link state and achievement history; fixture provider for demos |
|
|
|
|
Examples of stable operations are `POST /api/v1/searches`, `POST /api/v1/searches/{id}/refinements`, `POST /api/v1/candidates/{id}/invitations`, and `POST /api/v1/invitations/{id}/accept`. These are target examples, not implemented endpoints. Every business operation, response, and error belongs in OpenAPI with a stable `operationId`.
|
|
|
|
Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amounts for the MVP, and bounded cursor pagination. Distinguish null from absent fields. Errors have a stable `code`, safe message, optional field errors, and request ID. Use idempotency keys for invitation creation, analysis start, and assessment submission; scope keys by actor and operation, and reject reuse with a different body. Check access for every object ID, job, search run, and PDF. Never include contacts in common errors or public examples. The contract fixes the error model, Idempotency-Key, If-Match, pagination, and time format in [api/README.en.md](../../api/README.en.md#contract-conventions); of these, only the problem-based error mapping is implemented.
|
|
|
|
## Metrics, telemetry, and alerts
|
|
|
|
The Go service exports standard Go/process metrics and the product metrics on an internal `/metrics` listener outside `/api/v1`:
|
|
|
|
- API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}`, and `lincodex_http_problems_total{route,code}`. `route` is the chi route template of an operational route and, under `/api/v1`, the OpenAPI path template of the matched operation, such as `/api/v1/me/invitations/{invitation_id}`, which the router resolves with the generated server's `FindPath`; a path or method without an operation keeps the mount pattern `/api/v1/*` or `/api/*`, and a path outside every route is `unmatched`. `status_class` is `1xx` to `5xx`. `code` is the RFC 9457 problem code: `problem.New` records it from the closed catalogue through the request-scoped `observe` package (`adapter/primary/http/observe/`), the middleware counts it only for a 4xx or 5xx response, and the adapter counts a code outside its mirrored list as `other`. An error without a problem body, such as `/readyz` 503, is counted by status only. The request log (`middleware.RequestLog`, which replaces the go-httpkit logger) uses the same route template and logs the request ID, method, status and class, problem code, latency, response size, and the number of query parameters, never the raw path, a query key or value, a header, the client address, or the user agent; `/healthz` and `/readyz` are not logged.
|
|
- Outbox and events: the relay, consumer, and scheduled job metrics in [Outbox relay](#outbox-relay), [Event consumers](#event-consumers), and [Scheduled jobs](#scheduled-jobs). Outbox lag is `lincodex_outbox_relay_oldest_pending_age_seconds`.
|
|
- Mail: `lincodex_mail_deliveries{kind,status}` for every kind and the statuses `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected`, and `cancelled`, zero included; `lincodex_mail_sender_running`, 1 while this process's mail sending loop runs and 0 otherwise (per process, so aggregate it with `max`; it stays 0 with `EMAIL_PROVIDER=disabled`, where no loop starts); `lincodex_mail_delivery_oldest_due_pending_age_seconds`, which counts only service mail (`domain.ServiceMailKinds`), so a notification backlog never looks overdue; `lincodex_mail_sender_cancelled_total{reason}`, deliveries the sending worker ended without sending, by the closed set of cancel reasons, zero included; and, for an active transport, `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted`, each with `provider` and `window` (`day` or `month`). The sampler in `backend/internal/worker/deliverymetrics/` reads them every 30 seconds on its own one-connection pool: `postgres.DeliveryStatisticsStore` aggregates `deliveries` by kind and status, and `MailQuotaUsageReader.Usage` reads the current windows of the configured account. The delivery aggregate is the sqlc query `GetDeliveryStatistics` in `db/queries/delivery.sql`. It scans the table, which suits the current volume; add an index or per-status counters before the table holds millions of rows. `EMAIL_ACCOUNT` is not a label: it is free operator text that can name a person, and each process reports only its own account. Every instance reports the same database-wide values; aggregate them with `max`. A failed read keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` shows the last read in which every aggregate was read (0 from the sampler start until the first one), and the age gauge exists only after the first successful read. There is no attempt outcome counter yet; the delivery states, the logs of the sending worker, and the `delivery_attempts` history show outcomes.
|
|
- Assessment answers: `lincodex_assessment_answer_saves_total{format,outcome}` with the outcomes `stored`, `unchanged`, `rejected`, and `failed`. PRD 6.6 asks to observe the saving of answers; this is read as the assessment answer command `SubmitMyAssessmentAnswer`. The command is not implemented, so only the hook `Metrics.ObserveAssessmentAnswerSave` exists, and no series appears until the usecase calls it once per command. A value outside the closed sets becomes `other`. The HTTP latency and errors of the command already appear under the route `/api/v1/me/assessment-attempts/{attempt_id}/answers`.
|
|
|
|
Do not use user, candidate, delivery, or request IDs, full URLs or query strings, addresses, or resume content as labels. Unit tests drive the real router and every metric hook with email and UUID fixtures and fail when the exposition contains an email-like or UUID-like value. Go runtime, PostgreSQL, Redis, SeaweedFS, Linux, and Lincodex product dashboard JSON files are maintained project sources, not imported dashboard IDs. Inference metrics are not implemented in the current scaffold.
|
|
|
|
Planned observability work includes bounded measurements for queued jobs, oldest ready age, wait and run duration, retries, and terminal failures; pgxpool state should use bounded nonblocking reads inside Go. Nginx `stub_status` does not provide latency by HTTP status; access logs can provide `request_time` and `upstream_response_time`. cAdvisor is optional if the selected runtime supports it. Redis exporter is included in the separate monitoring Compose project; Prometheus scrapes its internal port 9121. SeaweedFS metrics are scraped directly on internal port 9327, retaining only selected aggregate series without object paths. DCGM exporter is only needed with a local NVIDIA model.
|
|
|
|
The planned browser path is Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. The React SDK is not connected yet. Collect cleaned Web Vitals, JavaScript errors, release, and normalized route; exclude console logs, form content, resume text, and session replay. Remove query strings, fragments, and identifiers from URLs. Limit receiver size, rate, and origin. Request/trace IDs remain log fields, not labels; complete span storage needs a separate backend such as Tempo and is not currently supported.
|
|
|
|
Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailable backend target, a 5xx share above 5% with at least 15 requests in 5 minutes, outbox lag, dead letters and stalled consumers, dead and lagging scheduled jobs, deliveries with an unknown outcome, stale delivery and quota gauges, a used-up mail quota, and overdue deliveries; the last one also requires `lincodex_mail_sender_running` to be 1 on some instance, so it stays silent where no sending loop runs, for example with `EMAIL_PROVIDER=disabled`. It counts only service mail, the kinds the worker sends, so a due notification does not fire it. `LincodexMailCancelledBroken` fires on an increase of `lincodex_mail_sender_cancelled_total` with the reason `content_invalid` or `processing_failed`, the cancellations that mean a broken row or a defect rather than a user action. `promtool test rules` gives every alert a firing case and every guard a silent one. Prometheus evaluates them and shows their state on its /alerts page and in Grafana; no Alertmanager or notification channel is configured, so no alert reaches a person. Future alerts cover latency budget breaches, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure `No Data` and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested.
|
|
|
|
## Requirements coverage
|
|
|
|
| Brief requirement | Target decision | State |
|
|
| --- | --- | --- |
|
|
| Two portals and verified email, pp. 3-4 | identity, roles, company, access checks | Not implemented |
|
|
| Manual or PDF resume, p. 3 | Manual profile first; PDF and ML extend it | Not implemented |
|
|
| Standard PDF, p. 3 | PDFRenderer with Cyrillic and access checks | Not implemented |
|
|
| Questionnaire, grade, test, category, pp. 1-3 | assessment, variants, grade history | Not implemented |
|
|
| Comparable tests and leak resistance, pp. 1-2 | Families, blueprint, rubrics, rotation, pilot | Planned |
|
|
| No forced grade decrease and change frequency, pp. 2-3 | verified/claimed, retry, cooldown, eligibility | Planned |
|
|
| Candidate search and explanation, pp. 3-4 | Hard filters, matching evidence, score components | Basic deterministic search implemented; ML, competition data, and snapshots are not |
|
|
| Refine search without losing prior results, p. 4 | Versioned search runs and server snapshots | Planned |
|
|
| Invitation without a vacancy, p. 3 | Optional vacancy_id | Not implemented |
|
|
| RUB salary range and employer contact, p. 4 | Required bounds and explicit period/tax basis | Not implemented |
|
|
| Status for both sides, p. 4 | State machine and event history | Not implemented |
|
|
| Contacts after acceptance/application, pp. 3-4 | Contact grant, separate DTOs, file access check | Not implemented |
|
|
| Privacy and access to own records, pp. 3, 6 | Consent, object/company authorization, cache and snapshot checks | Required, no implementation |
|
|
| FSP ID and missing history, pp. 2, 6 | External identity and fixture provider; empty history allowed | Real API unknown |
|
|
| Real FSP integration | Port and separate DTO until API is supplied | Not implemented |
|
|
| Recurring assessments, p. 3 | Consent, scheduled worker job, freshness signal | After MVP |
|
|
| Vacancies and applications, pp. 3-4 | vacancy/application and contact grant | After core flow |
|
|
| Unreliable employers and ATS, pp. 2-3 | Verification, complaints, limits, provider adapters | Future plan |
|
|
| Open source, API, launch, pp. 5-6 | Repository, OpenAPI, Compose, instructions | Technical scaffold |
|
|
| Dozens of users, p. 6 | Worker limits, indexes, pagination | No load test |
|
|
| Documentation and validation results, pp. 5-7 | RU/EN docs, API, separate evaluation report | Docs exist; evaluation absent |
|
|
| Presentation and prototype access, pp. 5-8 | Demo environment and backup recording | Unverified |
|
|
|
|
## Quality evaluation and numerical limits
|
|
|
|
The initial matching evaluation proposes 60-100 synthetic candidates and 8-12 varied employer needs. Two people label candidate-need pairs independently and resolve disagreements. Holdout is split by need; near-duplicate profiles do not appear in both tuning and evaluation.
|
|
|
|
Compare keyword search, verified-skill baseline, and ML. Metrics are Precision@5, nDCG@5, hard-filter violations, category coverage, and share of relevant results without FSP history. Define the denominator in advance when fewer than five candidates qualify and report result-set size. A small synthetic sample does not prove quality for the real labor market.
|
|
|
|
Assessment pilot uses equivalent forms and varies their order for part of the participants. Measure grade agreement, score spread, task-level decisions, and separation between stronger and weaker groups against independent expert assessment. Synthetic weak/strong answers help debug scoring but do not replace a human pilot.
|
|
|
|
ML evaluation uses a fixed resume set with labeled fields. Measure extraction errors and invented facts, recommendation usefulness under a human rubric, schema-valid rate, latency, and failures. Record model, prompt/schema version, parameters, and date. Compare with a simple baseline and use lawfully handled, de-identified inputs.
|
|
|
|
These are proposed acceptance targets, not results: 30 concurrent users; p95 profile reads under 500 ms; baseline search under 1 second on demo data, excluding external network time. Set a separate ML budget. Quality and load runs have not been performed.
|
|
|
|
## Future critical checks
|
|
|
|
- No contact data appears before a grant in API, search, PDF, errors, or employer-facing ML explanations. Another company never receives it after acceptance.
|
|
- Candidates cannot read other users' invitations, documents, jobs, or attempts. Companies cannot read other companies' needs or search runs.
|
|
- Failure never lowers grade; first lower-level retry is permitted; concurrent requests cannot bypass the 90-day promotion limit.
|
|
- Repeated submit/accept does not create duplicate results; concurrent state transitions are consistent.
|
|
- The manual path works when ML is off; a worker recovers an expired lease; an old response cannot overwrite a newer document version.
|
|
- Empty FSP history differs from an integration error and does not exclude a candidate.
|
|
- Refinement keeps the earlier snapshot; hidden profiles disappear from older snapshots.
|
|
|
|
## Team milestones
|
|
|
|
The October 11 critical path is email -> profile/questionnaire -> grade selection -> assessment -> category -> search -> salary offer -> acceptance -> contacts. Include a demo candidate with no FSP history. If schedule slips, cut specialty count, AI depth, and decorative screens while preserving the core flow and privacy.
|
|
|
|
Team plan: October 5 - contract, data model, scaffold, and frontend foundation; October 6-9 - identity, profiles, assessments, search, invitations, UI, and ML work in parallel; October 10 - integration and fixes; October 11 - demo. October 12-16 - PDF, grade history, worker reliability, and privacy checks; October 17-22 - assessment pilot and search evaluation; October 23-26 - vacancies or recurring assessments if core work passes; October 27-29 - feature freeze, load test, backup recovery, and presentation; October 30 - final handoff.
|
|
|
|
The application host, ML resources, inference budget, SMTP/domain, and pilot participants remain undecided. Without them, the team cannot promise a public demo, model speed, or categorization quality. The current task creates a technical scaffold; product logic is separate work.
|