Files
lincodex/docs/en/ARCHITECTURE.md
T

201 KiB

Lincodex architecture

This document separates the target product architecture from the technical scaffold in the repository. The requirements source is the specification. Page references in the coverage table use the printed pagination without the cover page. The 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.

This is an operational scaffold. It has no registration, roles, profiles, assessments, grades, candidate search, invitations, resume processing, PDF generation, or FSP integration. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.

See development, deployment, and testing 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. 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 publishes committed events to Kafka. The event consumer runtime applies events idempotently; one product consumer is registered, notification_delivery for mail deliveries. 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.

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 (TASK-030, TASK-458) 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. Idempotent consumers are described in 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 (TASK-009): 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.

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. 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 (TASK-010): 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. One product handler is registered (TASK-015): eventHandlers() in backend/internal/bootstrap/consumers.go returns the mail delivery handler notification_delivery described in Mail deliveries, so a backend with CONSUMER_ENABLED and DATABASE_URL runs one consumer in the group <CONSUMER_GROUP_PREFIX>.notification_delivery. 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.

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.

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.

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 (TASK-035): 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. No product handler is registered yet: jobHandlers() in backend/internal/bootstrap/jobs.go returns an empty list, so the backend logs no scheduled job kind is registered and starts no worker. The tests use a test-only kind. The first planned product kind is the invitation response deadline (TASK-205). Settings are in DEPLOY.md.

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/, TASK-014, 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 (TASK-016, see Sending service mail); product notifications are stored as deliveries but not sent until TASK-462. Settings are described in DEPLOY.md.

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. Provider deduplication has a window (24 hours for Resend); after it a retry may send the message twice, so the delivery layer must stop retrying and escalate to an operator.

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. Retries, backoff, and recording outcomes belong to a single planned delivery layer, not to the transport. The verification flows (TASK-053, TASK-054) 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 (TASK-017), the sending worker applies only the minimum schedule described in Sending service mail, and the stop at the end of the 24-hour key window is the sending worker's rule for an attempt whose worker was lost; waiting for a quota reset is decided by the quota gate described in Mail quotas.

Mail deliveries

Implemented (TASK-015): 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 with TASK-018; see Mail quotas. Implemented (TASK-016): the worker that claims due service mail, checks its token and account, passes it through the quota gate, and calls MailSender, with migration 00012_add_delivery_sending.sql; see Sending service mail. Planned: retries and the unknown outcome policy (TASK-017), and sending product notifications with the permission check before a send (TASK-462). The delivery state gauges are implemented with TASK-022; see Metrics, telemetry, and alerts. No product flow calls MailRequester yet, and no identity flow calls ServiceMailer yet (registration and reset are separate tasks), so a stored notification waits and no service mail exists outside the tests.

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 (TASK-016), which uses domain.NewDelivery and DeliveryRepository.Create and binds the delivery to the token; the identity flows that call it (registration, resend, reset) are separate tasks.

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.
  • 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), 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 (TASK-022) 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": a retry reuses the key and the stored body Optional; none means no automatic retry
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); 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 TASK-018's local 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 (TASK-017) 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 history is what an operator needs to judge an unknown outcome, what the end of the 24-hour key window counts from (the first attempt), and what an audit of a manual decision refers to. 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.

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). TASK-016 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 (TASK-016) 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 (TASK-462).

The store provides Get, ListAttempts, the version-checked RecordAttempt, WaitForQuota, Cancel, and Rebind, and for the sending worker ClaimDue, ReleaseClaim, and ServiceMailState.

Mail quotas

Implemented (TASK-018): 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 (TASK-016) 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. Planned: the API or identity flow that shows the status reader's result. Only service identity mail counts against the quota while TASK-462 is open.

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 (TASK-017).
  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 (TASK-017), 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). 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. 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 (TASK-022) come from MailQuotaUsageReader.Usage for the configured account, with the labels provider and window only; see Metrics, telemetry, and alerts.

