# Lincodex architecture This document separates the target product architecture from the technical scaffold in the repository. The requirements source is the [specification](../../requirements/specification.pdf). Page references in the coverage table use the printed pagination without the cover page. The [brandbook](../../requirements/brandbook/) is stored alongside the specification. The team supplied October 11 and October 30, 2026, as project milestones. ## Current scaffold The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface scaffold with public pages and two cabinet shells of placeholder screens, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port. 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](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTING.md) for source layout, commands, and current check coverage. ## Target system The target is a modular Go backend with Clean Architecture, a React SPA using Vite and FSD, and a separate ML HTTP service in one repository. The planned Go process runs the HTTP API and background worker together. PostgreSQL stores product records and jobs; Redis provides the cache. Private S3-compatible SeaweedFS storage is selected for resumes and generated PDFs; the file workflows are not implemented yet. The initial target uses Docker Compose on one application host, with ML in a separate environment. Go owns authorization, verified categories, invitations, contact grants, and final search results. ML proposes resume fields, helps interpret employer needs, and can take part in semantic search experiments. Model outages must leave manual profiles, assessments, filter-based search, and invitations available. Combining API and worker simplifies the demo deployment, while sharing process lifecycle, memory limits, and metrics registry. The worker can move to its own process when independent scaling is needed without moving usecases or ports. That worker is planned. The project brief assigns 35% of its score to matching, 25% to assessment and categorization, and 7% to technical implementation. The October 11 milestone calls for a working prototype flow. Technical work alone does not provide that flow. ## Contracts and code generation The contract roots are split by boundary: api/core/ contains browser-to-Go operations, and api/ml/ contains internal Go-to-ML operations. The shared Makefile, package.json, and Redocly configuration stay under api/. Python schema tools live in the repository-level scripts/ directory. Each contract is assembled from small source YAML files. The public Go handler is generated by ogen from backend/codegen/ogen.yml and mounted in chi. Orval independently generates the TypeScript client, TanStack Query hooks, Zod schemas, and MSW handlers. The ML Go client is configured at backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. datamodel-code-generator produces Pydantic v2 models from the same ML bundle in ml/src/lincodex_ml/api/models.py; the health/readiness handlers use these models. Python generator settings live in ml/codegen/pyproject.toml, while dependencies remain in ml/pyproject.toml. Backend sqlc configuration is backend/codegen/sqlc.yml and its generated SQL adapter is under backend/internal/adapter/secondary/postgres/sqlc/. Frontend configuration is frontend/codegen/orval.config.ts. There are three codegen directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Configuration belongs to the service that uses the generated code. OpenAPI 3.2.0 is the target version. Verify the subset used here across bundling and lint, ogen, the chi adapter, the API runtime path, Orval, Python Pydantic models, and documentation. A parser version or one fixture does not prove support for every OpenAPI 3.2.0 feature. The public API prefix /api/v1 is applied once. The internal /metrics endpoint remains separate. Health operations use names ending in z: healthz and readyz. Generated types and request validation do not implement ownership checks, company membership, consent, or valid product state transitions. Generate bundles from contract sources, then regenerate each Go, TypeScript, and Python consumer through its Make target. A contract change includes generation and drift checks for every consumer. Never edit generated files by hand. ## Service and data boundaries The planned backend boundaries are: - Primary adapters receive HTTP requests and translate them into inbound ports. - Usecases implement application flows and depend on domain rules and ports. - Secondary adapters implement storage, ML, email, and file operations. - Bootstrap wires implementations and controls process startup and shutdown. - Product rules stay in domain and usecase code, away from chi handlers, workers, SQL, and ML. Shared Go configuration belongs in backend/config/ outside internal. wahrwelt-kit logkit 0.6.0, httpkit 0.7.0, and cachekit 0.7.0 currently provide technical functions. Metrics use bounded custom collector/middleware code, and pgxpool collection must not block startup. pgkit and httpkit/metrics are not currently used. Technical libraries do not own product rules. Do not add unselected JWT or WebSocket dependencies for hypothetical features. PostgreSQL with pgx, sqlc, and goose is the database stack. Developers own SQL; sqlc generates typed adapters. goose manages versioned migrations: the SQL files are embedded in the binary, and the backend applies them at startup under a PostgreSQL advisory lock before it opens its listeners. wire provides compile-time dependency construction in bootstrap, with no runtime DI container. API and worker share the database pool in the planned single-process deployment. Redis is part of the core Compose project and connects through `backend/internal/adapter/secondary/redis/` to the outbound cache port. The adapter provides Get/Set/Del with TTL; bootstrap manages client construction and cleanup. The internal /readyz requires PostgreSQL, Redis, and the SeaweedFS bucket to be available. The cache is not a source of truth: future consumers must tolerate key eviction and Redis restarts. Profile, search, resume, and other product caching rules are not implemented yet. SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. Resume uploads, authorization, content limits, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup. The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. The [event consumer](#event-consumers) runtime applies events idempotently; no product consumer is registered yet. 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. ### Transactional outbox Implemented: migration `backend/db/migrations/00001_create_outbox_events.sql` creates `outbox_events`. Columns: - `position`: a bigint identity, unique and monotonic in insertion order; the relay scans by it. - `event_id`: uuid primary key, a UUIDv7 generated in Go. - `event_type`: a lowercase dotted name of at most 128 bytes. - `schema_version`: an integer above zero. - `aggregate_type`: snake_case, at most 64 bytes. - `aggregate_id`: a uuid. - `aggregate_version`: a bigint above zero. - `payload`: a jsonb object. - `occurred_at`: `clock_timestamp()` at insert. It is informational only and does not define order. - `published_at`: null until the relay publishes the row. A unique key on aggregate type, aggregate ID, aggregate version, and event type rejects a second event of the same type for the same aggregate version. A partial index on `position` where `published_at` is null serves the relay scan. CHECK constraints repeat the domain rules for versions, names, and the object payload as a backstop. The payload size limit lives only in Go, because the jsonb text and binary sizes differ from the compact input and a database length check could reject an event the domain accepted. A usecase writes through outbound ports. `Transactor.WithinTransaction(ctx, fn)` opens one READ COMMITTED transaction and passes a `UnitOfWork`; every repository it returns, including `Outbox().Append(ctx, events...)`, uses that transaction. The transaction commits when fn returns nil and rolls back when fn returns an error, panics, or its context is canceled. Calling `WithinTransaction` again with the callback context returns `outbound.ErrNestedTransaction` instead of opening a second connection. A conflict on the event ID or the unique key returns an error that wraps `outbound.ErrOutboxEventConflict` and names the constraint. A network error during commit leaves the outcome unknown, so callers that retry must be idempotent. The outbox uniqueness rule is a backstop, not concurrency control. Aggregate updates still check the expected version (`UPDATE ... WHERE version = $n`), so a stale writer fails before it records an event. `domain.NewDomainEvent` validates the event. The compact JSON payload is limited to 16 KiB and 32 nesting levels; numbers must fit a float64; NUL characters are rejected because jsonb cannot store them. jsonb normalizes the stored payload (key order, whitespace, duplicate keys), so consumers compare JSON values rather than bytes. Payloads carry identifiers and minimal facts only, never contact data, tokens, passwords, or resume and document contents. The relay that publishes these rows is described in [Outbox relay](#outbox-relay). Idempotent consumers are described in [Event consumers](#event-consumers). Still planned: retry bookkeeping columns (attempt count and last error) and retention of published rows. Bootstrap does not wire the transactor yet because no product usecase uses it; the first business transaction wires it together with a shared pool. ### Outbox relay Implemented (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](DEPLOY.md#outbox-relay). One pass is one READ COMMITTED transaction: 1. `SetRelayTransactionTimeouts` sets `statement_timeout` to `RELAY_STATEMENT_TIMEOUT` and `idle_in_transaction_session_timeout` to `RELAY_PRODUCE_TIMEOUT + RELAY_STATEMENT_TIMEOUT` for this transaction only (`SET LOCAL` through `set_config`). The pass context already cancels a slow pass of a live process; these server-side limits also hold when the process freezes or loses the network without closing the connection, so the server ends the transaction and releases its row locks instead of waiting for TCP keepalive. 2. `LockPendingOutboxEvents` selects rows with `published_at IS NULL` in `position` order, at most `RELAY_BATCH_SIZE`, with `FOR UPDATE OF pending SKIP LOCKED`. A row qualifies only when it is the earliest unpublished event of its aggregate (lowest `aggregate_version`, then `position`). There is no `position` or `occurred_at` watermark; every pass scans the unpublished rows again. 3. The relay publishes the batch and waits for the broker acknowledgements, at most `RELAY_PRODUCE_TIMEOUT`. 4. `MarkOutboxEventsPublished` sets `published_at` for exactly the acknowledged event IDs, and the transaction commits. Several relays, for example several backend instances, can run against one database. SKIP LOCKED lets them take different rows without waiting. Plain SKIP LOCKED would let a second relay skip a locked version 1 and publish version 2 first; the earliest-event rule prevents that, because version 2 does not qualify while version 1 is unpublished, whether another relay holds it, a failed pass left it pending, or a pass rolled back. The rule relies on aggregate writers checking the expected version: version 2 then commits only after version 1, so a statement that sees version 2 also sees version 1. Migration `00004_add_outbox_relay_index.sql` adds the partial index `(aggregate_type, aggregate_id, aggregate_version, position) WHERE published_at IS NULL` for this check. Trade-off: a pass publishes at most one event per aggregate, so a burst of N events of one aggregate needs N passes. A pass that found events starts the next one immediately, and different aggregates share a batch and spread across relays. Selection cost. The plan is a nested-loop anti join: an index scan of `outbox_events_unpublished_idx` in `position` order, one probe of `outbox_events_unpublished_aggregate_idx` per scanned row, and LIMIT on top, with no sort over the backlog; the generic plan of the prepared statement is the same. A pass reads rows until it has found `RELAY_BATCH_SIZE` aggregate heads, so it reads every non-head row in front of them. Measured with `EXPLAIN ANALYZE` on PostgreSQL in a scratch container with 100,000 pending rows and a batch of 100: 0.2 ms and 100 rows read when versions of 1,000 aggregates interleave; 16 ms and 9,901 rows read when each aggregate's 100 versions are contiguous; 225 ms and about 50,000 rows read when one aggregate has 50,000 pending versions ahead of 1,000 other aggregates. In the last case the hot aggregate drains one version per pass and every pass reads its remaining versions again, so draining k pending versions of one aggregate costs O(k²) row reads. Product aggregates change a few times per business action, so k stays small; a large k appears only when a writer emits many versions of one aggregate during a long Kafka outage. Publishing several consecutive versions of an aggregate whose head a pass has locked would remove that cost and is a possible later change. Kafka record: - Topic: `KAFKA_EVENTS_TOPIC`, `lincodex.domain.events` by default. All events go to one topic; consumers filter by `event_type`. One topic is enough while consumers are few, and per-aggregate order needs only the key. - Key: `:`. The default franz-go partitioner hashes the key, so all events of an aggregate land in one partition in publication order. - Value: a compact JSON envelope with `envelope_version` (currently 1; changes only with the envelope fields), `event_id`, `event_type`, `schema_version` (the payload layout version of that event type), `aggregate_type`, `aggregate_id`, `aggregate_version`, `occurred_at` (RFC 3339 in UTC, informational), and `payload` (the stored jsonb object, so key order can differ from what the writer appended). - Headers: `event_id`, `event_type`, `schema_version`, so a consumer can deduplicate and route without decoding the value. The producer uses acks from all in-sync replicas and idempotent writes (the franz-go default). By default franz-go cannot fail an in-flight idempotent record until the broker answers, so behind a frozen broker the record and every later record of its partition would wait indefinitely. The relay enables `AllowIdempotentProduceCancellation`, which lets the delivery timeout and the pass deadline fail such a record, and `Publish` stops waiting at the deadline in any case. The client retries a record at most five times within one publish; later attempts belong to the next pass. Kafka does not create topics on demand: before its first pass the relay calls `Prepare`, which creates `KAFKA_EVENTS_TOPIC` through `kadm` with `KAFKA_EVENTS_TOPIC_PARTITIONS`, `KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR` (-1 by default, the broker's `default.replication.factor`), and, when set, `min.insync.replicas` from `KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS` (otherwise the broker default). It accepts an existing topic without changing it and logs one warning when that topic has another partition count or, with an explicit replication factor, another replication factor. A failed `Prepare` does not block startup: the relay retries it with backoff and events stay pending. When a publish reports an unknown topic, for example after the topic was deleted, the relay calls `Prepare` again before its next pass. With acks from all in-sync replicas, a write is durable only on `min.insync.replicas` brokers; the production requirement is in [DEPLOY.md](DEPLOY.md#outbox-relay). With `KAFKA_PROVISION_TOPICS=false` the topic is managed outside the backend. Adding partitions later moves keys to other partitions, so per-aggregate order is not guaranteed across that change. Failure semantics: - Kafka unavailable: the publish fails within `RELAY_PRODUCE_TIMEOUT`, nothing is marked, and the rows stay pending. The relay logs a warning with counts and the error (event IDs and broker errors, never payloads), waits a backoff, and retries indefinitely. The backoff starts at `RELAY_BACKOFF_INITIAL`, doubles with every consecutive failure up to `RELAY_BACKOFF_MAX`, and waits half the current value plus a random share of the other half. Business transactions write only to PostgreSQL, so an outage never rolls back a saved business action. - Partial acknowledgement: only acknowledged events are marked; the rest are retried on later passes. Because a pass holds at most one event per aggregate, a failed event never lets a later version of its aggregate through. A pass that published at least one event resets the backoff and is followed by the next pass at once, so a failing event does not slow down the others; the backoff grows only across passes that published nothing. - A failure after publish and before commit, including a crash or a lost database connection: the rows stay unpublished and a later pass publishes them again with the same `event_id`. A record whose publish timed out can also reach the broker later. Delivery is at least once: consumers must deduplicate by `event_id` and ignore an `aggregate_version` they already applied, because a late duplicate of an earlier version can follow a later version. - Shutdown: when the process receives SIGTERM, the relay starts no new pass. A pass in progress has `SHUTDOWN_TIMEOUT` to finish and commit; after that it is canceled and its transaction rolls back. An unacknowledged event is never marked. Bootstrap closes the producer and the relay's pool only after the relay stopped. - The transaction stays open during the publish, holding row locks on at most `RELAY_BATCH_SIZE` outbox rows and one connection for at most `RELAY_PRODUCE_TIMEOUT`. Business writes only insert new rows and are not blocked; the bound also limits how long the open transaction delays vacuum. A smaller batch or timeout shortens it. - An event the broker rejects every time (a poison event; not expected, because the payload is at most 16 KiB and the topic is provisioned) blocks its own aggregate. While a pass still publishes other events, the relay keeps going at full speed. Because `ORDER BY position` returns the oldest heads first, every pass claims the poison heads again; when `RELAY_BATCH_SIZE` or more aggregate heads are poison, they fill the whole batch, no pass publishes anything, and the relay stalls at one pass per `RELAY_BACKOFF_MAX` while the backlog grows. An operator sees `failed` in `lincodex_outbox_relay_events_total` rising while `published` stays flat, `lincodex_outbox_relay_oldest_pending_age_seconds` growing, and warnings with the event IDs of the batch. The usual causes are on the Kafka side (the topic, its ACLs, or `min.insync.replicas` above the live replicas); after that is fixed, the next pass publishes everything. A raised `RELAY_BATCH_SIZE` lets other aggregates through meanwhile. There is no dead-letter path: an event that can never be published needs a decision by the owners of its consumers, and marking it published by hand skips it for every consumer. The metric `lincodex_outbox_relay_events_total{outcome}` counts published and failed events; a pending event is counted as failed on every attempt. The gauges `lincodex_outbox_relay_pending_events` and `lincodex_outbox_relay_oldest_pending_age_seconds` show the unpublished events and the age of the earliest one by `position`, measured by the database clock. The relay reads them with `GetOutboxBacklog`, which uses the partial index, at most once every 15 seconds, also while it retries `Prepare`, so a busy relay does not count the outbox on every pass. Every backend instance reports the same database-wide values; aggregate them with `max`. `/readyz` does not check Kafka, so a Kafka outage does not take the API out of service. ### Event consumers Implemented (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](#mail-deliveries), so a backend with `CONSUMER_ENABLED` and `DATABASE_URL` runs one consumer in the group `.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](DEPLOY.md#event-consumers). A handler implements three methods: - `ConsumerName()`: a snake_case name of at most 64 characters. It names the Kafka consumer group `.` and scopes deduplication, so renaming a consumer makes it process every retained event again. - `Handles(eventType)`: events of other types are counted as `ignored` and committed without a transaction. - `Handle(ctx, unit, event)`: receives the decoded envelope and an `outbound.UnitOfWork` bound to the transaction that holds the dedup marker. The effect must use only that unit. An error that wraps `inbound.ErrEventRejected` is final; any other error is retried. Errors must not quote the payload or personal data, because their text is logged and stored with a dead letter. Deduplication uses `event_id` only. Order by `aggregate_version` stays with the handler: a replayed dead letter can arrive after a later version of its aggregate, so a handler that keeps aggregate state ignores a version it has already passed. One record is processed as follows: 1. The Kafka adapter decodes the envelope. It requires `envelope_version` 1, a non-nil `event_id`, the domain rules of `domain.NewDomainEvent` for type, schema version, aggregate type, ID, and version, a non-zero `occurred_at`, a JSON object `payload`, and an `event_id` header, when present, equal to the envelope field. A record that breaks a rule is an invalid record; the handler never sees it. The error names the broken rule and never quotes the value. 2. One READ COMMITTED transaction sets `statement_timeout` and `idle_in_transaction_session_timeout` to `CONSUMER_HANDLER_TIMEOUT` for this transaction only, runs `INSERT INTO consumer_processed_events (consumer_name, event_id) ... ON CONFLICT DO NOTHING`, and checks the row count. Zero rows means the event was applied before: the transaction rolls back and the record is a `duplicate`. One row means the handler runs in the same transaction, and the effect commits together with the marker. 3. The offset is committed only after that commit, or after the dead letter row is stored. Why `ON CONFLICT DO NOTHING` in the same transaction as the effect. The marker is inserted before the effect, so the effect runs only while its transaction holds the uncommitted marker. A concurrent delivery of the same event, from another instance or after a rebalance, waits on that unique key until the first transaction ends: after a commit its insert affects zero rows and it skips the effect; after a rollback its insert succeeds and it applies the event itself. The effect therefore never runs twice or in parallel, and the outcome does not depend on timing. A plain `INSERT` that fails on the unique key waits the same way, but a duplicate then aborts the transaction with SQLSTATE 23505, puts an expected case into the PostgreSQL error log, and drives control flow by error. Checking with a `SELECT` before the insert leaves a race window under READ COMMITTED. The server-side timeouts end the transaction of a frozen process, so its marker cannot block a duplicate indefinitely. Offsets and partitions. Each consumer is one member of its group with autocommit off and franz-go `BlockRebalanceOnPoll`. It polls at most `CONSUMER_MAX_POLL_RECORDS` records and processes them one at a time in poll order, which keeps the order within every partition. After the batch it commits, for each partition, the position after the last finished record (with its leader epoch), and only then allows a rebalance. Because rebalances wait for that point, a commit never lands on a partition the member no longer owns. A failed commit is logged; the position is retried with the next commit and when the partition is revoked, and dropped when the partition is lost, in which case the next owner receives the records again and the markers turn them into duplicates. A new group starts at the earliest retained record, so a new consumer never skips an event. The adapter refuses a commit whose finished records are not, per partition, the first records of the last poll without a gap, so a commit can never move past an unfinished record. Rebalance budget. A batch holds rebalancing while it runs. If it takes longer than the rebalance timeout, the broker removes the member, its commit fails, and the new owner reprocesses from the last committed offset; deduplication makes that harmless, but the work is repeated. The timeout is set explicitly from `CONSUMER_REBALANCE_TIMEOUT` (60 seconds by default), and configuration refuses to start when the slowest record does not fit in it with a 5-second margin. The slowest record without a database outage is `CONSUMER_MAX_ATTEMPTS` handler attempts, the longest backoff before each retry, one dead letter write (each bounded by `CONSUMER_HANDLER_TIMEOUT`), and one offset commit (`CONSUMER_COMMIT_TIMEOUT`): 42.5 seconds with the defaults. A record is the unit because the consumer commits the finished prefix of a batch right after every record that needed a retry or a dead letter, so a member removed during the next slow record does not make its successor repeat the earlier ones. A database outage is not part of the budget: store failures are retried without a bound, and the removal they can cause only repeats work. The alternative, stopping a batch early when franz-go reports a blocked rebalance (`OnPartitionsCallbackBlocked`), would leave polled but unprocessed records behind on the partitions the member keeps; they would be skipped unless the fetch position were rewound with `SetOffsets`, which franz-go documents as prone to odd interactions inside a poll loop. The static budget is simpler and testable. Failures, retries, and dead letters: - Handler error: up to `CONSUMER_MAX_ATTEMPTS` attempts with the same backoff as the relay: the wait starts at `CONSUMER_BACKOFF_INITIAL`, doubles up to `CONSUMER_BACKOFF_MAX`, and is half the current value plus a random share of the other half. Each attempt is bounded by `CONSUMER_HANDLER_TIMEOUT` and rolls back its effect and marker. When the attempts run out, the record becomes a dead letter of class `retries_exhausted`. `inbound.ErrEventRejected` gives `handler_rejected` after one attempt. A handler panic is recovered, the transaction rolls back, the stack is logged without the panic value, and the record becomes `handler_panic`, so one event cannot crash the process on every delivery. - Invalid record: a dead letter of class `invalid_record` with zero attempts. - Refused commit: when the handler returns nil but PostgreSQL refuses the commit, the event is at fault, not the database. `pgx.ErrTxCommitRollback` (the handler ignored a failed statement, so the transaction was aborted) and SQLSTATE class 23 (a deferred integrity constraint) match `outbound.ErrEventEffectRejected`; class 40 (serialization failure or deadlock) matches `outbound.ErrTransactionConflict`. Both count as a handler attempt and are retried with backoff, so a deterministic refusal ends in `retries_exhausted` instead of a retry loop without end. Class 40 is transient by nature and usually succeeds on the next attempt; it still uses up an attempt so that a handler that deadlocks every time cannot retry forever. The same applies to a panic in `Handles`, which gives `handler_panic` without an attempt. - Store failure (begin, marker, a commit lost in transport, or the dead letter write): it does not use up the handler's attempts, because the event is not at fault. The consumer retries with the same backoff until the database answers or shutdown begins, and never dead-letters a record because the database was down. The offset stays uncommitted meanwhile, so a database outage stops the partition without a hot loop and loses nothing. - After the dead letter row exists, the offset is committed and the partition continues with the next record. A dead letter writes no marker, so a later replay of the event is applied. `consumer_dead_letters` stores the consumer name, topic, partition, offset, `event_id` (from the envelope, or from the `event_id` header of an invalid record; NULL when neither is a UUID), `event_type` (NULL for an invalid record), the class, a reason of at most 256 printable characters, the attempt count, the value size, its SHA-256, and the time. A unique key on consumer, topic, partition, offset, and value digest keeps one row per record: when the same record fails again, after a crash before its offset commit or a rewind of the group, the row gets the new class, reason, attempt count, and time. The digest is part of the key because a topic that was deleted and created again reuses offsets; a different value at a reused position is another record and keeps its own row instead of being dropped. Handler errors reach the reason and the logs only after the store replaced the text of any PostgreSQL error in them with its SQLSTATE and constraint, because a PostgreSQL message can quote row values. The record value itself is not stored. A valid event is still in `outbox_events` under its `event_id`, which is also the replay source, so a second copy would only duplicate data that events may carry later and that a dead letter table would keep without a retention rule. An invalid record did not come from the relay; while the topic retains it, an operator can read it by topic, partition, and offset, and the SHA-256 confirms it is the same value. The replay procedure is in [DEPLOY.md](DEPLOY.md#dead-letters-and-replay). Lifecycle. Startup runs the migrations, then wire builds the consumers: one PostgreSQL pool shared by all of them with one connection per consumer (a consumer holds one transaction at a time and writes a dead letter only after it ended) and one franz-go client per consumer. Nothing connects at that point, so an unavailable Kafka or database does not block startup. The application opens its listeners, starts the relay and every consumer next to the HTTP servers, and serves. On SIGTERM the HTTP servers, the relay, and the consumers stop at the same time; none depends on another. A consumer starts no new record and abandons any backoff wait at once. An attempt in progress has `CONSUMER_SHUTDOWN_GRACE` to commit; after that it is canceled and its transaction rolls back. Finished records are committed within `CONSUMER_COMMIT_TIMEOUT`; unfinished records are never committed, so the next member of the group processes them. Bootstrap waits for all workers before the cleanup, in which the members leave their groups in parallel, each within `CONSUMER_COMMIT_TIMEOUT` plus 2 seconds (the final revocation commits only finished positions), and then the pool closes. The whole shutdown budget is in [DEPLOY.md](DEPLOY.md#event-consumers). Trade-offs: one consumer processes one record at a time on one connection. Parallel processing comes from more backend instances in the same group, up to the partition count of the topic (3 by default). Markers are kept indefinitely; their retention is planned and must outlast the replay horizon, because deleting a marker lets a replay of that event apply again. The retention task also adds the index on `processed_at` that it needs; until then every applied event would pay for an index that nothing reads. The metric `lincodex_event_consumer_records_total{consumer,outcome}` counts finished records by `applied`, `duplicate`, `ignored`, or `dead_lettered`; `lincodex_event_consumer_failures_total{consumer,stage}` counts every failed operation, including the last handler attempt before a dead letter, by `handler`, `store`, `poll` (a failed poll of the event bus), or `commit` (a failed offset commit). The consumer label comes from the registered names in code, so the series are bounded. Every series of a consumer exists from its start at zero. Logs carry the consumer, group, topic, partition, offset, event ID, and event type, never the value or payload. ### 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. No flow calls the port yet: deliveries are stored (see [Mail deliveries](#mail-deliveries)), and the worker that sends them is planned (TASK-016). Settings are described in [DEPLOY.md](DEPLOY.md#mail). `Send(ctx, OutgoingMail)` makes exactly one attempt. `OutgoingMail` carries the recipient, subject, text and HTML bodies, and an idempotency key that stays the same for one logical delivery across retries (1 to 256 printable ASCII characters, the Resend limit, without personal data); the sender comes from `EMAIL_FROM`. With a nil error the result is one of: - `accepted`: the provider accepted the request and returned `ProviderMessageID`. This is not delivery or reading. - `rejected`: the provider did not take the message. Either it answered and refused, or the transport failed before the request was completely written (DNS, connect, or TLS), so no complete request reached the provider; the second case is always `temporary`, and a retry cannot duplicate the message. `Rejection` is `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted`, or `temporary`. - `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`), for example a timeout, a connection lost after the request was written, or a provider error raised while handling it. It is not "not sent": a retry reuses the idempotency key and the same content. 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, the attempt limit, and the stop at the end of the 24-hour key window belong to the planned delivery layer; waiting for a quota reset is decided by the quota gate described in [Mail quotas](#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](#mail-quotas). Planned: the worker that claims due deliveries, passes them through the quota gate, and calls `MailSender` (TASK-016), retries and the unknown outcome policy (TASK-017), delivery metrics (TASK-022), and the permission check before a send (TASK-462). No product flow calls `MailRequester` yet, and nothing sends a stored delivery. 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/` (`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` (`.v`), `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": , "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 to be created by the identity flows directly in the transaction that issues the token, through the same `domain.NewDelivery` and `DeliveryRepository.Create`; that wiring is planned with TASK-016 and the registration and reset 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](DEPLOY.md#mail-deliveries). - Deleting an account deletes its mail requests, deliveries, and their attempts by cascade. The unverified account cleanup locks them with `FOR UPDATE SKIP LOCKED` like tokens and sessions, so it never waits for the delivery consumer or a worker that holds a row. - A retention rule that deletes or clears terminal deliveries after a bounded period is not implemented yet; until it exists, 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. There is no delivery metric yet; TASK-022 adds them with labels limited to kind, status, and provider, never the address, account ID, or 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`; not delivery to or reading by a person | 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 | | `waiting_quota` | A provider quota or the local quota is used up | Optional: the expected reset (see [Mail quotas](#mail-quotas)); none when the reset is unknown, for example after a provider quota answer that names neither a window nor a wait, and an operator decides | Transitions: - `Delivery.RecordAttempt` takes the result of one transport attempt and appends an attempt row. `pending`, `waiting_quota`, and `unknown` accept an attempt: `accepted` gives `accepted`, a `permanent` or `invalid_request` rejection gives `rejected`, `temporary` or `rate_limited` gives `pending`, `quota_exhausted` gives `waiting_quota`, and `unknown` gives `unknown`. `accepted` and `rejected` 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.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](#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. Planned additive changes for later tasks. Each is a new column, index, or CHECK value in a later migration; existing rows stay valid: - A terminal cancelled status for a delivery that must not be sent anymore: a token or account invalidated before the send (TASK-016) or a revoked permission (TASK-462). - A nullable reference from a token mail delivery to `email_tokens.id`, so the worker can check that the token is still the active one for its purpose before it sends (TASK-016). - For the sending worker (TASK-016): lease columns (for example a claim owner and `claimed_until`) and a partial index on `next_attempt_at` for the statuses that are picked up again, so several processes claim due deliveries with `FOR UPDATE SKIP LOCKED` and an attempt whose process stopped after the request becomes `unknown`. The store already provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, and `Rebind`. ### 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`). Planned: the sending worker that calls the gate around `MailSender.Send` and builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP (TASK-016), quota metrics (TASK-022), and the API or identity flow that shows the status reader's result. Nothing sends yet, so the current build counts nothing. 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](#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 `` | | `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 sent. It means that the provider accepted it, not that it reached the inbox | | `rejected` | Your email could not be sent | Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quotas). The gate logs `mail quota is used up; the delivery waits for the reset` at info level and `the mail provider reported its quota used up; local sending stops until the reset` at warn level, with only the delivery ID, provider, period, and reset time. There is no quota metric yet; `MailQuotaRepository.Usage` is the read that TASK-022 can expose with the labels provider and period. ### 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:` or `operator:`, 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](../../api/README.en.md#identity-sessions-cookie-and-csrf)). They come from the versioned product policy, not from configuration: the registration, verification, and session usecases will read them from the effective policy version. The grade rules in [Assessment and grade verification](#assessment-and-grade-verification) use the same assessment values. 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 ```text api/core/ public browser-to-Go contract and bundle api/ml/ internal Go-to-ML contract and bundle backend/cmd/app/main.go calls bootstrap.Run and reports errors backend/cmd/migrate/ local migration status, up, and down-one backend/config/ shared runtime configuration backend/internal/domain/ product invariants, planned modules backend/internal/usecase/ application operations and orchestration backend/internal/port/ inbound and outbound interfaces backend/internal/adapter/ primary HTTP and secondary integrations backend/internal/bootstrap/ dependency wiring and process lifecycle backend/db/ migrations, SQL queries, and the embedded migration set backend/codegen/ ogen server and ML-client configs, sqlc frontend/src/ app, pages, widgets, features, entities, shared frontend/codegen/ Orval configuration ml/src/ FastAPI service and operational checks ml/codegen/ Python datamodel-code-generator settings deploy/ Compose, Nginx, and technical smoke checks observability/ Prometheus, Loki, Alloy, Grafana provisioning scripts/ shared documentation and schema tooling docs/ maintained Russian and English guides ``` ```text backend/ cmd/app/main.go calls bootstrap.Run and reports errors config/ shared runtime configuration internal/ domain/ flat package; DomainEvent, identity types, 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/notification/ mail requests and the consumer that stores them as deliveries 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, policy, password hashing, and mail boundaries adapter/primary/http/ api/ generated ogen handler middleware/ request metrics 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 ml/api/ generated client from backend/codegen/ogen-ml.yml postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity 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 and request 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/retry/ backoff with jitter and a context-aware wait shared by the workers bootstrap/ configuration, wiring, lifecycle, shutdown db/ embedded migrations and SQL queries; outbox, identity, policy, and event consumer tables codegen/ ogen and sqlc configs pkg/ reserved for justified shared technical helpers ``` 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 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 no registered product handler, 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, the `MailSender` port with the `disabled` and Resend transports, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, 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. Candidate future packages are `mailer` and test helpers. 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; the identity usecases (verification and password reset) are expected to call it when they create their deliveries, and that wiring is planned. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`. `api/` contains contract sources and tools; it is not a runtime hop in the request path. `api/core/` and `api/ml/` each own OpenAPI source, route and component fragments, and a committed bundle. Root `scripts/` merges schema fragments. Generated Go output belongs to its consumer: the public handler under `backend/internal/adapter/primary/http/api/`, the internal ML client under `backend/internal/adapter/secondary/ml/api/`, and sqlc output under `backend/internal/adapter/secondary/postgres/sqlc/`. The first is transport code mounted in chi; the latter two are outbound adapters. `backend/cmd/app/main.go` remains a small process entry point; bootstrap owns dependency wiring and graceful shutdown. ## Target modules | Module | Responsibility | Main data | | --- | --- | --- | | identity | Email, verification, sessions, roles | users, email_tokens, sessions, external_identities | | candidate | Profile, contacts, consent, visibility | profiles, contacts, skills, consents, resume_versions | | company | Company and its members | companies, company_members | | 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](#product-policy-versions); its thresholds are uncalibrated and are not a validated psychometric model. Task rotation and attempt limits reduce the value of leaked answers but do not prove resistance to hints or LLMs. Difficulty comparability needs measurement. ## 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. Future jobs 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](../../api/README.en.md#identity-sessions-cookie-and-csrf) 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`. The consent tables planned in TASK-062 can reference `users.id` the same way. 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. `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, and their mail deliveries with `FOR UPDATE SKIP LOCKED` and skips every account whose row, or any token, session, mail request, or delivery 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. - `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$$` 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. ## 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); product consumers and additional topics are planned. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI. k3s is outside the critical path. Consider it only with an operated cluster or measured multi-node need. A single-node cluster does not provide HA. A transition needs probes and resource limits, secrets, storage backup, ingress, and verified NetworkPolicy. Vacancies and voluntary applications, recurring assessments, employer complaints/verification, ATS adapters, and deeper matching are future scope. Employer verification and ATS integration are not implemented or required for the first prototype. ## First product API slice | Group | Initial target | | --- | --- | | identity | register, verify/resend email, login, logout, me; password reset can wait until the final phase | | candidate | own profile, questionnaire, consent, publish and hide | | documents | resume upload, analysis request, job status, confirmation of proposed fields, PDF retrieval | | assessment | available tests, attempt start, answer save, submit, history, and eligibility | | company | company profile and current user membership | | matching | need, confirmation of extracted fields, search create/refine/read | | invitation | send, list, view, accept/decline, withdraw, and authorized contact access | | achievement | FSP link state and achievement history; fixture provider for demos | Examples of stable operations are `POST /api/v1/searches`, `POST /api/v1/searches/{id}/refinements`, `POST /api/v1/candidates/{id}/invitations`, and `POST /api/v1/invitations/{id}/accept`. These are target examples, not implemented endpoints. Every business operation, response, and error belongs in OpenAPI with a stable `operationId`. Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amounts for the MVP, and bounded cursor pagination. Distinguish null from absent fields. Errors have a stable `code`, safe message, optional field errors, and request ID. Use idempotency keys for invitation creation, analysis start, and assessment submission; scope keys by actor and operation, and reject reuse with a different body. Check access for every object ID, job, search run, and PDF. Never include contacts in common errors or public examples. The contract fixes the error model, Idempotency-Key, If-Match, pagination, and time format in [api/README.en.md](../../api/README.en.md#contract-conventions); of these, only the problem-based error mapping is implemented. ## Metrics, telemetry, and alerts The current Go service exports standard Go/process metrics, `lincodex_http_requests_total` with bounded `method`, route-template `route`, and `status` labels, and `lincodex_http_request_duration_seconds`. Do not use user, candidate, request IDs, full URLs, addresses, or resume content as labels. `/metrics` uses an internal listener outside `/api/v1`. Go runtime, PostgreSQL, Redis, SeaweedFS, and Linux dashboard JSON files are maintained project sources, not imported dashboard IDs. Queue, inference, and product-event 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. Future alerts cover unavailable targets, elevated 5xx rate with enough requests, latency budget breaches, old or terminally failed jobs, 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.