Sending service mail

Implemented (TASK-016): the sending usecase ServiceMailSender (backend/internal/usecase/notification/service_sender.go), the enqueue usecase ServiceMailer (service_mail.go), the minimum retry schedule RetryPolicy (send_retry.go), Delivery.CheckServiceMail and Delivery.Cancel with the cancel reasons (backend/internal/domain/delivery.go, delivery_guard.go), the loop in backend/internal/worker/mailsender/, the inbound port inbound.MailPass (port/inbound/mail_sender.go), the repository methods ClaimDue, ReleaseClaim, Cancel, and ServiceMailState, migration 00012_add_delivery_sending.sql, the gauge lincodex_mail_sender_running, and the wiring in bootstrap/mail_sender.go. Not implemented: sending product notifications (TASK-462), the retry and unknown outcome policy (TASK-017), and the identity flows that call ServiceMailer.

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 route reads the fragment and sends the token in the body of an API request. A query would be needed only if a frontend route could not read the fragment, and then the page would have to send the token onward and the access log would see it, so the fragment is the choice. 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 or waiting_quota, next_attempt_at passed, pinned to the configured provider account, and held by no live lease. 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. A delivery in unknown, or in waiting_quota without a time, has no due time and waits for an operator. 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 notes first_send_started_at the first time. 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 sender never retries. 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 none: no automatic retry (TASK-017) 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. unknown is never read as not sent and is never repeated by the worker; an operator decides, and the alert LincodexMailDeliveryUnknownOutcome fires.

A worker lost after the call. If a worker stops after it called the provider but before it stored the answer, its lease expires and another worker claims the delivery on the same attempt and repeats the request with the same idempotency key. 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. 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 is not terminal and keeps its body, because a retry resends it; an operator who resolves it must clear it. 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. It is a test fixture only; production binds the real Resend transport with its fixed endpoint.

Open points. unknown has no automatic retry or escalation until TASK-017. Sending notifications, and the permission check they need, belong to TASK-462; until then they 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.

Product policy versions

Implemented as storage, a publisher, and a startup seed (TASK-005): 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 TASK-087); every organization starts at E0, and the rules that move it between tiers belong to the quota feature.

Open question for the attempt tasks (TASK-157 and TASK-158): MaxAttemptsPerWindow stores only the number. Whether the limit counts per grade, per specialty, or across all assessments of a candidate is not decided.

The document has schema_version 1 and the sections invitations, organization_quotas, assessment, identity, and search_status; field names carry their unit (_days, _business_days, _hours, _bp). Decoding is strict: it rejects unknown fields, missing or null fields, wrong types, fractions, values outside int32, an unknown schema version, trailing data, and documents over 64 KiB. The canonical form is the compact Go encoding in field declaration order. jsonb normalizes key order, so domain.RestorePolicyVersion decodes the stored document, validates it, encodes it again, and compares its SHA-256 with document_sha256; a mismatch returns domain.ErrPolicyDocumentIntegrity. A golden test pins the canonical form, because a change would make every stored version fail this check; a new layout needs a new schema version and decoder.

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). 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 use the same assessment values.

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.

Repository map and package purpose

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
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.

Product domain types and usecase modules, the SMTP and FSP adapters, and product worker jobs are reserved areas; their business behavior is not implemented. Keep main.go limited to starting bootstrap and handling 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 handler, the scheduled job runtime (worker/jobrunner) with no registered product job kind, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the PasswordHasher port with the Argon2id adapter and the password check that registration will call, 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 sending worker of service identity mail, which no account flow feeds yet. Account behavior (registration, verification, login, sessions), 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/ instead: 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 renders verification and password reset mail with it when the identity usecases issue a token, and those usecases (registration, resend, reset) are separate tasks. Templates, versions, and link format are described in DEPLOY.md. 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.

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; 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 (TASK-154), 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.

Matching and explanations

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.

Initial baseline after filtering:

score = 0.50 * skill_fit
      + 0.40 * assessment_score
      + 0.10 * fsp_evidence

Each component ranges from 0 to 1. skill_fit is weighted coverage of verified requested skills. assessment_score is the result for relevant assessment sections. fsp_evidence is a small bonus for relevant verified achievements. An empty skill set uses a predefined neutral value and avoids division by zero. Use a stable ID tie-break, never personal characteristics.

No FSP history gives a zero bonus without excluding the candidate. Synthetic achievements are marked and affect demo data only. Results include score_components, reason_codes, evidence, and gaps. A candidate with a verified Middle grade and 4 of 5 covered skills still fails a filter that requires confirmation of all five.

This is an initial baseline, not an optimized or measured ranking model. The plan compares keyword search, the verified-skill baseline, and an ML variant. Add a semantic signal only after an experiment; never treat 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.

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. 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

Implemented as storage only (TASK-051): migration backend/db/migrations/00002_create_identity_tables.sql, queries in backend/db/queries/identity.sql, domain types in backend/internal/domain/, ports in backend/internal/port/outbound/identity.go, and the sqlc-backed adapter in backend/internal/adapter/secondary/postgres/identity.go. The registration, verification, login, and session behavior described in api/README.en.md is planned (TASK-053 to TASK-056); no usecase or handler uses this storage yet.

  • 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 the allowed purposes, so a 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. 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. 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 is expected to answer 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 must return the session's CSRF token after a reload, which a stored hash cannot reproduce. TASK-056 can derive the token from the session token with a server key, which needs no storage, or add a column in an additive migration.

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). 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 (TASK-054) 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 writes last_seen_at only when the stored value is more than one minute older, so frequent requests do not rewrite the row and the idle timeout can end a session up to a minute early; 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 (TASK-052) and tested, but not wired into bootstrap: registration (TASK-053) and login (TASK-055) will create the hasher from configuration and call it.

  • 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; request rate limiting comes with the HTTP operations.
  • 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, so a login can store a new hash.
  • 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 will call it for an unknown email, so both branches parse, wait for memory, derive, and compare alike.
  • Login (TASK-055) must answer 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 must also log an error and call VerifyDummy. Remaining timing differences: a corrupt hash is refused without a derivation, which VerifyDummy compensates, and a hash with older parameters costs what its own parameters cost until the next successful login rehashes it.
  • identity.Credentials.HashNewPassword validates a new password and only then hashes it; registration will call it on every branch before it looks 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.

Implemented as storage, ports, and a read contract (TASK-062): migration backend/db/migrations/00009_create_consent_ledger.sql, queries in backend/db/queries/consents.sql, domain types in backend/internal/domain/consent.go, the ports in backend/internal/port/outbound/consents.go, the sqlc-backed adapter in backend/internal/adapter/secondary/postgres/consents.go, and ListMyConsents in the public contract (api/README.en.md). Granting C1-C3 and C5 with a current-version check is implemented as the usecase consent.Service (TASK-063, see Consent usecase). Revocation with its downstream effects and the HTTP handler (TASK-064), C1 in the registration transaction (TASK-053), and C4 in the invitation acceptance (TASK-201) are planned; no product flow calls the usecase yet.

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), 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 (TASK-063) 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. The downstream effects of a revocation (deletion request for C1, closing publication and grants for C2 and C4, the manual path for C3, stopping the import for C5) belong to TASK-064 and are not implemented.
  • 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. Whether a deleted account leaves its ledger, a tombstone, or nothing is decided by the C1 deletion request of TASK-064 and the account deletion procedure that executes it, which has no MVP task yet; the retention rule extends the delete condition in its own migration.
  • 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 TASK-053: the registration usecase calls UpdateRegistration and records the new C1 with consent.Service.GrantAtRegistration, strictly after UpdateRegistration, in the same transaction (see 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 evidence of the publication history of TASK-088, which must keep them with their times. 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 acceptance (TASK-201) calls it in the transaction that moves the invitation to accepted, creates the grant, and writes the audit event, so all of them commit or roll back together. A repeated acceptance gets the existing record with created false and compares its scope; an invitation whose C4 belongs to another subject returns 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.

Implemented (TASK-063): consent.Service in backend/internal/usecase/consent/. It is not wired into bootstrap yet, because no handler or registration flow calls it; the first caller builds it with consent.NewService(transactor, clock), the Transactor and the application clock that the other usecases already receive. A nil transactor or clock panics at construction, so a wiring mistake shows at startup and not at the first grant.

  • Entry points fix the source. GrantAtRegistration(ctx, repositories, subjectID, version) records C1 with the source registration; GrantInSettings(ctx, repositories, SettingsGrantInput) records C1, C2, C3, or C5 with the source consent_settings. Neither takes a source or a time, so a handler cannot read either from the client. repositories is an outbound.ConsentRepositories: pass the UnitOfWork of a business operation and the grant commits or rolls back with it. The registration (TASK-053) creates the account and records C1 in one transaction on the subject ID alone, so no session is needed. GrantInSettingsInNewTransaction opens its own transaction for a grant that is not part of another operation, and retries an ErrTransactionConflict up to three attempts in total with a short jittered wait (10 ms plus up to 10 ms) between them, which is safe because a repeat is idempotent; the wait ends at once 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.
  • 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 (TASK-053) 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 (TASK-201): 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 code path requires an active C3 for the profile, the manual assessment path, or another function. A subject without C3 has no C3 record, and Current returns ErrConsentNotFound for it, which is not an error state of the account. Whoever reads C3 (the manual assessment request of TASK-315, the revocation of TASK-064) treats a missing record as "not given" and keeps the manual path open.
  • No revocation here. Revoke stays on the ledger port, and TASK-064 calls it with the downstream effects and the outbox events in one transaction.
  • 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 (TASK-064, TASK-053, TASK-201).
  • 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 TASK-064, and neither exists yet.

Organizations and memberships

Implemented as storage, ports, and a source contract (TASK-077): migration backend/db/migrations/00010_create_organizations.sql, queries in backend/db/queries/organizations.sql, domain types in backend/internal/domain/organization.go and membership.go, the ports in backend/internal/port/outbound/organizations.go, the sqlc-backed adapter in backend/internal/adapter/secondary/postgres/organizations.go, and ListMyOrganizations, CreateOrganization, GetOrganization, and UpdateOrganization in the public contract (api/README.en.md). The create, read, and update usecases with their handlers (TASK-078) and the server-side context and membership checks of every tenant operation (TASK-079) are planned; until then the operations answer 401 or 501 and nothing in bootstrap calls the repositories. The only implemented behavior is the storage and its constraints.

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 decision follows TASK-079 (the context comes only from the caller's active memberships, and a terminated membership closes reads at once) and TASK-085 (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 (TASK-081, TASK-082). 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 (TASK-083, TASK-463).
  • 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; TASK-086 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 (TASK-087 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 (TASK-084), 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 of TASK-084, which changes a membership and the organization together, and the tenant repository of TASK-079 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 ledger tests of TASK-062 and TASK-063 to create real organizations, and the same migration has to add the invitation_id key, which needs the invitation table; both arrive with the migration that creates the invitation records (TASK-198), together with the keys of needs (TASK-179). All of them are ON DELETE RESTRICT, so an organization with consent history, 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 (TASK-078) 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 delete it at the end of the replay window; 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 (TASK-078 and TASK-087 need the owner's decision, and the prepared mechanism is a 409 state_conflict on create), are in api/README.en.md.

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.

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; 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 of TASK-022 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, Event consumers, and 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 Not implemented
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.