353 KiB
Lincodex architecture
This document separates the target product architecture from the technical scaffold in the repository. The requirements source is the specification. Page references in the coverage table use the printed pagination without the cover page. The brandbook is stored alongside the specification. The team supplied October 11 and October 30, 2026, as project milestones.
Current scaffold
The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface with public pages and two cabinets (working screens for the workflows described below), a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port.
Registration, email confirmation, login, and basic current-session operations work through the backend API and the frontend screens; local browser E2E covers candidate and employer accounts. The backend API and the cabinet screens also cover consents C1-C5 and the account deletion request; organizations, memberships, and employer needs; the manual candidate profile and the questionnaire with specializations and self-assessment; the public specialization catalog; assessment attempts (create, answers, finalize, result history, server signals, and skill evidence), where the task bank and the categories are demonstration data and uncalibrated; privacy settings and publication of the anonymous card; the internal notification inbox of both cabinets (see Internal notifications); and support cases. The manual assessment request is implemented as a support case of that type (usecase/supportcase, frontend/src/features/request-manual-assessment): it does not depend on consent C3, creates no attempt, changes no category, and only puts the case into the expert queue; the API has no operation for the expert side of that queue. The deterministic basic match search of the organization-visible bank works through the backend API without ML, competition data, or search snapshots (see Matching and explanations); category recommendations for a need are not computed, and the response carries an empty list (domain/need_response.go).
Invitations are implemented end to end (see Invitation drafts, Sending invitations, Candidate view and decline, Candidate acceptance, Pending limit, cooldown, and expiry, and Contact reads and revocation): an organization creates and updates a draft with versioned terms and sends it; the invitation reaches the candidate's inbox and produces an internal notification; the candidate reads it, marks it viewed, declines it, or accepts it with consent C4 for the chosen contacts; after acceptance the organization reads the shared contacts, and the candidate can revoke the contact grant. The pending limit per need, the cooldown of the organization-candidate pair after a decline, and the expiry at the response deadline apply. The frontend has the invitation composer reached from a search result, the organization's invitation list (pages/employer-invitations), and the candidate inbox. The operations for withdrawal by the organization (WithdrawOrganizationInvitation), cancellation by the candidate (CancelMyInvitation), and the salary raise (RaiseOrganizationInvitationSalary) are in the contract but not implemented, and answer 501 not_implemented.
Not implemented: counter-offers and the stages after acceptance (interviews), password reset, resume upload and analysis, PDF, search snapshots and refinement, ML inference and semantic search (the backend does not call the ML client), FSP integration (the adapter/secondary/fsp directory is empty), the SMTP transport (the backend fails to start with EMAIL_PROVIDER=smtp; only Resend sends mail), PDF generation (the adapter/secondary/pdf directory is empty), and ATS adapters. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.
See development, deployment, and testing for source layout, commands, and current check coverage.
Target system
The target is a modular Go backend with Clean Architecture, a React SPA using Vite and FSD, and a separate ML HTTP service in one repository. The planned Go process runs the HTTP API and background worker together. PostgreSQL stores product records and jobs; Redis provides the cache. Private S3-compatible SeaweedFS storage is selected for resumes and generated PDFs; the file workflows are not implemented yet. The initial target uses Docker Compose on one application host, with ML in a separate environment.
Go owns authorization, verified categories, invitations, contact grants, and final search results. ML proposes resume fields, helps interpret employer needs, and can take part in semantic search experiments. Model outages must leave manual profiles, assessments, filter-based search, and invitations available.
Combining API and worker simplifies the demo deployment, while sharing process lifecycle, memory limits, and metrics registry. The worker can move to its own process when independent scaling is needed without moving usecases or ports. That worker is planned.
The project brief assigns 35% of its score to matching, 25% to assessment and categorization, and 7% to technical implementation. The October 11 milestone calls for a working prototype flow. Technical work alone does not provide that flow.
Contracts and code generation
The contract roots are split by boundary: api/core/ contains browser-to-Go operations, and api/ml/ contains internal Go-to-ML operations. The shared Makefile, package.json, and Redocly configuration stay under api/. Python schema tools live in the repository-level scripts/ directory. Each contract is assembled from small source YAML files.
The public Go handler is generated by ogen from backend/codegen/ogen.yml and mounted in chi. Orval independently generates the TypeScript client, TanStack Query hooks, Zod schemas, and MSW handlers. The ML Go client is configured at backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. datamodel-code-generator produces Pydantic v2 models from the same ML bundle in ml/src/lincodex_ml/api/models.py; the health/readiness handlers use these models. Python generator settings live in ml/codegen/pyproject.toml, while dependencies remain in ml/pyproject.toml. Backend sqlc configuration is backend/codegen/sqlc.yml and its generated SQL adapter is under backend/internal/adapter/secondary/postgres/sqlc/. Frontend configuration is frontend/codegen/orval.config.ts. There are three codegen directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Configuration belongs to the service that uses the generated code.
OpenAPI 3.2.0 is the target version. Verify the subset used here across bundling and lint, ogen, the chi adapter, the API runtime path, Orval, Python Pydantic models, and documentation. A parser version or one fixture does not prove support for every OpenAPI 3.2.0 feature.
The public API prefix /api/v1 is applied once. The internal /metrics endpoint remains separate. Health operations use names ending in z: healthz and readyz. Generated types and request validation do not implement ownership checks, company membership, consent, or valid product state transitions.
Generate bundles from contract sources, then regenerate each Go, TypeScript, and Python consumer through its Make target. A contract change includes generation and drift checks for every consumer. Never edit generated files by hand.
Service and data boundaries
The planned backend boundaries are:
- Primary adapters receive HTTP requests and translate them into inbound ports.
- Usecases implement application flows and depend on domain rules and ports.
- Secondary adapters implement storage, ML, email, and file operations.
- Bootstrap wires implementations and controls process startup and shutdown.
- Product rules stay in domain and usecase code, away from chi handlers, workers, SQL, and ML.
Shared Go configuration belongs in backend/config/ outside internal. wahrwelt-kit logkit 0.6.0, httpkit 0.7.0, and cachekit 0.7.0 currently provide technical functions. Metrics use bounded custom collector/middleware code, and pgxpool collection must not block startup. pgkit and httpkit/metrics are not currently used. Technical libraries do not own product rules. Do not add unselected JWT or WebSocket dependencies for hypothetical features.
PostgreSQL with pgx, sqlc, and goose is the database stack. Developers own SQL; sqlc generates typed adapters. goose manages versioned migrations: the SQL files are embedded in the binary, and the backend applies them at startup under a PostgreSQL advisory lock before it opens its listeners. wire provides compile-time dependency construction in bootstrap, with no runtime DI container. API and worker share the database pool in the planned single-process deployment.
Redis is part of the core Compose project and connects through backend/internal/adapter/secondary/redis/ to the outbound cache port. The adapter provides Get/Set/Del with TTL; bootstrap manages client construction and cleanup. The internal /readyz requires PostgreSQL, Redis, and the SeaweedFS bucket to be available. The cache is not a source of truth: future consumers must tolerate key eviction and Redis restarts. Profile, search, resume, and other product caching rules are not implemented yet.
SeaweedFS runs as a separate server in the core Compose project. backend/internal/adapter/secondary/seaweedfs/ implements the outbound ObjectStorage port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. The shared file layer and the access controls of the SeaweedFS container are described in Private file storage. Resume uploads, authorization, product content rules, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup.
The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the outbox_events table has its transactional writer, and the outbox relay publishes committed events to Kafka. The event consumer runtime applies events idempotently; two product consumers are registered, notification_delivery for mail deliveries and notification_inbox for the internal notifications. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help.
HTTP perimeter and client address
Implemented. The frontend Nginx is the only public HTTP entry. It serves the SPA, proxies /api/v1/ to Go, and proxies the restricted /telemetry; every other path, including /metrics, /readyz, and administration paths of other services, is refused with 404. Security headers, a strict same-origin CSP, a 1 MB default body limit that answers 413 in the contract's problem format, and coarse per-client limit_req/limit_conn (429 with Retry-After) are set there; the limits are far above normal use and do not replace the domain quotas, which stay in the backend. The details and the checks are in DEPLOY.md.
The client address is derived only through trusted proxies. The edge replaces X-Forwarded-For; the app Nginx trusts the edge tunnel address and passes the backend one resolved entry; middleware.ClientIP (backend/internal/adapter/primary/http/middleware/clientip.go) trusts X-Forwarded-For only from TRUSTED_PROXY_CIDRS (by default only the pinned frontend container address) and reads it from the right, so an entry a client puts to the left of the first untrusted hop never counts. Usecases and handlers that need the address for a limiter read it with middleware.ClientAddr(ctx) and key the limiter with middleware.LimiterKey (IPv6 reduced to /64). The address is never logged or stored beyond the limiter window; the request log and metrics have no field for it. Registration, resend, and confirmation use client-address limits (see Registration, email verification, and resend); the router mounts ClientIP.
Private file storage
backend/internal/usecase/files/ is the shared private file layer over the ObjectStorage port. It holds technical rules only. A feature package (resume upload, import, PDF generation, document jobs, exports) defines a Policy with a namespace, a size limit in bytes, and exact media types, and owns every product rule: who may read or delete a file, page counts, content inspection, parsing, and retention. The layer is not wired into bootstrap until the first such feature uses it. Namespaces are declared in one place, namespace.go, and NewPolicy accepts no other value, so two features cannot share a namespace by accident.
- Keys have the form
<namespace>/<32 hex characters>from 128 random bits. Only the validated policy namespace comes from code; file names and other client input never become part of a key.OpenandDeleteaccept only keys of their policy's namespace and format, so a client-shaped key, a traversal path, or another feature's key is rejected before storage is called. - Writes take the exact size. A declared size above the policy limit is rejected before any request. The stream passes through an
io.LimitReaderguard that withholds the last chunk until the source has ended, so a longer or shorter source aborts the request before storage receives a complete body. Any failure after the write started deletes the key, also after caller cancellation. Sources of unknown length are not buffered; a feature that needs them must spool to a bounded temporary file or add multipart upload. The source needs its own deadline, such ashttp.ResponseController.SetReadDeadlineon a request body:Putwaits for a blocked read, and canceling the context does not interrupt it. Putreturns aRecord: the key, the bare media type, the size, the SHA-256 digest computed while streaming, and the sanitized original name. The layer keeps no index and adds no tables. Callers follow one order:Put, then persist the record with their ownership data in a database transaction, thenDeletethe key if that transaction fails. One race remains: when the whole body was sent before the caller canceled, the server may commit after the cleanupDeletereturned. Such orphans have no record and no request reaches them; a namespace sweeper that removes keys without a record is planned together with backups and exports and does not exist yet. The original name is display metadata only: it is not stored in SeaweedFS and is never used in keys or logs, but it may still contain personal data. Sanitizing removes path elements, control, format, separator, and private-use characters and does not normalize Unicode. The content type is declared by the caller; detection by content belongs to the document parser.Openchecks that the stored object still fits the policy and closes the response on every rejection. The caller closes the returnedFile; reading fails when the body differs from the stored size. The adapter'sSEAWEEDFS_TIMEOUTbounds connection setup, the TLS handshake, and the wait for response headers, not the body transfer ofPutandGet, so the caller's context is the only bound on a long or slow stream.Deleteis idempotent, and absence maps tofiles.ErrNotFound.- There are no public URLs. The layer creates no public, permanent, or presigned URLs, and the bucket has no public policy or anonymous ACL. A browser download must go through an authenticated backend endpoint that checks current access and streams
FilewithContent-Disposition: attachmentandX-Content-Type-Options: nosniff, so a stored file is never rendered as a page of the application origin. The key, bucket, and storage URL never reach clients.
SeaweedFS access. The primary control is the network: SeaweedFS joins only the internal storage Compose network, which the backend and the monitoring Prometheus (for the metrics on port 9327) also join. The frontend, PostgreSQL, Redis, Kafka, and other containers cannot resolve or reach it. This matters because mini serves much more than S3. The S3 gateway requires SigV4 credentials: the container's AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY create its only identity, -s3.iam=false removes only the IAM management API, and Compose refuses empty credentials because SeaweedFS without any identity accepts anonymous S3 requests. The other listeners do not use S3 credentials: the filer (8888), master (9333), and volume (9340) HTTP APIs; unauthenticated gRPC on 18888, 19333, 19340, and 18333 with server reflection; and an admin server on 23646 with worker gRPC on 33646 that -admin.ui=false does not stop and that mini cannot disable. Defense in depth inside the storage network: each start sets fresh random JWT signing keys for the filer and volume HTTP APIs, and -ip=127.0.0.1 with -whiteList=127.0.0.1,@ limits master and volume HTTP to callers inside the container. The upstream filer ignores its IP whitelist, so the JWT is its only HTTP control.
Remaining risk, limited to members of the storage network, which today means the backend (and Prometheus): they can reach the unauthenticated gRPC ports 19333, 18888, and 18333 and the admin ports 23646 and 33646. Master gRPC Assign returns a file ID with a signed volume write token, filer gRPC ListEntries returns object metadata, and entry changes through filer gRPC should be treated as possible. Volume gRPC 19340 refuses such callers. Integration tests verify that a volume write with a token from Assign is refused from outside the container (HTTP 401, whitelist) and that a volume read without a token is refused; this was not verified for the admin and worker ports. Low-priority disclosure inside the same network: the master UI and /cluster/status and the volume /status reveal topology and disk usage. A compromised backend already holds the S3 credentials, so these paths add little for it; any new member of the storage network widens the risk. gRPC mutual TLS would close the gRPC paths and is not configured.
Transactional outbox
Implemented: migration backend/db/migrations/00001_create_outbox_events.sql creates outbox_events. Columns:
position: a bigint identity, unique and monotonic in insertion order; the relay scans by it.event_id: uuid primary key, a UUIDv7 generated in Go.event_type: a lowercase dotted name of at most 128 bytes.schema_version: an integer above zero.aggregate_type: snake_case, at most 64 bytes.aggregate_id: a uuid.aggregate_version: a bigint above zero.payload: a jsonb object.occurred_at:clock_timestamp()at insert. It is informational only and does not define order.published_at: null until the relay publishes the row.
A unique key on aggregate type, aggregate ID, aggregate version, and event type rejects a second event of the same type for the same aggregate version. A partial index on position where published_at is null serves the relay scan. CHECK constraints repeat the domain rules for versions, names, and the object payload as a backstop. The payload size limit lives only in Go, because the jsonb text and binary sizes differ from the compact input and a database length check could reject an event the domain accepted.
A usecase writes through outbound ports. Transactor.WithinTransaction(ctx, fn) opens one READ COMMITTED transaction and passes a UnitOfWork; every repository it returns, including Outbox().Append(ctx, events...), uses that transaction. The transaction commits when fn returns nil and rolls back when fn returns an error, panics, or its context is canceled. Calling WithinTransaction again with the callback context returns outbound.ErrNestedTransaction instead of opening a second connection. A conflict on the event ID or the unique key returns an error that wraps outbound.ErrOutboxEventConflict and names the constraint. A network error during commit leaves the outcome unknown, so callers that retry must be idempotent.
The outbox uniqueness rule is a backstop, not concurrency control. Aggregate updates still check the expected version (UPDATE ... WHERE version = $n), so a stale writer fails before it records an event.
domain.NewDomainEvent validates the event. The compact JSON payload is limited to 16 KiB and 32 nesting levels; numbers must fit a float64; NUL characters are rejected because jsonb cannot store them. jsonb normalizes the stored payload (key order, whitespace, duplicate keys), so consumers compare JSON values rather than bytes. Payloads carry identifiers and minimal facts only, never contact data, tokens, passwords, or resume and document contents.
The relay that publishes these rows is described in Outbox relay. Idempotent consumers are described in Event consumers. Still planned: retry bookkeeping columns (attempt count and last error) and retention of published rows. Bootstrap does not wire the transactor yet because no product usecase uses it; the first business transaction wires it together with a shared pool.
Outbox relay
Implemented: the relay loop in backend/internal/worker/outboxrelay/, the outbound.OutboxRelayStore and outbound.EventPublisher ports (backend/internal/port/outbound/outbox_relay.go), the PostgreSQL store (adapter/secondary/postgres/outbox_relay.go), and the franz-go producer (adapter/secondary/kafka/). Bootstrap starts the relay together with the HTTP servers in the same process and stops it on shutdown. The relay has its own PostgreSQL pool of at most two connections, one for the claim transaction and one for the backlog read, so it never takes connections from request handling. It does not run when RELAY_ENABLED=false or DATABASE_URL is unset; the outbox then keeps the events. Settings are listed in DEPLOY.md.
One pass is one READ COMMITTED transaction:
SetRelayTransactionTimeoutssetsstatement_timeouttoRELAY_STATEMENT_TIMEOUTandidle_in_transaction_session_timeouttoRELAY_PRODUCE_TIMEOUT + RELAY_STATEMENT_TIMEOUTfor this transaction only (SET LOCALthroughset_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.LockPendingOutboxEventsselects rows withpublished_at IS NULLinpositionorder, at mostRELAY_BATCH_SIZE, withFOR UPDATE OF pending SKIP LOCKED. A row qualifies only when it is the earliest unpublished event of its aggregate (lowestaggregate_version, thenposition). There is nopositionoroccurred_atwatermark; every pass scans the unpublished rows again.- The relay publishes the batch and waits for the broker acknowledgements, at most
RELAY_PRODUCE_TIMEOUT. MarkOutboxEventsPublishedsetspublished_atfor 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.eventsby default. All events go to one topic; consumers filter byevent_type. One topic is enough while consumers are few, and per-aggregate order needs only the key. - Key:
<aggregate_type>:<aggregate_id>. The default franz-go partitioner hashes the key, so all events of an aggregate land in one partition in publication order. - Value: a compact JSON envelope with
envelope_version(currently 1; changes only with the envelope fields),event_id,event_type,schema_version(the payload layout version of that event type),aggregate_type,aggregate_id,aggregate_version,occurred_at(RFC 3339 in UTC, informational), andpayload(the stored jsonb object, so key order can differ from what the writer appended). - Headers:
event_id,event_type,schema_version, so a consumer can deduplicate and route without decoding the value.
The producer uses acks from all in-sync replicas and idempotent writes (the franz-go default). By default franz-go cannot fail an in-flight idempotent record until the broker answers, so behind a frozen broker the record and every later record of its partition would wait indefinitely. The relay enables AllowIdempotentProduceCancellation, which lets the delivery timeout and the pass deadline fail such a record, and Publish stops waiting at the deadline in any case. The client retries a record at most five times within one publish; later attempts belong to the next pass. Kafka does not create topics on demand: before its first pass the relay calls Prepare, which creates KAFKA_EVENTS_TOPIC through kadm with KAFKA_EVENTS_TOPIC_PARTITIONS, KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR (-1 by default, the broker's default.replication.factor), and, when set, min.insync.replicas from KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS (otherwise the broker default). It accepts an existing topic without changing it and logs one warning when that topic has another partition count or, with an explicit replication factor, another replication factor. A failed Prepare does not block startup: the relay retries it with backoff and events stay pending. When a publish reports an unknown topic, for example after the topic was deleted, the relay calls Prepare again before its next pass. With acks from all in-sync replicas, a write is durable only on min.insync.replicas brokers; the production requirement is in DEPLOY.md. With KAFKA_PROVISION_TOPICS=false the topic is managed outside the backend. Adding partitions later moves keys to other partitions, so per-aggregate order is not guaranteed across that change.
Failure semantics:
- Kafka unavailable: the publish fails within
RELAY_PRODUCE_TIMEOUT, nothing is marked, and the rows stay pending. The relay logs a warning with counts and the error (event IDs and broker errors, never payloads), waits a backoff, and retries indefinitely. The backoff starts atRELAY_BACKOFF_INITIAL, doubles with every consecutive failure up toRELAY_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 byevent_idand ignore anaggregate_versionthey 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_TIMEOUTto 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_SIZEoutbox rows and one connection for at mostRELAY_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 positionreturns the oldest heads first, every pass claims the poison heads again; whenRELAY_BATCH_SIZEor more aggregate heads are poison, they fill the whole batch, no pass publishes anything, and the relay stalls at one pass perRELAY_BACKOFF_MAXwhile the backlog grows. An operator seesfailedinlincodex_outbox_relay_events_totalrising whilepublishedstays flat,lincodex_outbox_relay_oldest_pending_age_secondsgrowing, and warnings with the event IDs of the batch. The usual causes are on the Kafka side (the topic, its ACLs, ormin.insync.replicasabove the live replicas); after that is fixed, the next pass publishes everything. A raisedRELAY_BATCH_SIZElets other aggregates through meanwhile. There is no dead-letter path: an event that can never be published needs a decision by the owners of its consumers, and marking it published by hand skips it for every consumer.
The metric lincodex_outbox_relay_events_total{outcome} counts published and failed events; a pending event is counted as failed on every attempt. The gauges lincodex_outbox_relay_pending_events and lincodex_outbox_relay_oldest_pending_age_seconds show the unpublished events and the age of the earliest one by position, measured by the database clock. The relay reads them with GetOutboxBacklog, which uses the partial index, at most once every 15 seconds, also while it retries Prepare, so a busy relay does not count the outbox on every pass. Every backend instance reports the same database-wide values; aggregate them with max. /readyz does not check Kafka, so a Kafka outage does not take the API out of service.
Event consumers
Implemented: the consumer runtime in backend/internal/worker/eventconsumer/, the handler port inbound.EventHandler (backend/internal/port/inbound/event_handler.go), the outbound.EventSource and outbound.EventConsumerStore ports (backend/internal/port/outbound/event_consumer.go), the franz-go consumer group member (adapter/secondary/kafka/consumer.go), the PostgreSQL store (adapter/secondary/postgres/event_consumer.go), and migration 00005_create_event_consumer_tables.sql with the consumer_processed_events and consumer_dead_letters tables. Two product handlers are registered: eventHandlers() in backend/internal/bootstrap/consumers.go returns the mail delivery handler notification_delivery described in Mail deliveries and the inbox handler notification_inbox described in Internal notifications, so a backend with CONSUMER_ENABLED and DATABASE_URL runs one consumer in each of the groups <CONSUMER_GROUP_PREFIX>.notification_delivery and <CONSUMER_GROUP_PREFIX>.notification_inbox. The runtime integration tests use a test-only handler that writes into a table the test creates. A product module adds its handler to that list. Settings are listed in DEPLOY.md.
A handler implements three methods:
ConsumerName(): a snake_case name of at most 64 characters. It names the Kafka consumer group<CONSUMER_GROUP_PREFIX>.<name>and scopes deduplication, so renaming a consumer makes it process every retained event again.Handles(eventType): events of other types are counted asignoredand committed without a transaction.Handle(ctx, unit, event): receives the decoded envelope and anoutbound.UnitOfWorkbound to the transaction that holds the dedup marker. The effect must use only that unit. An error that wrapsinbound.ErrEventRejectedis 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:
- The Kafka adapter decodes the envelope. It requires
envelope_version1, a non-nilevent_id, the domain rules ofdomain.NewDomainEventfor type, schema version, aggregate type, ID, and version, a non-zerooccurred_at, a JSON objectpayload, and anevent_idheader, 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. - One READ COMMITTED transaction sets
statement_timeoutandidle_in_transaction_session_timeouttoCONSUMER_HANDLER_TIMEOUTfor this transaction only, runsINSERT 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 aduplicate. One row means the handler runs in the same transaction, and the effect commits together with the marker. - 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_ATTEMPTSattempts with the same backoff as the relay: the wait starts atCONSUMER_BACKOFF_INITIAL, doubles up toCONSUMER_BACKOFF_MAX, and is half the current value plus a random share of the other half. Each attempt is bounded byCONSUMER_HANDLER_TIMEOUTand rolls back its effect and marker. When the attempts run out, the record becomes a dead letter of classretries_exhausted.inbound.ErrEventRejectedgiveshandler_rejectedafter one attempt. A handler panic is recovered, the transaction rolls back, the stack is logged without the panic value, and the record becomeshandler_panic, so one event cannot crash the process on every delivery. - Invalid record: a dead letter of class
invalid_recordwith 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) matchoutbound.ErrEventEffectRejected; class 40 (serialization failure or deadlock) matchesoutbound.ErrTransactionConflict. Both count as a handler attempt and are retried with backoff, so a deterministic refusal ends inretries_exhaustedinstead 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 inHandles, which giveshandler_panicwithout an attempt. - Store failure (begin, marker, a commit lost in transport, or the dead letter write): it does not use up the handler's attempts, because the event is not at fault. The consumer retries with the same backoff until the database answers or shutdown begins, and never dead-letters a record because the database was down. The offset stays uncommitted meanwhile, so a database outage stops the partition without a hot loop and loses nothing.
- After the dead letter row exists, the offset is committed and the partition continues with the next record. A dead letter writes no marker, so a later replay of the event is applied.
consumer_dead_letters stores the consumer name, topic, partition, offset, event_id (from the envelope, or from the event_id header of an invalid record; NULL when neither is a UUID), event_type (NULL for an invalid record), the class, a reason of at most 256 printable characters, the attempt count, the value size, its SHA-256, and the time. A unique key on consumer, topic, partition, offset, and value digest keeps one row per record: when the same record fails again, after a crash before its offset commit or a rewind of the group, the row gets the new class, reason, attempt count, and time. The digest is part of the key because a topic that was deleted and created again reuses offsets; a different value at a reused position is another record and keeps its own row instead of being dropped. Handler errors reach the reason and the logs only after the store replaced the text of any PostgreSQL error in them with its SQLSTATE and constraint, because a PostgreSQL message can quote row values. The record value itself is not stored. A valid event is still in outbox_events under its event_id, which is also the replay source, so a second copy would only duplicate data that events may carry later and that a dead letter table would keep without a retention rule. An invalid record did not come from the relay; while the topic retains it, an operator can read it by topic, partition, and offset, and the SHA-256 confirms it is the same value. The replay procedure is in DEPLOY.md.
Lifecycle. Startup runs the migrations, then wire builds the consumers: one PostgreSQL pool shared by all of them with one connection per consumer (a consumer holds one transaction at a time and writes a dead letter only after it ended) and one franz-go client per consumer. Nothing connects at that point, so an unavailable Kafka or database does not block startup. The application opens its listeners, starts the relay and every consumer next to the HTTP servers, and serves. On SIGTERM the HTTP servers, the relay, and the consumers stop at the same time; none depends on another. A consumer starts no new record and abandons any backoff wait at once. An attempt in progress has CONSUMER_SHUTDOWN_GRACE to commit; after that it is canceled and its transaction rolls back. Finished records are committed within CONSUMER_COMMIT_TIMEOUT; unfinished records are never committed, so the next member of the group processes them. Bootstrap waits for all workers before the cleanup, in which the members leave their groups in parallel, each within CONSUMER_COMMIT_TIMEOUT plus 2 seconds (the final revocation commits only finished positions), and then the pool closes. The whole shutdown budget is in DEPLOY.md.
Trade-offs: one consumer processes one record at a time on one connection. Parallel processing comes from more backend instances in the same group, up to the partition count of the topic (3 by default). Markers are kept indefinitely; their retention is planned and must outlast the replay horizon, because deleting a marker lets a replay of that event apply again. The retention task also adds the index on processed_at that it needs; until then every applied event would pay for an index that nothing reads.
The metric lincodex_event_consumer_records_total{consumer,outcome} counts finished records by applied, duplicate, ignored, or dead_lettered; lincodex_event_consumer_failures_total{consumer,stage} counts every failed operation, including the last handler attempt before a dead letter, by handler, store, poll (a failed poll of the event bus), or commit (a failed offset commit). The consumer label comes from the registered names in code, so the series are bounded. Every series of a consumer exists from its start at zero. Logs carry the consumer, group, topic, partition, offset, event ID, and event type, never the value or payload.
Scheduled jobs
Implemented: durable jobs that run once when they fall due, such as a response deadline. The runtime is in backend/internal/worker/jobrunner/, the handler port inbound.JobHandler in backend/internal/port/inbound/job_handler.go, the outbound.JobScheduler and outbound.JobStore ports in backend/internal/port/outbound/scheduled_job.go, the validated domain.ScheduledJob in backend/internal/domain/scheduled_job.go, the PostgreSQL store and scheduler in adapter/secondary/postgres/scheduled_job.go, and migration 00008_create_scheduled_jobs.sql with the scheduled_jobs table. Two product handlers are registered in jobHandlers() (backend/internal/bootstrap/jobs.go): assessment.signal_review, which computes the assessment review band, and invitation.response_deadline, which moves an invitation to expired when its response deadline passes (Pending limit, cooldown, and expiry). The tests also use a test-only kind. Settings are in DEPLOY.md.
Scheduling. A usecase calls unit.ScheduledJobs().Schedule(ctx, job) in its business transaction, so the job exists exactly when the change that needs it committed, and Cancel(ctx, kind, key) stops a job that has not finished. A job has a kind (the handler name, a lowercase dotted name), a key that identifies the logical job within its kind (for example an aggregate ID), a due time from the application clock, an optional attempt limit, and a payload: a flat JSON object of identifiers of at most 2 KiB. Neither the key nor the payload may contain personal data; the handler reads everything else from the source tables when it runs. (kind, key) is unique and the first schedule wins: a repeat inserts nothing (INSERT ... ON CONFLICT DO NOTHING) and reports false, also after the job ran or was canceled. This is insert-or-ignore rather than an upsert on purpose: a repeated command cannot move a deadline that must not be reset, and a stale writer cannot revive a finished job. A new occurrence needs a new key, for example <id>:<version>.
States. due_at is the deadline the job stands for and never changes; available_at is when a worker may claim the job next, due_at at first and the retry time after a failed attempt. pending waits for available_at; failed waits for its retry after a failed attempt; running is claimed under a lease; done, dead, and cancelled are final. Finished rows are kept, so their key stays reserved; their retention is not implemented yet.
Claim and lease. The worker claims up to JOBS_BATCH_SIZE jobs in one statement: a CTE selects waiting jobs whose available_at passed and running jobs whose lease_expires_at passed, of the kinds that have a handler in this process, in available_at order, with FOR UPDATE SKIP LOCKED, and the same statement sets status = running, lease_owner (a random ID per worker instance), and lease_expires_at = now + JOBS_LEASE_DURATION, and counts the attempt. Two partial indexes serve the claim, one on waiting rows and one on running rows; the kind filter applies after the index, so when many waiting jobs belong to kinds that the claiming process has no handler for, an index on (kind, available_at, id) is the next step. now is passed from the injected application clock; the database clock never decides whether a job is due or a lease expired, so tests move a fake clock instead of waiting days. Jobs of a kind without a handler stay untouched, so an older instance during a rolling deployment leaves them to the instances that have the handler. Right before its handler transaction, each job is started: a separately committed, guarded UPDATE renews its lease from now and sets started_at, but only while the lease of the claim has not expired. The attempt is counted at the claim, so a job that crashes its process while its handler runs cannot loop forever: when the lease of a started attempt expires on the last allowed attempt, the claim marks the job dead with lease_expired instead of running it again. A claim whose attempt never started (the worker stopped or was busy before the job's turn) is not the job's fault: the next claim reuses that attempt without counting another one and records no error class.
Run and completion. Each job runs in its own READ COMMITTED transaction: it sets statement_timeout and idle_in_transaction_session_timeout to the lease duration, locks the job row with a guard on status = running, the lease owner, and the attempt number, calls the handler with an outbound.UnitOfWork of the same transaction, marks the job done with the same guard, and commits. The handler effect and the completion therefore commit together: for an effect that stays in PostgreSQL a job is applied exactly once even when workers race, restart, or a lease expires. While the handler runs the row is locked, so another worker's claim skips it even after the lease expired by the clock; when the guard fails because the job was canceled or reclaimed, the handler is not called and nothing commits (lease_lost). A handler may cancel its own job through the unit, for example an expiry that also cancels the deadline job it stands for: the completion then finds the job cancelled in its own transaction, treats it as finished, and commits the effect, and the job stays cancelled. Any other change of its own job by the handler rolls back and makes the job dead with completion_conflict, because it would repeat on every attempt. A handler whose effect leaves the database, such as a call to another service, can repeat after a crash between that call and the commit and must be idempotent itself. The handler context ends with the renewed lease. A handler decides by job.DueAt, the deadline the job stands for, which a retry keeps, not by when it happens to run.
Lock order. The handler holds the job row lock and may then lock product rows. A business transaction that cancels a job should call Cancel before it locks those product rows. A candidate's answer does not cancel the response deadline job: the run finds the answered invitation and changes nothing (Pending limit, cooldown, and expiry). Cancel waits for a handler transaction in progress: after its commit the job is done and Cancel reports false, so the caller sees the finished job; otherwise the job is canceled and the worker finds its lease gone. The opposite order can deadlock, which PostgreSQL resolves by aborting one side with ErrTransactionConflict; the job side counts a failed attempt and retries.
Failures. A failed attempt rolls back its effect; a second statement, guarded the same way, records it. A handler error, a lease timeout, a deadlock or serialization failure (conflict), or a commit that PostgreSQL refuses (effect_rejected, for a handler that ignored a failed statement or a deferred constraint) moves the job to failed with available_at = now + backoff, where the backoff is the shared worker/retry delay from JOBS_BACKOFF_INITIAL, doubling up to JOBS_BACKOFF_MAX, with jitter. inbound.ErrJobRejected, a handler panic, and completion_conflict are final, also when they happen during shutdown. After the last allowed attempt (the job's own limit or JOBS_MAX_ATTEMPTS) the job is dead: it is logged at error level and counted as dead, and it needs an operator. last_error_class stores only a bounded class; a sanitized reason appears only in the log. A database failure outside the handler is not the job's fault: the worker releases its unfinished jobs without counting the attempt and backs off before the next claim, so an outage causes no hot loop. When the failure record itself cannot be written, the job keeps its started lease; a later claim then counts it as lease_expired, which on the last attempt makes it dead.
Shutdown. When the context ends, the worker claims nothing more. A job in progress has JOBS_SHUTDOWN_GRACE to commit; after that it is canceled and its transaction rolls back, so an unfinished job is never marked done. The worker then releases it, and the claimed jobs of the batch it did not start, explicitly: back to pending or failed, without counting the attempt, guarded by owner and attempt so a job that another worker reclaimed or a caller canceled meanwhile is left alone. Release makes the jobs claimable at once by another instance instead of after up to one lease, which matters during a rolling deployment; if the release cannot reach the database, the lease expires and a later claim takes the jobs, so the release is only a shortcut and never needed for correctness. Bootstrap starts the worker next to the HTTP servers, the relay, and the consumers, and runs the cleanup that closes its pool only after it stopped.
Trade-offs: one worker runs one job at a time on a pool of two connections; more throughput comes from more backend instances. The jobs of one batch are claimed together but each renews its lease when it starts, so a slow job ahead costs the next ones only waiting time: a job whose claim lease expired before its turn is not started and is released with its attempt intact, or, when another worker already took it over, that worker runs it on the same attempt. Due times are honored with a delay of up to JOBS_POLL_INTERVAL plus the batch ahead of it. There is no separate cmd/worker: the worker is a goroutine of the backend process, and migrations run as before.
Metrics: lincodex_scheduled_jobs_total{kind,outcome} counts claimed jobs by done, retry, dead, lease_lost, or released; the kind label comes from the registered handlers, and every series exists at zero from the start. lincodex_scheduled_jobs_due, lincodex_scheduled_jobs_oldest_due_age_seconds, and lincodex_scheduled_jobs_dead describe all kinds at the last backlog read, at most every 15 seconds. Logs carry the job ID, kind, attempt, and error class, never the key or payload.
Mail transport
Implemented: the outbound MailSender port (backend/internal/port/outbound/mail.go), the disabled transport (adapter/secondary/mail/disabled/), the Resend transport (adapter/secondary/mail/resend/, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; EMAIL_PROVIDER selects exactly one transport (resend, smtp, or disabled), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (mail/smtp/, outside the MVP); until it exists, smtp fails startup after its settings are validated. The callers are the sending workers: the service worker for identity mail (see Sending service mail) and the notification worker (see Sending product notifications). Settings are described in DEPLOY.md.
Send(ctx, OutgoingMail) makes exactly one attempt. OutgoingMail carries the recipient, subject, text and HTML bodies, and an idempotency key that stays the same for one logical delivery across retries (1 to 256 printable ASCII characters, the Resend limit, without personal data); the sender comes from EMAIL_FROM. With a nil error the result is one of:
accepted: the provider accepted the request and returnedProviderMessageID. 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 alwaystemporary, and a retry cannot duplicate the message.Rejectionispermanent,invalid_request,rate_limited,quota_exhausted, ortemporary.unknown: the request may have reached the provider but no conclusive answer came back (delivery_uncertain), for example a timeout, a connection lost after the request was written, or a provider error raised while handling it. It is not "not sent": a retry reuses the idempotency key and the same content. Resend keeps an idempotency key for 24 hours. The worker stops automatic retries at 23 hours, leaving a one-hour safety margin; after that an operator must decide whether to retry because the old key may no longer prevent a duplicate.
rejected and unknown may carry RetryAfter, the provider's wait hint or a wait the transport derived from documented provider rules, and ProviderCode, the provider's error name. A quota_exhausted rejection also names the exhausted window in QuotaPeriod (day or month) when the provider said which; it is empty otherwise. A transport sets ProviderCode only from its fixed list of documented names and leaves it empty otherwise, so it never carries provider text and is safe to log and store.
A non-nil error means the message certainly did not leave the process: ErrMailChannelUnavailable in disabled mode, ErrInvalidOutgoingMail for an invalid message, or the context error when the caller's context ended before the request was written. A failure before the request was written while the context is still active is rejected/temporary, not an error. The transport makes one request; the worker owns retries, backoff, and outcome storage. The verification flows must treat ErrMailChannelUnavailable as not sent: it never confirms an address or replaces an account check. OutgoingMail redacts itself in fmt and slog output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses.
The Resend transport uses net/http without an SDK. One Send is one POST https://api.resend.com/emails with from (EMAIL_FROM), to (one recipient), subject, text, and html (a blank part is omitted), an Authorization: Bearer key, a User-Agent, and Idempotency-Key set to the message's key. Resend keeps a key for 24 hours and answers the same key and body with the original result without sending again, so a retry must repeat the stored body under the same key; a changed body under an old key is a conflict, not a reason to make a new key. EMAIL_TIMEOUT bounds the whole attempt. The client follows no redirects, uses HTTP/1.1, and opens a fresh connection for every send: a kept-alive connection that the server closed while idle would fail after the request was handed to it and turn a message Resend never saw into a false unknown. The request also has no GetBody, because net/http treats a POST with Idempotency-Key as replayable on a broken reused connection. The adapter has no retry loop and does not log. An answer is read up to 64 KiB; only the message ID and the error name are parsed, and the provider's message and body are not kept.
| Resend answer | Result |
|---|---|
2xx with an id of up to 128 letters, digits, -, or _ |
accepted with ProviderMessageID |
2xx without a valid id, truncated, or over 64 KiB |
unknown: the request may have been accepted |
| 3xx, not followed | rejected, invalid_request: the API documents no redirect, and a repeat gets the same one |
403 validation_error (unverified sender domain: without one Resend sends only testing emails to the account's own address) |
rejected, permanent |
| Other 4xx: 400, 422, key and permission errors (401, 403), 404, 405 | rejected, invalid_request |
408; 409 resource_locked |
rejected, temporary, RetryAfter from Retry-After |
409 concurrent_idempotent_requests |
unknown: another request with the same key is in progress and may be accepted; retry later with the same key |
409 invalid_idempotent_request |
unknown: the key was used with another body, so an earlier request may have been accepted; repeating cannot succeed, so the delivery layer stops and escalates |
| 409 without a known name | unknown |
429 rate_limit_exceeded or unnamed |
rejected, rate_limited, RetryAfter from Retry-After (seconds or a future HTTP date), otherwise from ratelimit-reset |
429 daily_quota_exceeded |
rejected, quota_exhausted, QuotaPeriod day, RetryAfter until the next 00:00 UTC |
429 monthly_quota_exceeded |
rejected, quota_exhausted, QuotaPeriod month, no RetryAfter: the reset follows the billing cycle |
503 service_unavailable |
rejected, temporary, RetryAfter from Retry-After |
Other 5xx, including 500 application_error and internal_server_error, a truncated body, or a proxy or gateway answer |
unknown: the API may have accepted the message before it failed |
| No answer after the request was written: timeout, reset, or closed connection | unknown |
| Failure before the request was written: DNS, connect, TLS, or the attempt timeout | rejected, temporary: no complete request reached Resend |
| The caller's context ended before the request was written | the context error; nothing was sent |
Every rejected or unknown answer with a known error name sets ProviderCode to that name, for example invalid_idempotent_request, invalid_api_key, or daily_quota_exceeded. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (invalid_api_key, invalid_from_address, invalid_access, invalid_region, security_error, internal_server_error); any other name counts as no name. RetryAfter is capped at 24 hours. Rate-limit pacing and the attempt limit belong to the retry policy, the sending worker applies the minimum schedule described in Sending service mail, and automatic retries of uncertain sends stop at 23 hours, one hour before Resend's 24-hour key window ends. Waiting for a quota reset is decided by the quota gate described in Mail quotas.
Mail deliveries
Implemented: the domain.Delivery aggregate, domain.MailContent, and domain.MailRequest (backend/internal/domain/delivery.go, mail_content.go, mail_request.go), the outbound.DeliveryRepository and outbound.MailRequestRepository ports (port/outbound/delivery.go) through UnitOfWork.Deliveries(), UnitOfWork.MailRequests(), and postgres.DeliveryStore, migration 00006_create_deliveries.sql with the mail_requests, deliveries, and delivery_attempts tables, the queries in backend/db/queries/delivery.sql, and in backend/internal/usecase/notification/ the request usecase MailRequester and the consumer DeliveryHandler. The quota gate that admits or defers a send is implemented; see Mail quotas. Implemented: the service-mail worker, bounded retries, the unknown-outcome cutoff, and the audited local operator command, with migrations 00012_add_delivery_sending.sql and 00017_retry_unknown_mail.sql; see Sending service mail. Sending product notifications, with the rights check before each send, is implemented; see Sending product notifications. The delivery state gauges are implemented; see Metrics, telemetry, and alerts. The invitation send is the first product caller of MailRequester. Registration and resend create verification mail through ServiceMailer; password reset is not implemented.
A delivery is the durable state of sending one message to one recipient. A deliveries row holds:
id: the stable ID of the logical request, so a repeated request maps to the same row. The idempotency key sent to the provider with every attempt isdelivery/<id>(idempotency_key, unique); it contains no personal data.source_event_id: the domain event the delivery was created from, or NULL for a delivery created directly in a business transaction.- The recipient:
recipient_user_id, a foreign key touserswithON DELETE CASCADE, andrecipient_email, the delivery form of the account address when the delivery was created. - The content:
kind(verification,password_reset, ornotification),template_version(<kind>.v<N>),subject,text_body,html_body, andcontent_sha256over the version, subject, and both parts, the same digest as the mail templates (domain.MailContentHash). - The provider account:
providerandprovider_account, the values ofEMAIL_PROVIDERandEMAIL_ACCOUNTat creation. They are configuration identity, never a credential. - The attempt state:
status,attempt_count,next_attempt_at,last_attempt_at,provider_message_id, the optimisticversion,created_at, andupdated_at, all from the application clock.
Creation path:
- 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 amail_requestsrow with that ID, the recipient, the kind, the raw subject, body, and link path, the subject the notice concerns (for an invitation, the invitation and its organization), and the request time, and appendsnotification.mail_requestedwith schema version 1: aggregate typemail_request, aggregate ID equal to the request ID, aggregate version 1, and the payload{"mail_request_id": <id>, "kind": "notification"}and nothing else. - The relay publishes the event, and the consumer
notification_deliveryapplies it in the transaction of its dedup marker. It checks the envelope and thatmail_request_idequals 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 withsource_event_idset, and deletes the request row, all in that transaction. - A redelivered event is a
duplicateof 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. - 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_atNULL). 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 ahandler_rejecteddead letter; storage errors are retried. An account deleted after the handler read it makes the insert fail on the foreign key; the transaction is aborted, so the error is retried, and the retry finds the request deleted with the account and skips.
Why the event carries only a reference. Events stay in outbox_events and in Kafka for the topic retention, and the domain event rule allows only identifiers and minimal facts. FR19 also requires that a queue does not keep revoked data available. The text therefore lives in mail_requests, which the account's deletion removes by cascade, and only as long as needed: the handler deletes the row in the transaction that stores the rendered delivery. After that the text exists only in the delivery, under the same retention and access rules. The address is read from the account in the handler transaction, so it is the address current at creation.
Token mail. Verification and password reset bodies carry a one-time bearer token, which must never enter an event or a request row, and storage keeps only its SHA-256. mail_requests and schema version 1 therefore allow only kind notification. Token mail deliveries are created by the identity flows directly in the transaction that issues the token, through ServiceMailer, which uses domain.NewDelivery and DeliveryRepository.Create and binds the delivery to the token. Registration and resend create verification mail; password reset is a future flow.
Immutable content. A delivery stores the rendered body and never renders it again. Rendering at send time would need the raw token, which exists only in memory when it is issued, and a retry under the same idempotency key must repeat exactly the same body: Resend treats a changed body under an old key as a conflict. The domain recomputes the content hash on every read and fails with domain.ErrMailContentIntegrity on a mismatch. The trigger deliveries_refuse_content_change refuses an UPDATE that changes the recipient, content, idempotency key, source event, or creation time (SQLSTATE 23000, constraint deliveries_content_immutable, mapped to outbound.ErrDeliveryContentImmutable). A new template version therefore applies to new deliveries only; old template files are not needed to send a stored delivery.
Personal data at rest. A delivery row holds the recipient address and the bodies, and a pending mail_requests row holds the raw notification text. The body of a token mail holds a live bearer token until it is used, replaced, or expires (at most 7 days by policy), so read access to deliveries is access to that account's confirmation or reset link, and database dumps and backups carry it. The consequences:
- Queries for operations select metadata columns (ID, kind, status, attempts, times, provider) and never the bodies, the request text, or the address; see DEPLOY.md.
- Deleting an account deletes its mail requests, deliveries, and their attempts by cascade. The unverified account cleanup locks them with
FOR UPDATE SKIP LOCKEDlike tokens and sessions, so it never waits for the delivery consumer or a worker that holds a row. - The bodies of a token mail are cleared when the delivery reaches
accepted,rejected, orcancelled(body_redacted_at, see Sending service mail), so a database dump or backup holds no token of a finished mail; a retention rule that deletes other terminal deliveries after a bounded period is not implemented yet, and until it exists those rows stay. Encryption of the bodies at rest is not implemented either. Delivery,MailContent,MailRequest,NotificationText, andEmailAddressredact themselves infmtandslogoutput: a delivery logs its ID, kind, status, and provider. Handler errors name the broken rule and never quote the payload, and the adapter replaces PostgreSQL error text with its SQLSTATE and constraint. The delivery metrics carry only the kind, status, provider, and quota window labels, never the address, a user or delivery ID, the provider account label, or the subject.
Statuses. The values follow the MailSender outcomes:
| Status | Meaning | next_attempt_at |
|---|---|---|
pending |
Waits for its first attempt, or for a retry after a temporary or rate_limited rejection |
Required: when it is due |
accepted |
The provider accepted the message and returned provider_message_id: "accepted by the provider". Not delivery to or reading by a person; no status claims that |
None; terminal |
rejected |
A permanent or invalid_request rejection; the cause must be fixed |
None; terminal |
unknown |
The attempt may have reached the provider (delivery_uncertain). Never "not sent": an eligible automatic or operator-approved retry uses the pinned key and stored body |
Optional; none means operator review is required |
cancelled |
The message was deliberately not sent and never will be: the token or the account no longer matches, a notification's rights no longer hold, or the stored message is unsendable. cancel_reason says why; no attempt is recorded |
None; terminal |
waiting_quota |
A provider quota or the local quota is used up | Optional: the expected reset (see Mail quotas); none when the reset is unknown, for example after a provider quota answer that names neither a window nor a wait, and an operator decides |
Transitions:
Delivery.RecordAttempttakes the result of one transport attempt and appends an attempt row.pending,waiting_quota, andunknownaccept an attempt:acceptedgivesaccepted, apermanentorinvalid_requestrejection givesrejected,temporaryorrate_limitedgivespending,quota_exhaustedgiveswaiting_quota, andunknowngivesunknown.accepted,rejected, andcancelledrefuse any further attempt withdomain.ErrDeliveryTransition.Delivery.WaitForQuota(at, until)parks apendingorwaiting_quotadelivery inwaiting_quotawithout an attempt, for the case where the local mail quota defers a send before the transport is called; a zerountilmeans the reset is unknown. It refusesunknown, whose earlier attempt may have been accepted and whose retry belongs to the retry policy, and the terminal statuses.DeliveryRepository.WaitForQuotastores it.Delivery.Cancel(at, reason)ends apendingorwaiting_quotadelivery incancelledwithout an attempt; the reason is one oftoken_missing,token_purpose_mismatch,token_owner_mismatch,token_consumed,token_revoked,token_expired,account_not_current,recipient_mismatch,content_invalid,processing_failed,rights_revoked,recipient_ineligible, orsource_closed. It refusesunknown, likeWaitForQuota: an earlier attempt may have been accepted, so it is never reported as not sent.DeliveryRepository.Cancelstores it.Delivery.Rebind(at, account)moves a delivery that has no attempt yet to another provider account; see below.DeliveryRepository.Rebindstores it.
Every change advances version, and the store applies it only over the previous version. The next attempt time comes from the caller's retry policy and must fit the target status; the CHECK deliveries_next_attempt_matches_status repeats the rule, and deliveries_provider_message_id_when_accepted requires the provider ID exactly for accepted.
Attempts. The current state sits in counters on deliveries, so a worker reads one row, and every attempt is a row in delivery_attempts: number, time, outcome, rejection, provider code, provider message ID, wait hint, resulting status, and next attempt time. The first provider-call start is recorded by the database clock and is the age source for the automatic cutoff. Operator decisions are kept separately in delivery_retry_decisions, including the delivery ID, current attempt count, actor handle, explicit duplicate-risk acknowledgement, whether an expired lease was recovered, and decision time. It has no foreign key, so deleting the account does not erase the audit; row-level UPDATE/DELETE and statement-level TRUNCATE are refused. The wait hint is stored exactly as the Go time.Duration in nanoseconds (retry_after_ns), so a round trip never changes it. RecordAttempt stores the delivery and the attempt in one statement: a data-modifying CTE updates the delivery only while its version is still the one before the attempt and appends the attempt only if that update matched. A second writer of the same attempt gets outbound.ErrDeliveryVersionConflict and writes nothing. A trigger refuses an UPDATE of an attempt.
Quota accounting is not derived from this history: the cascade from an account deletes its deliveries and attempts, so counting sends from delivery_attempts would lose sends of deleted accounts and let the provider quota be exceeded. The quota therefore has its own counter that does not cascade, keyed by provider, provider account, and UTC day or month; see Mail quotas.
Provider account. Each delivery is pinned to the transport and account configured when it was created. Providers and accounts share no idempotency keys, so FR19 forbids moving an uncertain delivery to another one; a configuration change applies to new deliveries only, and the sending worker must use the pinned account. EMAIL_ACCOUNT names the account (default unless set); change it whenever RESEND_API_KEY moves to another Resend account. The account may change only while the delivery has no attempt, because before the first attempt no provider has seen the key: Delivery.Rebind refuses a delivery with an attempt or in a terminal status, and the trigger refuses a provider change after an attempt (constraint deliveries_provider_pinned, mapped to outbound.ErrDeliveryProviderPinned). The service mail worker uses it for deliveries created while EMAIL_PROVIDER=disabled once the stand enables a transport; whether it rebinds them automatically or on an operator's request is its decision.
Migration 00012_add_delivery_sending.sql is additive; existing rows stay valid. It adds to deliveries: email_token_id (a nullable foreign key to email_tokens.id for token mail, immutable like the rest of the content, NULL for notifications), cancel_reason (set exactly when the status is cancelled, CHECK-limited to the reasons above), the lease columns claim_owner and claimed_until (both or neither; only a delivery the worker may still send holds one), first_send_started_at (when the first request started, by the database clock), failure_count (consecutive failures of the worker on the row), body_redacted_at (the bodies of a token mail were cleared), the status cancelled with its CHECKs, and two partial indexes: deliveries_due_idx on (next_attempt_at, id) whose predicate names the service kinds and the statuses that are picked up again, so notification rows never enter it and an idle poll does not scan them, and one on email_token_id. The trigger deliveries_refuse_content_change also allows exactly one change of the bodies: a terminal token mail may have both set to empty together with body_redacted_at, once. It adds the password_reset token purpose to email_tokens. The down migration turns cancelled deliveries into rejected ones and deletes reset tokens. Planned: a cancelled delivery for a revoked permission.
The store provides Get, ListAttempts, the version-checked RecordAttempt, WaitForQuota, Cancel, and Rebind, and for the sending workers ClaimDue (one statement per lane, selected by ClaimScope), ReleaseClaim, and ServiceMailState. The notification rights reader is UnitOfWork.NotificationRights(). Migrations 00044_add_notification_subject.sql and 00045_send_product_notifications.sql add the subject columns, the product due index deliveries_product_due_idx, and the cancel reasons of the rights checks. Migration 00017_retry_unknown_mail.sql adds the manual-cycle markers, the append-only decision journal, and unknown to the due index predicate. It drops and recreates the partial due index, which takes a table lock while it rebuilds. Rolling this migration back drops the decision journal and its audit data; preserve an export first if rollback is required.
Mail quotas
Implemented: quota windows and limits in backend/internal/domain/mail_quota.go; the outbound.MailQuotaRepository port (port/outbound/mail_quota.go), whose writes go through UnitOfWork.MailQuotas() and whose reads also go through postgres.MailQuotaStore; migration 00007_create_mail_quota_usage.sql with the mail_quota_usage and mail_quota_reservations tables; the queries in backend/db/queries/mail_quota.sql; in backend/internal/usecase/notification/, QuotaGate with PrepareSend and SettleSend (quota.go), the startup report ReportQuotaUsage, and the user status reader DeliveryStatusReader (delivery_status.go); SendResult.QuotaPeriod in the mail port, filled by the Resend adapter; and the startup report in bootstrap (bootstrap/mail_quota.go). The sending worker calls the gate around MailSender.Send and bootstrap/mail_sender.go builds it from configuration with resend.IdempotencyWindow or zero for SMTP; see Sending service mail. Planned: the API or identity flow that shows the status reader's result. Both lanes count against the quota: a product notification is admitted only while the windows keep the service reserve free (see Sending product notifications).
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 (dayormonth), and period start (a UTC date; the first day for a month), withused_recipients,provider_exhausted_at, andupdated_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 lastsettled_outcome(accepted,unknown,rejected, ornot_sent) withsettled_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:
- 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". Anacceptedorrejecteddelivery fails withdomain.ErrDeliveryTransition. - 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. - 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.
- 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
pendingorwaiting_quotadelivery is stored aswaiting_quotawithnext_attempt_atat that time throughDelivery.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. Anunknowndelivery is returned unchanged with the reset time: its retry belongs to the retry policy, and parking it would hide that an earlier attempt may have been accepted.
The row locks last until the caller's transaction ends, so the worker must commit before it calls the transport; the cost is that sends of one account reserve one after another.
Settlement. QuotaGate.SettleSend(ctx, unit, permit, result, sendErr) runs in the transaction that stores the attempt or, after a Send error, the delivery's next state. It always journals the outcome, and:
acceptedandunknownkeep the reservation. An unknown attempt may have been sent, and counting it errs on the safe side.- A
Senderror, where nothing left the process, and everyrejectedoutcome 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 setsreleased_atonly 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. rejectedwithquota_exhaustedalso refines the count from the provider's answer. The window comes fromSendResult.QuotaPeriod, which the transport fills from the provider's own error name (Resenddaily_quota_exceededgivesday,monthly_quota_exceededgivesmonth), 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 recordsprovider_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.SettleSendreturns the time to store as the attempt'snext_attempt_at.
No purchase, plan switch, or transport change. The gate only defers. Nothing buys a plan, moves the account to a paid tier, or sends a waiting delivery through another transport, provider, or account; the delivery stays pinned (see Mail deliveries). Switching EMAIL_PROVIDER is an operator decision, and the gate applies to the new transport too: it runs in the usecase before any transport is called, smtp needs stated limits, and deliveries pinned to the old account are refused instead of being sent without a limit. Counters are kept per provider and account label, so a new transport or a new EMAIL_ACCOUNT label starts with its own count. A transport that reaches the same provider account by another route, for example Resend's own SMTP endpoint, shares the provider's quota but not the local count, and so does a relabeled account: the provider's refusal then refines the count as above, the startup report warns about other labels with usage this month, and the operator should set the limits to what the account has left.
Startup report. After the startup migrations, unless EMAIL_PROVIDER=disabled, bootstrap logs mail quota usage with the provider, account, and the day and month usage and limits, and warns other accounts of this mail provider have quota usage this month; renaming EMAIL_ACCOUNT without changing the provider account resets the local count when other account labels of the same provider have usage this month. A failed read is a warning and never stops startup.
What the user sees. notification.DeliveryStatusReader.LatestForUser(ctx, userID, kind) returns the status of the newest delivery of a kind addressed to the account: the kind, the status, WaitingUntil for waiting_quota (the stored next_attempt_at), and the time of the last change. It returns no address, subject, body, provider, or delivery ID, and false when there is none. The query is scoped to deliveries addressed to the given account, so the caller must pass the authenticated account's own ID, never an ID from request input. No HTTP route calls it yet; the identity flows and a later API show it. A user interface maps the statuses as follows:
| Status | What the user is told |
|---|---|
waiting_quota with WaitingUntil |
Your email is waiting until <WaitingUntil> |
waiting_quota without WaitingUntil |
Your email is waiting; the time is not known yet |
pending, unknown |
Your email is being sent. unknown is not shown as a failure: the message may have been accepted |
accepted |
Your email was handed to the email provider, which accepted it. We cannot confirm that it reached your inbox |
rejected |
Your email could not be sent |
cancelled |
Your email was not sent because the link in it is no longer valid; request a new one |
Operators read the same rows with the queries in DEPLOY.md. The gate logs mail quota is used up; the delivery waits for the reset at info level and the mail provider reported its quota used up; local sending stops until the reset at warn level, with only the delivery ID, provider, period, and reset time. The quota gauges come from MailQuotaUsageReader.Usage for the configured account, with the labels provider and window only; see Metrics, telemetry, and alerts.
Sending service mail
Implemented: the sending usecase ServiceMailSender (backend/internal/usecase/notification/service_sender.go), the enqueue usecase ServiceMailer (service_mail.go), the retry schedule RetryPolicy (send_retry.go), bounded retries of unknown Resend outcomes, audited operator decisions through DeliveryRetryOperator, and the local command backend/cmd/mail-retry/. Delivery.CheckServiceMail and Delivery.Cancel hold the cancel reasons (backend/internal/domain/delivery.go, delivery_guard.go), the loop is in backend/internal/worker/mailsender/, and the inbound port is inbound.MailPass (port/inbound/mail_sender.go). The repository and migrations 00012_add_delivery_sending.sql and 00017_retry_unknown_mail.sql store attempts, leases, retry cutoffs, and operator decisions. Registration queues a verification email, and ConfirmEmail consumes its link. The password reset flow is not implemented.
Scope. The service worker claims only the kinds verification and password_reset. A product notification is never claimed here, whatever its state; the notification lane is described in Sending product notifications. Service mail needs no consent record of any purpose: it is part of the account flow, so nothing reads the consent ledger, and C2 (publication of the candidate card) and the other product consents play no part. What stands between the account and the mail is the check below, not a consent.
Enqueue. ServiceMailer.EnqueueVerification and EnqueuePasswordReset run in the transaction that inserts the token, with the token record, the raw token, the recipient address, and the lifetime in hours. They check that the token purpose fits the message, render the message once with the current template version, and store a pending delivery bound to the token (email_token_id) under the token's ID as the delivery ID. A repeated call for the same token stores nothing new, and the stored body stays as it was.
Links. The token travels only in the URL fragment: <APP_PUBLIC_URL>/verify-email#token=<token> and <APP_PUBLIC_URL>/reset-password#token=<token>, built by mailtemplate (tokenLink). A browser never sends the fragment to a server, so the token stays out of the nginx access log, which records $uri, out of Referer headers, and out of the Go request log; it is not in the path and not in the query. The frontend reads and removes the fragment, waits for explicit confirmation, then sends the token and registration password in the API request. It also consumes a new link opened in the same tab and ignores results from an older in-flight request. The password reset route and API are not implemented. The renderer rejects a token in any other place, its golden files and tests fix the format, and the delivery tests check that the stored body holds the link with the fragment and no ?token=. The body in deliveries holds the live token until the mail is sent or cancelled; see Personal data at rest.
Codes. Each verification message also carries a six-digit code: in the text part as the line Код подтверждения: <code> (the Russian copy), and in the HTML part as a large block. The code lives 30 minutes, or until its token ends when that is sooner, and the message states that lifetime. The code is an alternative to the link, not a replacement: ConfirmEmailByCode checks it (see Registration, email verification, and resend). Like the link, the code stays in the body of the delivery until the mail is sent or cancelled, and is then redacted; the token row keeps only a keyed digest of the code, never the code. Read access to deliveries before that point exposes the code too.
One pass of ServiceMailSender.ProcessNext takes one delivery through three steps:
- Claim transaction.
DeliveryRepository.ClaimDuetakes the most overdue due delivery withFOR UPDATE SKIP LOCKED: kindverificationorpassword_reset(literals that match the predicate ofdeliveries_due_idx, so the poll reads only that small index), statuspending,waiting_quota, or a scheduledunknown,next_attempt_atpassed, pinned to the configured provider account, and held by no live lease. An initial uncertain result is scheduled only while the delivery is inside the automatic cutoff; terminal unknown rows and unknown rows without a due time wait for an operator. A single-use manual authorization also makes an unknown row due. It setsclaim_ownerandclaimed_until(the lease) without changing the version or the update time, so several processes never take one delivery. The lease is measured by the database clock (clock_timestamp()plus the lease length, and live whileclaimed_untilis later thanclock_timestamp()), never by the clock of an application instance, so instances whose clocks differ cannot take over a live lease or hold a dead one; due times stay on the application clock that wrote them. In the same transaction the sender rebinds mail stored whileEMAIL_PROVIDER=disabledto the configured account (allowed before the first attempt only, so no provider holds its key), runs the check below, and thenQuotaGate.PrepareSend, which reserves the recipient or parks the delivery inwaiting_quota. The transaction commits before the transport is called, so a slow provider never holds a row lock. A failure inside it (a deterministic one, such as a row that cannot be restored) rolls the lease back too, so the failure is then recorded for the row in a transaction of its own; see Failing rows. - Check right before the send, one short transaction: it locks the delivery row (only for the lease holder), reads the token and the account again with
ServiceMailState, so a revocation after the claim committed is honored, and recordsfirst_send_started_atby the database clock. For an uncertain retry, it rechecks the age against the 23-hour cutoff here, after quota and lease waits, immediately before any network call. A manual authorization is consumed only when this send-start is recorded. A mail that is no longer valid is cancelled and its reservation given back. Then one call toMailSender.Sendwith the stored content and the stable idempotency keydelivery/<id>. The transport never retries internally. The call is bounded by what is left of the lease after the claim and the settlement budget, and by the shutdown grace. - Settlement transaction. It locks the delivery row first (only while this worker still holds the lease), then
QuotaGate.SettleSendandDeliveryRepository.RecordClaimedAttemptcommit together, and the lease ends with the attempt.RecordClaimedAttemptapplies only over the delivery's version and only for the lease owner, so a worker whose lease was taken over cannot record, and if two workers reach this step for one delivery only the first is kept; the other rolls back, including its quota settlement, and reportslease_lost. A database failure while storing the answer is repeated up to three times inside a settlement budget, because the answer exists only in memory until it is stored.
Time budget. The lease is EMAIL_TIMEOUT plus one minute. The claim and the check come first; the call gets what remains of the lease minus the settlement budget (20 seconds), so claim, call, and the whole settlement fit inside the lease. When shutdown has begun the settlement budget is the shorter of 5 seconds and SHUTDOWN_TIMEOUT minus the 3-second shutdown grace (at least 1 second), so the process stops within its shutdown timeout, which is 10 seconds by default (the Compose stop grace period is 30 seconds). A result that cannot be stored in time is covered by the takeover below.
Lock order. Every path locks the delivery row first and the quota rows second: the claim locks the row with FOR UPDATE SKIP LOCKED, and the check and the settlement start with LockClaimed (SELECT ... FOR UPDATE of the row of the lease holder), so no two paths can wait for each other in opposite directions.
Check before sending. In the claim transaction, Delivery.CheckServiceMail compares the delivery with a snapshot read in one statement (ServiceMailState: the token and the account, no lock, only the address comparison key). The first failure cancels the delivery with cancelled and that reason; nothing is reserved and nothing is sent:
| Order | Rule | Reason |
|---|---|---|
| 1 | A token is bound and its row exists | token_missing |
| 2 | Its purpose is the one the mail kind carries (email_verification for verification, password_reset for reset) |
token_purpose_mismatch |
| 3 | It belongs to the recipient account | token_owner_mismatch |
| 4 | It is not consumed | token_consumed |
| 5 | It is not revoked (invalidated_at, by a resend or a re-registration) |
token_revoked |
| 6 | It has not expired | token_expired |
| 7 | The account still has the registration version the token was issued for, and a verification mail does not go to an address that is verified already | account_not_current |
| 8 | The address in the delivery is still the account's address | recipient_mismatch |
A claimed row whose content no longer matches its hash (only a manual edit can cause that) is cancelled by the claim itself with content_invalid, with the bodies cleared like any cancelled token mail, and logged at error level with the delivery ID. Any other failure to restore a row may be transient, so it is not cancelled for good: it is a failing row, below.
There is no deactivated flag on an account. "Current" is rule 7 and the token rules: a re-registration moves the version and revokes the token, and a deleted account takes its deliveries with it by cascade, so nothing is left to send. A reset mail has no verification-state rule: that the reset applies only to verified accounts is a product decision for the reset flow. The check is a snapshot: a token consumed or revoked after it, before the provider call, still lets the mail go. That is harmless, because the link is checked again when it is used.
What a provider answer becomes. The delivery state machine of domain.Delivery decides; the worker only fills the attempt:
| Result | Delivery | Next attempt | Quota |
|---|---|---|---|
accepted |
accepted, provider message ID stored |
none | counted |
rejected permanent or invalid_request |
rejected |
none | released |
rejected temporary or rate_limited |
pending |
now plus RetryPolicy: 1 minute, doubling to at most 30 minutes, never shorter than the provider's Retry-After |
released |
rejected quota_exhausted |
waiting_quota |
the reset the gate returns (next 00:00 UTC for a day, the first of the next month for a month); none when the provider named no window | window marked full |
unknown |
unknown |
minimum retry schedule until the 23-hour cutoff; after that, none until an operator decision | counted |
Send error: no transport (ErrMailChannelUnavailable) or the context ended |
unchanged, lease released | still due | released |
Send error: invalid message (ErrInvalidOutgoingMail) |
cancelled, content_invalid |
none | released |
Send error: anything else without an answer |
not counted against the row; it moves back by RetryPolicy and the worker backs off |
now plus RetryPolicy |
released |
The retry schedule has no attempt limit on purpose: the token expires, and the check then cancels the delivery with token_expired. Each delay gets bounded jitter, up to a fifth over the schedule, from an injectable source (nil in tests, so times are exact), so deliveries refused together do not return together. Confirmed temporary and rate_limited refusals are retried with the same pinned account, key, and body; the Retry-After value is a lower bound. A confirmed refusal proves that request was not accepted, but it does not clear uncertainty from an earlier unknown attempt. Automatic retries of uncertain Resend outcomes use the same key and exact body only until 23 hours after the database-recorded first send, one hour before Resend's documented 24-hour key expiry. The last storage check repeats this cutoff immediately before the provider call. An unknown answer or a lost lease after send-start ends automatic retries and requires operator review. A pending manual decision permits a potential send; confirmed temporary or 429 refusals may continue under that decision, but an unknown result or lost lease after send-start requires another explicit decision. Recovery records a lost send as an unknown attempt before it schedules the new decision, and does not call the provider. A manual decision does not restart Resend's key window. The local mail-retry command uses the database credential as its operator boundary: make -C backend mail-retry ARGS='inspect --delivery <uuid>' shows metadata and the duplicate warning, while make -C backend mail-retry ARGS='retry --delivery <uuid> --actor operator:<handle> --acknowledge-duplicate-risk' prints the warning before atomically scheduling and auditing a single-use decision. It never calls a provider. The actor is an audit handle, not an authentication mechanism; there is no HTTP operator endpoint. Reusing an expired key may send a duplicate despite the acknowledgement. The alert LincodexMailDeliveryUnknownOutcome fires while an outcome needs review.
Automatic retry after a lost worker. If a worker stops after a provider call but before storing the answer, another worker may claim that attempt and repeat the request with the same key while the 23-hour cutoff has not passed. A lost result after a manual send-start is recorded as unknown and waits for another operator decision; recovery does not call the provider. Resend answers a repeated key and body with the original result, and the quota gate reuses the open reservation, so the message exists once and counts once. The provider keeps the key for 24 hours from the first request, so the age is counted from first_send_started_at (set by the database clock right before the first request), not from the latest lease: however many workers were lost in turn, and whatever the lease length, once that age reaches 23 hours (the window less a one-hour safety margin) the earlier request may be forgotten and repeating it could send twice, so the delivery is recorded as an unknown attempt without a next attempt instead. The same applies at once to a transport without provider-side deduplication (window zero, SMTP). A lease that never reached the first request leaves nothing in doubt.
Failing rows. A fault in one row must not hold the head of the queue. When the claim transaction fails after it took a row, its lease rolls back with it, so the same row would be claimed again at once and every delivery behind it would wait. Only a fault that the row itself causes is counted against it: a domain rule it breaks (ErrInvalidDelivery, ErrDeliveryTransition, invalid content or address), a row that cannot be restored for a reason other than a hash mismatch, or a data or integrity constraint refusal (SQLSTATE classes 22 and 23, outbound.ErrRowFault). Everything else says nothing about the row and is never counted: a context that ended, a timeout, a deadlock, a lost connection (SQLSTATE 08, 40, 53, 57, XX), an I/O error, a missing quota configuration. Such an error is returned to the worker, which backs off like for any global failure, and the lease expires or rolls back. For a counted fault the sender records the failure in a short transaction of its own (RecordFailure): failure_count is incremented, the lease ends, and the row is due again by RetryPolicy (outcome row_failed; the next pass takes the delivery behind it). The statement leaves a row alone that another worker holds under a live lease, so a claim that rolled back cannot disturb a row that someone else has just claimed. The count means consecutive failures: a successful claim and preparation (the check before the send) clears it, and so does a recorded attempt. A circuit breaker in the worker stops the counting when failures hit different rows pass after pass: three passes in a row that fail on three different rows are read as a global fault, the worker waits with a growing backoff (a row_failed pass never loops at once), and failures are moved back but not counted, and no row is cancelled, until a pass succeeds. After 3 consecutive counted failures the row is cancelled with the reason processing_failed, the existing terminal status that fits: it is visible to the operator and the alert below fires, and a new status was not needed. A database outage that also stops this record leaves the row under its lease, which expires.
EMAIL_PROVIDER=disabled. Bootstrap does not start the loop: newMailSenderWorker returns no worker and logs mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait, so lincodex_mail_sender_running stays 0 and LincodexMailDeliveriesOverdue stays silent. Stored mail waits, pinned to disabled; after the stand restarts with a transport the worker rebinds it and sends it, if the token and the account still pass the check. The local operator command is available only with the Resend transport selected. A worker that is run against the disabled transport anyway (tests) gets ErrMailChannelUnavailable from every send, records nothing, releases the lease and the reservation, and backs off (5 seconds doubling to 2 minutes) instead of claiming again at once, so it never spins.
Loop and shutdown. worker/mailsender repeats passes: a pass that handled a delivery is followed at once by the next, an idle pass waits 5 seconds, and a database failure, a missing transport, or an interrupted call waits with the growing backoff. When the context ends the worker claims nothing more, lets the send in progress continue for 5 seconds, stores its result, and returns; the gauge is 0 from then on. The loop is a goroutine of the backend process on its own pool of two connections, like the other workers; more throughput comes from more instances, and each handles one delivery at a time, which suits service mail under the Resend Free quota.
Token at rest. The body of a token mail holds the one-time token, and a reset token is an account takeover primitive for anyone who can read the database or a backup. When a token mail reaches accepted, rejected, or cancelled (by any path: an attempt, a cancellation, the broken-row cancellation, or processing_failed), the same statement sets text_body and html_body to empty and body_redacted_at; the subject, the content hash, and the template version stay. The trigger allows exactly that change once, for a terminal row, and refuses any other change of the bodies or of the mark; the CHECK deliveries_body_present accepts an empty body only with the mark; the domain restores such a row as redacted content (RestoreRedactedMailContent), which cannot be sent. unknown keeps its body while it waits for review or a retry, because the worker may need to resend the stored content. The local command does not display or edit the body. Notifications are not redacted. Rolling back migration 00012 puts a placeholder in cleared bodies.
Privacy. Logs name a delivery only by delivery_id, its kind, and closed values (the outcome and the cancel reason); no address, token, link, subject, or body appears in a log line, an error, or a metric label, and the metric has no labels at all. ServiceMailSender builds the outgoing message from the stored content and never logs it; OutgoingMail and Delivery redact themselves.
Test fixture only. resendfixture and resend.NewLoopbackSender are never used by production code: backend/.golangci.yml forbids importing the fixture and calling the constructor outside _test.go files (depguard and forbidigo), and bootstrap binds the real transport with resend.NewSender.
Tests. integration_test/mail_sender_test.go runs a local Resend fixture (resendfixture, an httptest server speaking the part of the API the transport uses, reached through resend.NewLoopbackSender, which accepts only a loopback endpoint) against PostgreSQL; see TESTING.md. It is a test fixture only; production binds the real Resend transport with its fixed endpoint.
Open points. Notifications are not counted in the overdue gauge, so a notification backlog does not fire LincodexMailDeliveriesOverdue (the gauge lincodex_mail_delivery_oldest_due_pending_age_seconds covers domain.ServiceMailKinds; its predicate is the one of deliveries_due_idx); the notification lane has no overdue alert yet. Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume.
Sending product notifications
Implemented: the notification lane of the sending loop. usecase/notification.NewNotificationSender (notification_sender.go) builds a DeliverySender (delivery_sender.go) for the notification kind. It claims with ClaimDueProductDelivery through the partial index deliveries_product_due_idx and uses the same transport, quota gate, and settlement as the service lane. A SubjectRights implementation decides, per subject kind, whether a notice may still go out. The invitation notice is invitationNoticeRights (invitation_rights.go), and its rule is Delivery.CheckInvitationNotice (backend/internal/domain/invitation_notice.go). bootstrap/notification_sender.go builds the loop with the service timing and EMAIL_PROVIDER.
Subject. A notification names the record whose rights it depends on: domain.MailSubject, stored with the request and copied to the delivery. The invitation send names the invitation and its organization. The subject is fixed with the delivery, and the content trigger refuses to change it (migration 00044_add_notification_subject.sql).
Rights check. Before the transport is called, the lane's eligibility runs twice: once in the claim transaction, and again in the check transaction that holds the delivery lock, so a change after the claim is honored. The invitation rule checks, in this order: the recipient account exists and its address is verified; the address of the delivery is still the address of the account; the invitation exists in the organization of the subject; the invitation still awaits an answer (delivered or viewed) and its response deadline has not passed; the candidate has not hidden the organization; and the candidate's publication (C2) is current. The notice declares no allowed fields: its body is fixed text that names neither the organization nor the terms, and it carries no contact, so no field consent (C4) applies. The content was rendered once when the request was handled, so the check is the only work before the transport call. Like the check of service mail, the rights read is a snapshot taken in the sending transaction.
Contacts. Mail never carries a contact. Contact reads are pull-only, and each read re-checks the consent and the grant, so a contact copied into mail would outlive its grant. A future notice that carries a candidate field or a contact adds its consent check to SubjectRights before it can be sent.
Cancel reasons. A failed check cancels the delivery with no attempt, no provider call, and no change of the provider account, and clears its bodies (deliveries_body_present allows the clearing of a cancelled notification). rights_revoked covers a hidden organization, a withdrawn publication, and an invitation that was answered, expired, or passed its deadline. recipient_ineligible covers a missing account or an unverified address, and recipient_mismatch a changed address. source_closed covers a notice that names no subject, or an invitation that no longer exists. A subject kind that this build cannot check is neither sent nor cancelled: the claim returns ErrNoSubjectRights and the row waits for a build that can check it. None of these reasons counts as a broken cancellation for LincodexMailCancelledBroken.
Reserve. The notification lane's quota gate admits a send only while, after it, each window keeps at least EMAIL_SERVICE_RESERVE_DAILY and EMAIL_SERVICE_RESERVE_MONTHLY recipients free (QuotaGate.WithReserve). The defaults are a fifth of each quota limit: 20 a day and 600 a month on the Resend Free plan. The service lane keeps the full limits, so service mail always has its share of the same windows. A notification that the reserve refuses is parked in waiting_quota until the reset, and an idle pass does not claim it again, so the loop does not spin. A provider answer that its quota is used up marks the full window, not the reserve.
Retention. Every due notice is checked when it is claimed, including one whose invitation ended long ago, so no cancellable row stays due. A cancelled notice loses its bodies. An accepted notice keeps its neutral body, which is an open point.
Loop and disabled transport. The loop has its own gauge, lincodex_notification_sender_running, and its cancellations count in lincodex_mail_sender_cancelled_total by reason. With EMAIL_PROVIDER=disabled or without a database no loop starts, and a stored notice waits pinned to the transport it was created under, as service mail does. Once a transport runs, the loop rebinds the notice and sends it, if its rights still hold.
Privacy. Logs name a notice only by its delivery ID, kind, and closed values (the outcome and the cancel reason). The subject, the address, the candidate, and the body never appear in a log line, an error, or a metric label.
Open points. The invitation notice requires the candidate's publication, so a withdrawn publication cancels a pending notice; the product owner should confirm that choice. Accepted notices keep their neutral bodies, and no retention rule clears them yet. The notification lane has no overdue alert; the lincodex_mail_deliveries{kind="notification",status="pending"} gauge shows its backlog.
Internal notifications
Implemented: the inbox of delivered events with a read state, the consumer that fills it, and four operations that list and mark it. The send of an invitation is the first product producer (Sending invitations); the synthetic event remains for tests and probes.
Code: migrations backend/db/migrations/00032_create_notification_inbox.sql and 00036_allow_synthetic_notification_event.sql, queries backend/db/queries/notification_inbox.sql, the model backend/internal/domain/notification_inbox.go, the port port/outbound/notification_inbox.go (UnitOfWork.NotificationInbox()), the adapter adapter/secondary/postgres/notification_inbox.go, the usecase files usecase/notification/inbox.go, inbox_handler.go, and inbox_content.go, the HTTP handler adapter/primary/http/v1/notifications.go with its cursor notification_cursor.go, the wiring in bootstrap/notification.go and eventHandlers(), and the frontend feature frontend/src/features/notifications/ with the page frontend/src/pages/notifications/. The operations are in api/README.en.md.
- The inbox is the delivery state inside the platform. A row means that the notification reached the recipient's cabinet, and
read_atsays that the recipient read it. Mail is another channel with its own state indeliveries(Mail deliveries), and neither reads the other. The inbox handler never readsdeliveries,mail_requests, or the verification state of an address, so an unverified address,EMAIL_PROVIDER=disabled, or a failed send never blocks a notification, and a sent email never counts as seen. The delivered state of an invitation is its owndelivered_at, written by the send transaction; the inbox row of its notification follows through the consumer. - A row holds references, not text.
notification_inbox_eventshas the key(recipient_user_id, event_id)and the columnsorganization_id,event_type,schema_version,source_type,source_id,occurred_at, andread_at. It stores no title, summary, name, contact, or score. Triggers keep the reference immutable (only the firstread_atmay be set) and refuse a direct delete; deleting the recipient's account removes the rows by cascade, and the organization foreign key isRESTRICT. A CHECK allows only the pairs of event type and source type thatdomain.NotificationInboxSourceForallows, both at schema version 1:invitation.deliveredwithinvitation, and the syntheticnotification.synthetic_deliveredwithorganization. Migration 00032 is deployed and unchanged; 00036 only widened the CHECK, and its rollback refuses while a synthetic row exists. - Producer contract. A producer appends, in its own transaction, an event of an allowlisted type with the payload
{"recipient_user_id": ..., "organization_id": ...}(two identifiers, no unknown field, schema version 1) and the aggregate that the type names. Forinvitation.deliveredthe aggregate is theinvitation, which is also the content source. The synthetic event uses a one-offsynthetic_noticeaggregate at version 1, and its source is the organization of the payload;notification.SyntheticNoticeEventPayloadis the single writer of that payload. The invitation module needed no change in the table, the consumer, or the API: the send transaction appendsinvitation.deliveredthroughnotification.InvitationNotifier, andnotification.ResolveInvitationNoticeis registered for the sourceinvitationinnotification.DefaultInboxSourceResolvers(). - Synthetic event type.
notification.synthetic_deliveredhas no product meaning. It exists so that the whole path (outbox, relay, Kafka, consumer, read-time check, list, read state) can be exercised before a real producer exists and in browser tests. It is off by default: the consumer handles it and the inbox renders it only whenNOTIFICATION_SYNTHETIC_ENABLED=true(a development or browser-test stand; the e2e overlay sets it). With the switch off the event is acknowledged and ignored and a stored synthetic row is listed without content; the database CHECK allows the type either way, so turning the switch on needs no migration. Only code that can append to the outbox can produce it, and its content is a fixed text that names the sending organization. The browser suite appends it through thecompany-fixture(Go build tage2e), never through a user operation. - Consumer
notification_inbox.InboxHandlerhandles the allowlisted types. In the transaction of the dedup marker it checks the envelope and the payload and rejects a broken event for good (ErrEventRejected), skips a recipient whose account was deleted, and stores the row withON CONFLICT DO NOTHINGon the key. A recipient deleted between the check and the insert aborts the insert with a foreign-key error that names the recipient; the handler returns it as a retryable error, and the retry finds the account gone and skips, while a foreign-key error on the organization is rejected for good. Three layers keep one row per recipient and event ID: the consumer marker, the key, and the comparison of a duplicate with the stored metadata, which rejects an event ID that comes again with other metadata instead of overwriting it. A replay under a renamed consumer therefore stores no second row.occurred_atis the informational insert time of the outbox row; it orders the list together with the event ID. The consumer group<CONSUMER_GROUP_PREFIX>.notification_inboxis new, so it starts at the earliest retained event; events of other types are counted as ignored. - Content is resolved at read time.
InboxServicelists a page and calls the resolver of each item's source type in the transaction that authorized the viewer; the result is never stored. A resolver returnsErrInboxContentUnavailablewhen the source is gone or the recipient may not see it now. The item then stays in the list withcontentnull, the client shows a generic line, and an earlier text is never shown. A source type without a resolver is unavailable, never guessed. The resolver of a delivered invitation reads it only when it is addressed to the recipient and delivered, in the organization of the entry, and names the organization and the role; it shows no candidate value and links to/candidate/invitations. The resolver of the synthetic notice uses a fixed Russian text that names the sending organization by its current name, whichOrganizationNameForRecipientreads under the recipient's current standing. Both read the name that way: a candidate sees the name until they hide the organization, and an employer while their membership is active. A name that does not fit the presentation limits is not shown. A content link is a same-origin path of a narrow alphabet, and the client opens it only inside its own cabinet. - Scope. The candidate cabinet needs a verified candidate account and lists every organization context of the caller. The cabinet of one organization needs an employer account with a verified email (otherwise 403
email_not_verified, like the other organization operations) and an active membership of any role in the organization of the path. The membership is lockedFOR SHAREwithLockActiveMembershipin the transaction of the list or the mark, like the card reads, so a revocation cannot commit between the check and the read and stops the next request. The recipient always comes from the session; the organization of the path narrows the rows and a path identifier alone grants nothing. A candidate on an organization route and an employer on the candidate route get 403. A missing membership, an unknown organization, an item of another account, an item of another organization, and an unknown ID all get the same 404not_found. The organization routes are not in the owner-only list ofNewCompanyContextMiddleware;TestCompanyContextOperationInventoryMatchesOpenAPInames them as authorized in their own transaction. - Reading and marking.
GET /api/v1/me/notificationsandGET /api/v1/organizations/{org_id}/notificationsreturn a newest-first page with a cursor bound to the account and the cabinet; a cursor of another account or cabinet is a 400.POST .../{notification_id}/readstores the first read time and returns it again on every repeat. It reads no source and returns no content, so an item without content can still be marked. All four areCache-Control: no-store; a mark needs the session, the CSRF token, and an allowed Origin, and no Idempotency-Key because it is idempotent by its effect. No problem code was added. - Frontend.
features/notificationsexportsNotificationInbox(candidate or one organization) andOrganizationNotificationInbox(the chooser of the organization in theorganization_idparameter plus the inbox). The pages/candidate/notificationsand/employer/notificationsand an entry "Уведомления" in each shell use them. The list is read on every visit and never kept (gcTime: 0), is keyed by account and cabinet, and is dropped when the account or the session changes or when access is refused. States: loading, empty, error with retry, forbidden, an item without content, and "show more". The read state is a word, not only a style, the mark is a native button, and focus moves to the item's heading after it succeeds. - Trade-off: eventual consistency. The row is written by the consumer after the relay and Kafka, so a notification appears seconds after the producer committed, not inside the producer's transaction. The alternative, writing the row in the producer's transaction through
UnitOfWork.NotificationInbox(), would make it immediate but would tie every producer to the inbox and drop the replay and dead-letter handling that the consumer gives. The browser suite therefore waits for the item and then replays the event. - Tests. Unit:
domain/notification_inbox_test.go,usecase/notification/inbox_test.goandinbox_handler_test.go(cabinet checks, membership revocation, resolver fallback, idempotent handler, rejected events, aninvitation.deliveredevent under the same contract),adapter/primary/http/v1/notifications_test.go,adapter/primary/http/notification_contract_test.go,bootstrap/consumers_test.go, and the feature tests infrontend/src/features/notifications/. Integration:TestNotificationInboxOverHTTPandTestSyntheticNotificationMigration*. Browser:frontend/e2e/notifications.spec.tsin the registration mode (TESTING.md). - Not implemented: an unread counter or badge in the shells, live updates (the list is read on a visit and on window focus), archiving or deleting an item, retention of old rows, per-role filtering of employer notifications, a mail preference, and a metric for the inbox. The rows of the synthetic type are never removed by the application.
Product policy versions
Implemented as storage, a publisher, and a startup seed: migration backend/db/migrations/00003_create_policy_versions.sql, queries in backend/db/queries/policy.sql, the typed policy in backend/internal/domain/ (policy.go, policy_document.go, policy_version.go, policy_demo.go), the outbound.PolicyRepository port (port/outbound/policy.go), the sqlc-backed adapter in backend/internal/adapter/secondary/postgres/policy.go, and the publisher in backend/internal/usecase/policy/. No product rule reads the policy yet; invitations, quotas, assessment, sessions, and the search status will read it as their tasks are implemented.
policy_versions columns:
id: uuid primary key, a UUIDv7 generated in Go (domain.PolicyVersionID).policy_key: the policy family. Each family has one document layout and one decoder;product, decoded asdomain.ProductPolicy, is the only family, and both the domain and thepolicy_versions_policy_key_knownCHECK 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:demoorcalibrated, the calibration state of the whole version. Consumers read this flag. Thepolicy_versions_calibrated_kind_matches_documentCHECK and the domain refuse acalibratedversion whose document marks the assessment section as uncalibrated.created_at: the publication time from the database clock. The BEFORE INSERT triggerpolicy_versions_stamp_creationsets it toclock_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 tocreated_at; a scheduled time must not be earlier (policy_versions_effective_after_creation, mapped tooutbound.ErrPolicyVersionBackdated).author:system:<name>oroperator:<handle>, at most 128 bytes of lowercase letters, digits,.,_, and-. It excludes@, so it cannot hold an email address. It is text rather than a reference tousers: the seed has no account, admin roles do not exist yet, and a version must outlive any account, while a cascading or nulling foreign key would conflict with immutability. An admin editor can add an account reference in an additive migration.document: a jsonb object with the typed policy.document_sha256: the SHA-256 of the canonical document, 32 raw bytes.
The database enforces immutability. The trigger function policy_versions_refuse_change refuses every UPDATE and DELETE (row trigger) and TRUNCATE (statement trigger) with SQLSTATE 23000 and the constraint name policy_versions_immutable; the adapter maps exactly that pair to outbound.ErrPolicyVersionImmutable, never the message. The port has no update or delete method, so a change is always a new version. The guarantee covers application statements and manual SQL; a role that owns the table can still disable the trigger or drop the table, so a least-privilege runtime role remains future work.
Typed policy, domain.ProductPolicy: every value is a named field whose type carries the unit: CalendarDays, BusinessDays (no conversion to a duration; the consuming feature supplies the business calendar), Hours, and BasisPoints for probabilities and the standard error, an integer count of 0.0001 (0.80 is 8000). Basis points compare exactly, without floating-point drift, and keep integers in the document. The Validate method of each section rejects zero, missing, and out-of-range values and inconsistent combinations, such as a default deadline outside the options, a higher quota tier with a lower limit, an inactive E0, an active tier above an inactive one, or stop probabilities that do not surround the confirmation threshold. The ranges are sanity bounds against unit mistakes, not product decisions. Quota tiers E0 < E1 < E2 are looked up with OrganizationQuotaPolicy.Tier(domain.OrganizationTier) (for organization quota enforcement); every organization starts at E0, and the rules that move it between tiers belong to the quota feature.
The MVP attempt accounting decision is candidate-wide: MaxAttemptsPerWindow counts root attempts across specializations in the rolling AttemptWindow. A corrective attempt shares its root slot, and training does not consume it. Retry and promotion timers remain independent by specialization.
Legacy documents use schema_version 1 with the sections invitations, organization_quotas, assessment, identity, and search_status. Schema 2 adds independently optional assessment.attempt, assessment.training, assessment.signals, support, and matching, and requires at least one of those extensions. Encoding selects schema 1 without extensions and schema 2 otherwise. Each schema has a strict decoder: the legacy decoder rejects extension keys even when null, and an absent optional section never acquires defaults. Required fields reject missing/null values, wrong types, fractions, and values outside int32; both decoders reject unknown fields, unknown schema versions, trailing data, and documents over 64 KiB. Field names carry their unit (_days, _business_days, _hours, _seconds, _bp). The canonical form is compact Go JSON in field declaration order. domain.RestorePolicyVersion decodes, validates, re-encodes, and compares SHA-256 with document_sha256; mismatch returns domain.ErrPolicyDocumentIntegrity. The schema 1 golden bytes and hash stay unchanged. Deploy readers supporting schema 2 before publishing it; a previous binary cannot read schema 2, so publishing it prevents rollback to that binary. Stored policy documents are never rewritten for compatibility.
The port outbound.PolicyRepository is available through UnitOfWork.Policies() and outside a transaction through postgres.PolicyStore. Methods that take a family reject an unknown one before reading storage.
Createstores a numbereddomain.PolicyVersionDraftand returns the storeddomain.PolicyVersionwith the database times. The insert usesON CONFLICT DO NOTHING, so a taken number or ID returnsErrPolicyVersionConflictwithout aborting a surrounding transaction.GetByIDreads one version.GetEffective(key, at)returns the newest publication, the highest number, among the versions whoseeffective_atis not afterat. 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; the E0 companies of one holding share one pool, and E1 and above count separately (see Company quotas) |
assessment, uncalibrated initial |
same-grade retry after 30 days; at most 3 attempts per 180 days; at most one promotion per 90 days; confirmation at P_G >= 0.80, high strength from 0.90; after at least 8 scored items stop at P_G >= 0.90 or <= 0.10 or SE <= 0.25; at most 23 scored items plus 2 seed items; practice is mandatory |
identity |
verification token 24 hours; unverified account deleted 7 days after the latest registration; session idle timeout 24 hours, absolute lifetime 7 days |
search_status |
the "searching" status is confirmed every 30 days |
The identity lifetimes in this table are the values of the identity contract (api/README.en.md). They come from the versioned product policy, not from configuration: the registration, verification, and session usecases will read them from the effective policy version. The grade rules in Assessment and grade verification use the same assessment values.
Matching coefficients (matching, schema 2, domain.MatchingPolicy in policy_matching.go, demo version domain.DemoProductPolicyV4()): every field is required once the section is present, and the units are basis points except the two skill weights and the cohort size. The demo values are the design values of PRD 4.9 for checking the flow, not measured results; they are published explicitly (the isolated browser fixture publishes V4; startup still seeds V1 only), and a policy version without the section makes the search fail closed instead of ranking with defaults.
| Field | Demo value | Meaning |
|---|---|---|
fit_coverage_weight_bp, fit_domain_weight_bp, fit_semantics_weight_bp |
7500, 1500, 1000 | Fit = 0.75 * Cov + 0.15 * Dom + 0.10 * Sem; the three add up to 1 |
rank_fit_weight_bp, rank_strength_weight_bp |
5000, 5000 | S = (0.5 * Fit + 0.5 * P) * freshness * responsiveness; the two add up to 1 |
freshness_floor_bp, responsiveness_floor_bp |
9000, 9000 | the multiplier 0.9 + 0.1 * x of Fr and Rsp; a floor of zero is refused |
competition_boost_bp |
3000 | P = T + 0.3 * (1 - T) * V |
neutral_unknown_bp |
5000 | the neutral 0.5 for an unknown component (Dom, Sem, T, Fr, Rsp, and Cov of an empty request) |
near_skill_threshold_bp |
2500 | a required skill that contributes less moves a confirmed profile to the near group |
required_skill_weight, desired_skill_weight |
2, 1 | weights of the skills in Cov |
trust_stated_bp, trust_online_bp, trust_identity_bp, trust_in_person_bp |
2500, 6000, 8500, 10000 | coefficients of the evidence trust levels 0 to 3 |
attribution_personal_bp, attribution_team_role_bp, attribution_team_unattributed_bp |
10000, 8000, 5000 | personal result, team role, team result without a role |
relation_exact_bp, relation_narrower_bp, relation_broader_bp |
10000, 8000, 4000 | evidence for the same skill, a narrower one, a broader one |
percentile_min_cohort |
30 | the smallest comparable real cohort that allows a percentile; the search compares the real cohort of each returned category with it |
max_results_per_group |
10 | entries of each group that one search may return; the whole bank is ranked and only the output is cut |
skill_taxonomy |
backend over docker, go, kafka, postgresql; devops_sre over docker | the technologies inside each specialization, which decide whether evidence is broader or narrower than a requested skill |
The validation keeps each share in 0..1, the fit and rank weights at a sum of 1, the trust and relation coefficients ordered, and the floors above zero. Not in the policy yet: the competition half-life of 24 months and the embedding-only relation 0.3, because no competition data and no embeddings exist.
Seeding: at startup, after migrations and under the same condition (DATABASE_MIGRATE_ON_START is true and DATABASE_URL is set), bootstrap calls Publisher.EnsureDemoProductPolicy. It checks only whether product has any version and never decodes one, so a stored version of a newer or unknown layout cannot block startup. When the family is empty, it publishes demo version 1 effective at publication; otherwise it changes nothing and logs that the seed was skipped. Instances that start together race for version 1, and the loser skips. The log line names only the key, number, kind, and ID. A database error stops startup. The seed is not a data insert in a migration, so the schema and the policy values change independently.
Referencing a version (planned): tables that record a decision built under a policy, such as grade decisions, selection snapshots, and invitations, carry policy_version_id uuid NOT NULL REFERENCES policy_versions (id) and store the version used when the decision was made. An existing decision reads that version with GetByID and is never recomputed through GetEffective, whose answer for a given time changes when a scheduled version is superseded. A referenced version cannot be deleted, by the foreign key and by the trigger, and a new version never rewrites past decisions.
Test fixtures use their own values. Since product is the only family, the integration tests give every case its own database, and no fixture stands in for the demo policy.
Release artifacts and restoration
The local release manifest separates core image verification from product data availability. It records immutable release IDs, source and Compose file hashes, exact built image IDs, registry digests for pulled images, and bounded hashes for versioned data artifacts. Restoration checks these references and hashes before Compose starts and never resolves a moving tag again. The bundled demo policy source is version 1, but that does not establish which policy row is active in PostgreSQL. The demo seed is versioned by the hashes of its bundled source, which also holds the synthetic demo bank, and its image is pinned so the isolated demo stand can be restored from the same delivery. The assessment bank remains unavailable until an accepted snapshot exists, so product_data_status is partial. Named Compose volumes persist across a release restart, but the manifest is not a database backup or data snapshot. See DEPLOY.md for the commands and manifest schema.
Repository map and package purpose
api/core/ public browser-to-Go contract and bundle
api/ml/ internal Go-to-ML contract and bundle
backend/cmd/app/main.go calls bootstrap.Run and reports errors
backend/cmd/migrate/ local migration status, up, and down-one
backend/config/ shared runtime configuration
backend/internal/domain/ product invariants, planned modules
backend/internal/usecase/ application operations and orchestration
backend/internal/port/ inbound and outbound interfaces
backend/internal/adapter/ primary HTTP and secondary integrations
backend/internal/bootstrap/ dependency wiring and process lifecycle
backend/db/ migrations, SQL queries, and the embedded migration set
backend/codegen/ ogen server and ML-client configs, sqlc
frontend/src/ app, pages, widgets, features, entities, shared
frontend/codegen/ Orval configuration
ml/src/ FastAPI service and operational checks
ml/codegen/ Python datamodel-code-generator settings
deploy/ Compose, Nginx, and technical smoke checks
observability/ Prometheus, Loki, Alloy, Grafana provisioning
scripts/ shared documentation and schema tooling
docs/ maintained Russian and English guides
backend/
cmd/app/main.go calls bootstrap.Run and reports errors
config/ shared runtime configuration
internal/
domain/ flat package; DomainEvent, identity types, consent ledger, organizations and memberships, product policy
usecase/health/ operational readiness usecase
port/inbound/ readiness and event handler input boundaries
usecase/identity/ password validation before hashing (Credentials)
usecase/policy/ publication of policy versions and the demo policy seed
usecase/consent/ granting of consents C1-C3 and C5 and the scoped C4 with the current-text check
usecase/files/ shared private file layer: policies, opaque keys, stream limits, checksums
usecase/notification/ mail requests and the consumer that stores them as deliveries, the quota gate, the service mail enqueue (`ServiceMailer`), the senders of service mail (`ServiceMailSender`) and of product notifications (`NewNotificationSender`), and their rights checks
usecase/notification/mailtemplate/ pure rendering of versioned service emails; the delivery consumer renders notifications with it
port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, organization and membership, policy, password hashing, and mail boundaries
adapter/primary/http/
api/ generated ogen handler
middleware/ request log and request metrics by route template
observe/ request-scoped observations, such as the problem code
problem/ RFC 9457 error responses
v1/ handwritten handlers of the contract operations
router.go chi composition
adapter/secondary/
argon2id/ Argon2id password hasher with a memory budget
kafka/ franz-go event publisher and consumer group member: record envelope, its decoding, and events topic provisioning
mail/disabled/ mail transport that sends nothing and reports the channel unavailable
mail/resend/ mail transport that sends one request to the Resend HTTP API per message
mail/resend/resendfixture/ local stand-in for the Resend API, for tests only; production never imports it
ml/api/ generated client from backend/codegen/ogen-ml.yml
postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity, consent ledger, organization, membership, and policy repositories, health check
postgres/sqlc/ generated SQL adapter
redis/ cache adapter and Redis check
seaweedfs/ S3 adapter and bucket check
prometheus/ bounded Go/process, request, problem, outbox, consumer, job, delivery, quota, and answer save metrics
worker/outboxrelay/ outbox relay loop: claim, publish, mark, backoff, and shutdown
worker/eventconsumer/ event consumer runtime: dedup transaction, retries, dead letters, offset commits, and shutdown
worker/jobrunner/ scheduled job runtime: claim under a lease, run with the completion, retries, release, and shutdown
worker/mailsender/ sending loop of the mail lanes (service identity mail and product notifications): repeats passes, waits when idle, backs off on failures, reports its running gauge
worker/retry/ backoff with jitter and a context-aware wait shared by the workers
worker/deliverymetrics/ periodic read of the delivery and mail quota aggregates into the metrics
bootstrap/ configuration, wiring, lifecycle, shutdown
db/ embedded migrations and SQL queries; outbox, identity, policy, event consumer, delivery, mail quota, scheduled job, consent ledger, and organization tables
codegen/ ogen and sqlc configs
pkg/testutil/ fake application clock and identifier scan shared by tests
Domain types live directly in backend/internal/domain/: user.go, candidate.go, and other files as their models are defined. Do not nest directories by entity or feature. The first type is DomainEvent in domain_event.go, the validated event that a transaction writes to the outbox. Identity storage types live in email_address.go, secret_token.go, user.go, email_token.go, and session.go; the normalized password is in password.go. The consent ledger types live in consent.go. The organization, verification, and membership types live in organization.go and membership.go. The product policy and its versions live in policy.go, policy_document.go, policy_version.go, and policy_demo.go.
Outside the implemented flows (identity, consents, organizations, profile and questionnaire, assessment, needs and matching, invitations, support cases, notifications), usecases for documents and FSP achievements are not implemented. SMTP and FSP adapters remain planned; the product worker jobs are currently only the computation of the assessment review band and the expiry of an invitation at its response deadline. main.go starts bootstrap and handles process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the notification_delivery and notification_inbox handlers, the internal notification inbox with its list and read-state operations, the scheduled job runtime (worker/jobrunner) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for every operation protected by the API contract, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the PasswordHasher port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the MailSender port with the disabled and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
backend/pkg/ is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. pkg/testutil/ holds FakeClock, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a func() time.Time clock, and FindPersonalIdentifiers, which the metrics tests use to find email-like and UUID-like values in an exposition. A mailer package remains a candidate. Mail templates live in internal/usecase/notification/mailtemplate/: they hold product copy and use domain types such as SecretToken. It is a pure rendering package without I/O or logging. The delivery consumer in internal/usecase/notification/ renders notifications with it; ServiceMailer creates verification mail during registration and resend. Password reset mail belongs to the planned reset flow. Templates, versions, and link format are described in DEPLOY.md. Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under internal/.
api/ contains contract sources and tools; it is not a runtime hop in the request path. api/core/ and api/ml/ each own OpenAPI source, route and component fragments, and a committed bundle. Root scripts/ merges schema fragments. Generated Go output belongs to its consumer: the public handler under backend/internal/adapter/primary/http/api/, the internal ML client under backend/internal/adapter/secondary/ml/api/, and sqlc output under backend/internal/adapter/secondary/postgres/sqlc/. The first is transport code mounted in chi; the latter two are outbound adapters. backend/cmd/app/main.go remains a small process entry point; bootstrap owns dependency wiring and graceful shutdown.
Target modules
| Module | Responsibility | Main data |
|---|---|---|
| identity | Email, verification, sessions, roles | users, email_tokens, sessions, external_identities |
| candidate | Profile, contacts, consent, visibility | profiles, contacts, skills, consents, resume_versions |
| company | Company and its members | organizations, organization_representatives, memberships |
| assessment | Questionnaire, tasks, attempts, scoring, grade | questionnaires, task_templates, attempts, answers, grade_history |
| matching | Needs, filters, ranking, search versions | hiring_needs, search_runs, search_items |
| invitation | Offer and contact permission | invitations, invitation_events, contact_grants |
| document | Files, resume analysis, standard PDF | files, analysis_results, document_jobs |
| achievement | FSP link and achievement provenance | fsp_links, achievements, sync_runs |
| vacancy, later | Vacancies and voluntary applications | vacancies, applications |
The MVP uses one PostgreSQL database. Keep relational links and constraints explicit. JSONB can hold versioned questionnaire answers and ML results; it does not replace the data model. Skills and specialties use normalized references. Large PDFs stay outside PostgreSQL. Candidate category combines specialty and test-verified grade. Claimed and verified grades remain separate.
An achievement records its source, external ID, event date, receipt date, and trust status. Missing FSP history, a missing link, and a temporary sync error are distinct states. ML has no direct access to the business database.
Target user flow
Candidate flow: verify email -> complete profile and consent -> answer questionnaire -> select expected grade -> take assessment -> receive a verified category -> publish profile.
Employer flow: verify email -> create company profile -> describe need -> confirm extracted skills -> choose filters -> review an explainable result set -> send a salary offer -> candidate accepts -> only that company can access contacts.
An invitation includes the employer, description, contact channel, both salary bounds, and RUB currency. Both salary values are required whole rubles in multiples of 1000 and must satisfy 0 < salary_from < salary_to, with a width (salary_to - salary_from) / ((salary_from + salary_to) / 2) from 10% to 40% inclusive (PRD FR13); the same rule applies to the salary range of a need. Show the pay period and tax basis (net or gross). vacancy_id is optional. Main transitions are draft -> delivered -> viewed -> accepted or declined; the internal sending step is never visible, a send answers with delivered, and direct acceptance from delivered is allowed. The candidate records viewed with an explicit view command; reading an invitation has no side effect. withdrawn (by the organization), expired (a server deadline), and cancelled_by_candidate are terminal states. Retries are idempotent, and transactions protect concurrent state changes. The draft part of this flow is implemented; see Invitation drafts.
A contact grant belongs to one candidate-company pair and is created after an accepted invitation or a candidate's own application. The server checks the user, company membership, grant, and current visibility on each read. Before a grant, employers receive no contacts, original PDF, messaging links, or contact fragments from resumes or ML.
The owner profile, search card, and authorized contacts use separate DTOs. The candidate can receive a complete PDF. A company export is built from its allowed view after another access check. A permanent public file URL does not replace authorized delivery. Revoked consent removes the profile from new and saved search results; it cannot retrieve information another party already received.
Assessment and grade verification
Assessments use reviewed task families and a blueprint for each specialty and grade. The blueprint records competencies, difficulty, task count, and weights. Variants change the prompt and input while keeping the assessed skill; shuffling answer choices is insufficient. Go backend and React frontend at junior/middle level are the initial demo scope. Other specialties need a real task bank.
Fix the seed, version, and conditions before an attempt. Keep answers and keys on the server. Prefer automatically scored formats that do not execute candidate code in the MVP. Free-form answers can be an additional signal; LLM scoring is never the sole basis for a grade. Team pilots set thresholds, and a high average must not hide a critical-section failure.
Grade state rules:
- Before the first passing assessment, status is unverified and a claimed grade does not grant verified category access.
- A failed attempt never lowers an existing verified grade.
- After an initial failure, the candidate may choose a lower-level test; the system does not assign it automatically.
- A promotion after a successful qualification is allowed at most once per 90 days.
- The first lower-level test after failure is outside that interval. A retry of the same grade waits 30 days, and a candidate takes at most 3 attempts in any 180 days.
- A strong result may suggest a higher-level test. Keep the grade history available.
These intervals are the accepted initial policy, stored as demo version 1 of the product policy; its thresholds are uncalibrated and are not a validated psychometric model. Task rotation and attempt limits reduce the value of leaked answers but do not prove resistance to hints or LLMs. Difficulty comparability needs measurement.
Assessment bank
Implemented as storage and a loader, not as a candidate-facing feature: migration backend/db/migrations/00011_create_assessment_bank.sql, queries in backend/db/queries/assessment_bank.sql, the domain types in backend/internal/domain/ (assessment_family.go, assessment_generator.go, assessment_algorithms.go), the outbound.AssessmentBankRepository port (port/outbound/assessment_bank.go, reachable through UnitOfWork.AssessmentBank()), the sqlc-backed adapter in backend/internal/adapter/secondary/postgres/assessment_bank.go, and the loader in backend/internal/usecase/assessment/ (Bank, Bundle). Bootstrap creates assessment.NewBank once (bootstrap/catalog.go, with its own small PostgreSQL pool) and hands it to CatalogHandler; HTTP uses only the read Bank.SpecializationAvailability for the public specialization catalog (GET /api/v1/specializations). HTTP does not call the loader operations (ImportBundle, PublishFamily, RetireFamily, OpenCategory): the demonstration seed command (adapter/primary/cli/demoseed, usecase/demoseed) and cmd/questionnaire-fixture call them, so no category is open in a build without the seed. Assessment attempts run through a separate AttemptService that reads the bank through the UnitOfWork.AssessmentBank() repository, not through Bank.
- Family version. One
assessment_familiesrow is one version of one family (family_key,version): category, specialization (the domain inside the category), title, author (ai:<name>oroperator:<handle>), reviewer (operator:<handle>or NULL),review_status(pending,approved,rejected), the seed generator, the answer key, the rubric, a content hash with itshash_scheme, a lifecycle (draft,published,retired), and the operators and times of publication and retirement. The reviewer is never the author, and a review is pending exactly while there is no reviewer (CHECK constraints; the domain applies the same rules). The reviewer in a bundle and the operator of a publication are declared values, not authenticated identities, until reviewer and operator accounts exist. - Immutability. The content of a stored version never changes: the trigger
assessment_families_guard_updaterefuses every UPDATE that changes a column other than the lifecycle columns (lifecycle,published_at,published_by,retired_at,retired_by), andassessment_families_refuse_removalrefuses DELETE and TRUNCATE, all with SQLSTATE 23000 and the constraint nameassessment_families_immutable, which the adapter maps tooutbound.ErrAssessmentFamilyImmutable. The lifecycle moves only forward (draft, published, retired), the trigger sets the times and keeps the publisher through a retirement, and a version is published only with an approved review by a reviewer (assessment_families_published_requires_review). A change is a new version with the next number; the loader accepts only version 1 for a new family and the successor of the latest version otherwise. A pending draft is never approved in place: its review is recorded by importing a new version of the family that carries the review, and the pending version stays an unpublished draft. The domain recomputes the content hash when it reads a row and returnsErrAssessmentFamilyIntegrityfor a row changed outside the application. The hash is the SHA-256 of a canonical JSON document that holds the content without the bundle name, ID, lifecycle, and publication fields. Thehash_schemecolumn (a smallint with a CHECK of the known values, one of the immutable columns) names the layout: the domain verifies a row with the hash function of the scheme the row was stored with, so a later scheme (a new function and a new CHECK value, never an edit of scheme 1) verifies new rows without invalidating old ones, and a row with an unknown scheme is refused; tests verify a row with its own scheme and pin the scheme 1 hash of a fixed input. As forpolicy_versions, a role that owns the table can still disable the triggers. - One published version per family. A partial unique index (
assessment_families_one_published_key) allows at most one published version of a key.Bank.PublishFamilyretires the published older version in the same transaction and refuses withnewer_version_publishedwhen a newer version of the key exists in any state, a draft or a retired one included, so superseded content is never put back in the bank (earlier content is published again by importing it as a new version);Bank.ActiveFamilyreads the single published version. Coverage counts each family once. - Seed generator and variants. A generator names a registered algorithm with a versioned name (
rate_limit_window.v1,dedup_window.v1,lru_hits.v1,dependency_order.v1), the ranges of its parameters, and a statement template. A seed selects a variant: the same version and seed always give the same statement and reference answer (the pseudo-random source is SplitMix64 written out in the domain, so variants stay reproducible across Go releases; golden tests pin one statement and answer per algorithm), and the rubric is a property of the family, so no seed changes it. The reference answer comes from the algorithm's solver, which has unit tests with hand-computed cases. The registry only grows: a changed algorithm gets a new name, because stored versions refer to the old one. - Statement templates. A template is plain text with
{{.name}}placeholders and nothing else: the text/template parser reads it without functions, and a whitelist walk refuses every node except text and a single field action (sodefine,template,block,range,with,if, variables, pipelines, and calls such asprintfare refused). The loader renders the placeholders itself, never runs the template engine, and caps the template at 2000 bytes and the rendered statement at 8 KiB. Every placeholder must belong to the algorithm, and the template must contain the placeholders the answer depends on (the input data and the answer-relevant parameters), so a statement always shows the input. A bundle is validated fully at import, with probe renders at the lowest parameter values and, for eight seeds each, at the highest values (the largest inputs) and at drawn values, so a template close to the size cap cannot pass on one lucky seed; reading a stored row does not repeat the probes, because the content hash proves the content is the one that passed them. Titles, templates, and rubric texts refuse control characters, Unicode format characters (for example bidirectional overrides), and the line and paragraph separators U+2028 and U+2029; the title CHECK constraint also refuses the common ones. - Rubric. A rubric holds a principle and a list of criteria. It has no points, weights, or pass mark; how criteria become a grade is not decided in the bank.
- Lifecycle and the loader.
Bank.ImportBundlestores every family of a bundle as a draft in one transaction and never publishes, whatever the review says; importing the same bundle again, also concurrently, reports the versions as unchanged.Bank.PublishFamilyandBank.RetireFamilytake the operator, and refuse with a reason (reviewer_missing,review_not_approved,not_draft,not_published,newer_version_published); the refusal is a*domain.AssessmentRefusalErrorthat carries the reason, and the sentinels of a race that the database decided (a lifecycle step that lost to another, a missing approved review, insufficient coverage) become the same refusals. Publishing, retiring, and opening take a transaction-scoped advisory lock of the category first, so they run one after another per category;LockCategoryworks only inside a transaction (the repository of a unit of work takes it, the standalone store returnsErrAssessmentLockOutsideTransaction). - Category availability.
Bank.OpenCategoryrecords an opening inassessment_category_openingsunder a referenced policy version (policy_versions.id); it refuses withgrading_policy_missingfor a missing or unknown reference and withgrading_policy_not_currentunless the version is the one of theproductfamily in force now, judged against the database clock of the same transaction (clock_timestamp()), the clock that stamps the effective time of a policy version, so the bank defines no thresholds of its own and no application clock enters the decision. The number of distinct published families that a category needs is read from that policy:RequiredPublishedAssessmentFamiliesreturnsassessment.stop_rule.max_scored_itemsplusassessment.stop_rule.seed_items. The owner accepted this rule as a product decision on 2026-10-06. The reason: one family gives at most one item to an attempt, so a full adaptive attempt, which can run to the maximum of scored items and also carries the seed items, cannot run out of families. The insert trigger derives the same number from the stored policy document itself (the same two JSON paths; an integration test keeps the SQL and the domain equal) and checks both values as plain non-negative integers of at most four digits before the cast, so a malformed document written around the application raises theassessment_category_openings_policy_thresholdsrefusal instead of a cast error. The trigger also counts the published families, and the CHECK constraint refuses the row when they are fewer, so a call written around the usecase cannot open a category with a lower requirement. The opening stores the policy version, the operator (operator:<handle>), and the required and counted families, and is never edited. Availability is live:Bank.CategoryAvailabilityreturns the current opening only while the published families counted now still reach the opening's requirement, and otherwise refuses withcoverage_insufficient(orErrAssessmentCategoryNotOpenwithout an opening), so a retirement can close a category. It also refuses withgrading_policy_not_currentwhen the opening's policy version is no longer the one in force, so a policy change requires a new opening. The table checks the policy reference in the trigger instead of a foreign key, because PostgreSQL refuses TRUNCATE of a referenced table before thepolicy_versionstrigger can refuse it with its own error.ListFamiliespages by (key, version) cursor with a hard limit of 200. - Demo bundle.
backend/testdata/assessment/backend_demo_bundle.jsonholds four original practice problems for the categorybackend. They are an AI-generated draft (authorai:claude-draft) with a pending review and no reviewer, so the loader imports them as drafts, publication is refused, and the category stays closed. No human has reviewed the statements, solutions, rubrics, or difficulty; the bundle makes no validity or calibration claim. A real review produces a new version of the families that carries the approval. - Not implemented: authorship and review of a real task bank, blueprints per specialty and grade, an HTTP or admin interface of the loader and authenticated reviewer and operator identities (the storage of attempts, answers, and grading exist as separate assessment operations, not as part of the loader).
Assessment signals and the review band
Implemented as server-side signals of a real attempt (root or corrective), a review band computed by a scheduled job under the policy version pinned to the attempt, and an operator-only reader. The band is a hint for a manual check by a person. It does not change the result, the category, or a quota; no candidate or employer operation carries it, and the public contract has no field for it (a test walks every operation, request, response, and header to check this). Until staff roles exist, the only reader is the local command assessment-review, which records each read (DEPLOY.md). Browser signals are described separately by the signal receipt contract; this section covers what the server observes itself.
Code: migration backend/db/migrations/00033_create_assessment_signal_review.sql, queries backend/db/queries/assessment_signal_review.sql, the policy section and band rules in backend/internal/domain/ (assessment_signal_policy.go, assessment_signal_review.go), the observer, the review job, and ReviewOperator in backend/internal/usecase/assessment/signal_review.go, the repository in backend/internal/adapter/secondary/postgres/assessment_signal_review.go, and the command in backend/cmd/assessment-review/.
- Facts.
assessment_answer_observationshas one row per accepted answer: the family, the seed, the answer format, the server time from the last activity of the attempt (the previous answer or the start of the current work session) to the accepted answer, whether that time starts at the previous answer, and a keyed answer fingerprint.assessment_attempt_origin_markshas a row when the login session or the client network of an accepted answer or signal batch differs from the last row (digests of both), so the list stays short however many requests arrive. The browser events of the signal receipt contract only add totals (focus loss time, clipboard events, fullscreen exits). Rows are append-only, removed only by the cascade from the attempt or the account, and written in the same transaction as the answer or the batch, which already holds the attempt row lock. Two maintained counters,assessment_answer_fingerprint_holders(answers per family version, key generation, and fingerprint) andassessment_answer_family_totals(answers per family version and key generation), are increased by a trigger in the transaction of each observation insert; they only grow, so an answer removed with an account stays counted, and they are derived caches without foreign keys. A transaction touches one row of each, always in the same order. - No answer text, keyed digests only. The new tables store no answer text; the raw answer already exists in
assessment_attempt_itemsand is untouched. Fingerprints and digests are HMAC-SHA-256 values under purpose keys derived fromIDENTITY_KEY_SECRETwith their own domain labels (Keyring.AssessmentAnswerFingerprint,AssessmentSessionDigest,AssessmentNetworkDigest); no new secret exists. Each stored value carries akey_version(now 1) and only values of one generation are compared, so a future key rotation is an explicit step. The answer fingerprint covers the family version and the canonical answer and is the same for every candidate and seed. The session and network digests also bind the attempt, so they cannot be linked between attempts. The HTTP adapter passes the session ID and the limiter key of the client address (an IPv6 address reduced to its /64) to the usecase, which hashes them; no address, session ID, token, or answer text is logged or stored. The digests live as long as the attempt (the retention period is an open question). ChangingIDENTITY_KEY_SECRETmakes old and new fingerprints incomparable. - Server signals. Response time: an answer faster than the per-format floor of the policy is fast, and within one format an answer more than the policy ratio below the median of the attempt is an anomalous deviation (only the fast side; a slow answer is not suspicious, and a format needs enough answers of its own). One answer counts once: an answer under its floor is fast and not also a deviation. The first item of a work session is measured from the session start, which only bounds when the item was shown, so it is excluded from both. Parallel sessions: requests that return to an earlier login session after another session was used (a single move to a new session is not counted). Networks: the number of distinct client networks beyond the first, so a move to another network and back counts once. Parallel sessions and extra networks are weak and correlated (a phone and a laptop produce both), so they form one group: alone it reaches attention at most, and review only together with a strong signal (fast, deviating, or duplicate answers) at attention or above. Client time only complements server time: it is never the source of a response time, and client signals can raise a normal band to attention but never to review.
- Identical answers of different candidates, compared pairwise. For one attempt the comparison looks at every other attempt separately: matched answers are equal fingerprints of the same family version and key generation, given by another candidate to a different seed variant, so an expected agreement on one seed is not a signal and a candidate never matches their own attempt. A matched answer carries -log2 of the share of answers that hold that fingerprint among the answers of the family version and key generation, read from the maintained counters (so a rotation does not skew the share), between zero and the cap of its format (
duplicate_integer_cap_bits,duplicate_sequence_cap_bits). A popular value, such as the correct answer of a variant, therefore carries little, and so does a population of a few attempts. The bits of one pair add up, the strongest pair decides, andduplicate_bits_attentionandduplicate_bits_revieware thresholds on that sum. The list of pairs is bounded and never leaves the usecase; nothing identifies the other attempt or candidate in any output, and the operator output holds counts only. - Why the demo thresholds are 48 and 64 bits, and what the figure means.
TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLowsamples 4000 seeds of each of the four demo families (the three integer families have 36 to 47 distinct answers, the dependency order about 2250), builds the distribution of shared values and their bits, and computes the probability that one pair of honest candidates who answer a 23-item attempt correctly reaches each threshold. Multiplied by 10,000 rivals (union bound), the per-attempt false flag rate is about 4e-5 for attention and 3e-9 for review, against test targets of 1e-3 and 1e-8. The model uses the distribution of reference answers: it does not model the distribution of wrong answers or correlated mistakes (candidates who make the same common error, or a shared tutorial), which can make honest coincidences more likely than computed. These are demo values pending calibration on a real bank, with four AI-drafted families. In the other direction,TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlaggedcalculates how many answers per family a copied pair needs before the demo thresholds flag it, when the pair copies every answer and nobody else holds those values: for an attempt of 13 items, attention from 26 answers per family and review from 61; for 23 items, from 9 and from 14. A stand with fewer attempts flags nothing by design. To try the feature on a small stand, publish a policy version with lower thresholds inassessment.signals(the integration tests do this with 4 and 6 bits); the demo policy is not changed for that. - Policy. The optional section
assessment.signalsof a schema 2 policy document holds every threshold (domain.AssessmentSignalPolicy); a version without it computes no band.DemoProductPolicyV3isDemoProductPolicyV2plusDemoAssessmentSignalPolicy;DemoProductPolicyV1andDemoProductPolicyV2and the startup seed are unchanged, and a stored version is never rewritten. The band uses the thresholds of the product policy version inassessment_attempts.product_policy_version_id, so a policy published later does not change an attempt in progress or a stored review;assessment_attempt_reviews.policy_version_idrecords the version, and a trigger refuses to change it. A matched attempt is re-evaluated under its own pinned version; pairs are selected with the attention level of the evaluating attempt, so across versions with different levels a pair can be missed on the side with the lower level. - When and how. The review never runs in a candidate's transaction. The first accepted answer schedules the job
assessment.signal_reviewwith the key<attempt>:deadline, due one minute after the deadline of the attempt (so an answer committed right at the deadline is in its facts), and finalization schedules<attempt>:ended, due at once; both are inserts intoscheduled_jobsin the transaction of the answer or the finalization, and repeats do nothing. The deadline job also covers an attempt that expires or is abandoned, however and whenever its state changes. A review is a point-in-time evaluation: it describes the facts committed when its job ran, and the job at the deadline runs it again for a finalized attempt, which picks up later matches. The job computes the review of its attempt and refreshes the review of every other attempt that has ended (terminal state or past its deadline) and shares answers with it at the attention level or above, at most 50 per job; a ring of more than 50 attempts that share answers is covered because each member runs its own deadline job and sees the others. An attempt that is still running is flagged by its own job when it ends and sees the other facts then. Writers are ordered by a transaction-scoped advisory lock per review: the job locks the review of every attempt it will write, in ascending attempt order, before it reads any fact, so the later of two jobs over one attempt waits and then reads what the earlier committed (no lost update, and no lock cycle). The times of a review come from the database clock inside the upsert and the update time never falls behind the stored times. Nothing else is locked: the facts are append-only and a job is scheduled after its facts are committed. A failure is retried by the runner with backoff and can never block or change a result; without the worker (JOBS_ENABLED=false) reviews wait with their jobs. The only review statement in a candidate's transaction is the insert of the job (and the two counter updates of the answer). The job logs one line with the number of reviews it wrote and its duration, and no answer, address, or candidate. Applicability bound: the share is read from the counters in constant time, but the comparison joins the answers of the attempt with the answers that hold the same values, so its cost grows with the number of holders of popular values, at most 23 items times the holders of each; it is fine for background jobs on populations of up to about 100,000 answers per family and needs sampling or a cap above that. - Limits. Browser signals can be forged or suppressed, so they are a hint only. The client measures of the attempt page (fullscreen, covering the task, blocking copy, selection, print, and paste) stop only the casual route: the task text is in the candidate's browser, so a screenshot, a second device, or an extension takes it out, and they change no score by themselves. A helper such as an LLM on another device is not visible. False positives are possible: a shared or changing network (mobile data, NAT), a reload, two tabs, copying the task text, and coinciding answers of a small answer space. The retention period of these facts, whether collecting them needs a separate consent beyond the notice, and who calibrates the thresholds are not decided.
Skill evidence
Implemented as a stored projection of the immutable assessment results, with two reads: the candidate's own list and the permitted projection of a currently visible card. The match search reads the organization projection (see Matching and explanations); no percentile reads it yet.
Code: migration backend/db/migrations/00035_create_skill_evidence.sql, queries backend/db/queries/evidence.sql, the model in backend/internal/domain/evidence.go, the port port/outbound/evidence.go (UnitOfWork.Evidence()), the adapter adapter/secondary/postgres/evidence.go, the usecase backend/internal/usecase/evidence/read.go, the handler adapter/primary/http/v1/evidence.go, and the operations ListMyEvidence and GetOrganizationCandidateEvidence (api/README.en.md).
- One event is one fact.
skill_evidence_factshas one row per source event (UNIQUE (source_type, event_id));skill_evidence_skillsholds the skills of that event as tags (primary key(fact_id, skill_code), a closed set of the nine specialization codes and the four technology codes of the card). A second tag adds a tag, never a fact, so repeated tags cannot multiply a contribution. A fact without a skill cannot be committed (a deferred constraint trigger), tags, once stored, are never rewritten or removed, and a tag joins a fact only in the transaction that created it (created_txidand the triggerskill_evidence_skills_require_new_fact), so a stored fact is never widened afterwards. - A fact keeps its source, event, result, attribution, date, visibility, and trust, and tells a claim from a measurement.
kindisclaim(trust 0, a statement that nothing confirmed separately) ormeasurement(trust 1 to 3, an observed result); a CHECK ties each kind to its levels. Only measurements are written today, so no claim is stored and the profile claims (trust 0) are not listed.source_typeisassessment_resultand the event and the result are the attempt, because a result is keyed by its attempt (result_idis a foreign key toassessment_attempt_resultswith the owner, and a cascade removes the fact with its result or account).attributionispersonal(the team values of the PRD are reserved by the CHECK). The result part is the grade that was passed, the basis (synthetic_demo), and the calibration (uncalibrated), copied from the category decision of the result: a demonstration category is shown as one. - Trust 1. An online assessment is unproctored and nothing confirms who answered, so the projection writes trust 1 (the PRD level without a reliable confirmation of the identity or authorship). A CHECK allows only 1 or 2 for this source, never the in-person level 3; 2 is reserved for a result tied to a confirmed identity, which no flow produces yet.
domain.EvidenceTrustOnlineUnconfirmedand the SQL value are kept equal by the integration test. - Which results qualify. One SQL predicate (
skill_evidence_result_qualifies) says that a result is evidence: a real result (rootorcorrective) of the basic mode, version 2, with the outcomeconfirmed, and a category decision with the statusassignedorunchanged, that is, a reviewed synthetic source. A result that passed but had no reviewed source (not_eligible, for example with the demonstration gate off) is not evidence, a failed attempt is not evidence and is never shown as a failure, and an express training run (demo_express, a version 1 result of the modedemo_express) is never evidence. A lower passing result under a higher category (unchanged) is a fact of its own: the grade was passed, and the category stays. - Why a stored projection written by the database, not a derivation on read. Decision: a trigger on
assessment_attempt_resultscallsskill_evidence_project_assessment_resultafter the insert of a result, in the transaction that finalizes the attempt, and the migration projects the results that already exist with the same function. Reasons: the atomicity with the result and the category holds without a change to the finalization code; no write path (a command, a repair, a future import) can store a qualifying result and forget its evidence, or the reverse; a fact needs state that a derivation cannot carry (the candidate's visibility, tags from other events); and every read touches only the projection, so no query of the evidence names a result, an answer, an attempt, or a review (a test reads the query files and fails on it). The cost: the rule lives in SQL as the category guards do, the projection must be rebuilt by the function if the rule changes (the function is idempotent, and an integration test truncates the projection and rebuilds it), and the facts duplicate three values of the result. A guard trigger refuses a fact whose result does not qualify or does not match the fact, even through a direct write, and the table refuses every change butvisibility. Rolling the migration back drops the projection, which is derived, and applying the migration again rebuilds it; but the rollback refuses (skill_evidence_retained) while any fact is hidden, because hiding is the candidate's decision and no result can bring it back. Known risks: a trigger failure rolls the finalization back with it, which is the intended atomicity (a result without its fact is never stored); and a real version 2 result whose specialization is outside the closed skill list would fail the backfill of the migration and the trigger, so a new specialization needs a change of the list in the same migration that admits it. - The candidate reads
GET /api/v1/me/evidence: own facts only, newest first, the hidden ones withvisibilityhidden, a cursor bound to the candidate (the cursor of the privacy lists),Cache-Control: no-store. The fact names the result that the candidate can open atGetMyAssessmentResult. - The organization reads
GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence. The evidence is a section of the card, so the read runs the checks of the card read in one transaction: verified employer, active membership, effective C2 publication, the hiding of this organization, the minimum cohort, and the card must show at least one category after the cohort rules (candidateview.Service.AuthorizeCategoriesSection, which returns the categories of the card, each with its grade). Then the statementListOrganizationVisibleEvidencerepeats the barrier: it selects fromcandidate_effective_publications, excludes the candidates that hide the organization withNOT EXISTS, requires thecategoriesfield in the published fields, and returns only visible measurements. It returns one fact for each category of the card: the earliest fact that passed exactly the confirmed grade of that category, so a lower grade or a retake adds nothing, and only the skill of the category, never the other tags. A closed or revoked publication, a hidden organization, an unknown handle, a suppressed card, and a card without categories answer one 404; a hidden fact gives an empty list, not an error. The answer is an allowlist: the skill, the passed grade, the trust level, the year of the event (observed_year), and the basis and calibration of the method (synthetic_demo,uncalibrated), which are the same for every candidate and tell the organization that the fact is a demonstration, not a validated measurement (they add no fingerprint). It has no identifier of the fact, the event, the result, or the candidate, no month or exact time, no source, and never an answer, score, item, failure, signal, or review band. What can and cannot be linked: no key joins the answer to a person, but it is not unlinkable. The skill, grade, trust, and year, together with the other values of the card, can narrow a small pool of candidates, and the minimum cohort of the card does not cover the year. The read consumes the card-view quota under the distinct-card rule and is recorded in the access history with the fieldcategories, so the candidate sees it. - Scope of the consent C2. Publishing the
categoriesfield now sends an organization the confirmed category and one supporting assessment fact for it (skill, grade, trust level, year, and the demonstration labels). The candidate sees the same section inGetMyCardPreview(evidence), which applies no organization or cohort, so an organization can receive less. The C2 consent text was written before this section existed, and whether it needs a new version for it is a decision for the owner and the lawyer; this change does not touch the consent texts. - Express and failure. Reading the evidence before and after an express run shows the same list, the database refuses a fact whose result is an express run or a failed attempt, and an express run is not in the category, hence not in the card cohort. There is no percentile or ranking cohort in this release; when they appear they must read the same predicate.
- Contract checks.
TestEvidenceOperationsFollowTheConventions,TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements,TestNoOrganizationOperationReachesRawAssessmentData, andTestEvidenceWalkReachesTheEvidenceFamily(Go) andtest_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data(Python) walk every organization operation and the candidate list through all references and fail on an assessment, signal, or review schema, or on a raw answer, score, or failure property. - Not implemented: an operation to hide or show a fact (the column and the guard exist; no HTTP operation changes it), claims from the profile as facts, facts from FSP or other sources, revocation of a source, a trust level above 1, the use of evidence in the Passport PDF, and retention. Whether the evidence should need its own card field instead of
categoriesis open.
Assessment availability and the confirmed grade
GET /api/v1/me/assessment-availability (GetMyAssessmentAvailability) only reads. The usecase backend/internal/usecase/assessment/availability.go reads the policy, the bank, the questionnaire, the attempts, the quota, and the current categories in one repeatable-read snapshot. For each questionnaire specialization, confirmed_grade and its basis confirmed_basis come from the current candidate_assessment_categories row through the ListCandidateCategories port, not from the results. The grade and its basis are therefore read together, and confirmed_basis is null exactly when no grade is confirmed. A category of a specialization that the questionnaire no longer lists does not appear in the availability, but the profile shows it.
The profile (GetMyProfile, SaveMyProfile) reads the same rows in its own transaction. confirmed_categories holds one category per specialization in catalog order, with its basis, its assignment time (confirmed_at), and the attempt_id of the attempt whose result assigned it. An empty list means that no result has confirmed a category.
A category changes only by a strict grade upgrade (the database trigger and the domain): a result with a higher pass replaces the row, a pass at an equal or lower grade leaves it as it is and the decision gets the status unchanged. A failed attempt does not change the category. The domain has no category revocation; the row leaves only through the cascade of an account deletion.
basis is the same value as the source of the category decision. Today it is always synthetic_demo: the database accepts only the demonstration source and calibration_status = uncalibrated. The candidate card and the organization search therefore show such a category as a demonstration, not as a validated measurement. The basis is required in every category object, so a category without a basis cannot look like a standard confirmation.
Matching and explanations
Implemented as a deterministic search without ML: POST /api/v1/organizations/{org_id}/matches (SearchOrganizationMatches, api/README.en.md). Code: the usecase backend/internal/usecase/matching/ (search.go the flow, filter.go the filters, score.go the integer scoring, explain.go the explanation), the card list candidateview.Service.ListVisibleCards, the policy section domain.MatchingPolicy (policy_matching.go), the skill relations domain.RelateEvidenceSkill (evidence_relation.go), the handler adapter/primary/http/v1/matches.go, and the wiring bootstrap/matches.go. There is no new table, migration, or query file: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule.
- Access before ranking. The search is one transaction. The owner role is checked under the membership lock before any card is read.
ListVisibleCardsthen runs the checks of a card read: verified employer, thenListVisibleCandidateViewSources, which selects fromcandidate_effective_publications(published and backed by an unrevoked C2) and excludes the candidates that hide the reading organization withNOT EXISTSovercandidate_hidden_organizations; then the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five. The list is therefore exactly the set of handles thatGetOrganizationCandidateCardopens at that moment: a card that the cohort rules suppress is not searched, a revoked C2, a closed publication, or a hidden organization takes effect on the next request, and nothing is cached or stored. The permitted evidence is read only through the organization-safe batch queryListOrganizationVisibleEvidenceBatch(one statement for the whole candidate set, with the barriers of the single read: the effective publication view,NOT EXISTSover the hiding, thecategoriesfield, visible measurements), and only when the request names skills. The locks are those of the card read and nothing else is locked; the writes of the search are limited to the candidates it returns. - Owner only. For the MVP milestone the active owner of the organization searches. The HTTP boundary refuses every other role (
ownerCompanyOperations), and the usecase repeats the role check under the membership lock, so a membership alone grants nothing. The full role and assignment matrix is later work and must not widen rights by one membership. - Charged like card reads. A search returns card content (the confirmed category with its strength and basis, the declared grade, the stack, the experience band, the work formats, and the explanation), so it passes through the same allowance as a card read. The whole visible bank is ranked, and then each group is cut to
max_results_per_groupof the policy version (demo value 10, so at most 30 reveals for one search, below the 50 distinct card views per day of tier E0); no total is returned. Walking the output in the ordermain,near,unconfirmed, each newly revealed candidate is reserved through the company quota port (candidateview.SearchViews.Reserve, the sameReserveCardViewas a card read: idempotent per organization and candidate inside the window, so repeating the search or opening the card afterwards does not charge twice), and the candidate's access history gets onecard_viewedentry per search with the fields actually returned (SearchViews.Record), all in the transaction of the search. When the allowance ends, the output stops at the first refusal: the entries already paid for are returned,truncatedis true, nothing is written for the rest, and there is no error.truncatedis also true when a group exceeded its limit; it carries no count. Opening a card is still the read for the full card. - One entry per candidate specialization, built from the card the organization is allowed to see. A specialization is confirmed only when the card shows its category (
categoriespublished and not generalized away); a role that the self-assessment lists as unconfirmed is an unconfirmed entry; a role marked confirmed whose category the card does not show gives no entry, because a result cannot claim a confirmation the candidate did not publish. The same handle can therefore be confirmed in Backend and unconfirmed in Networks, and a Backend confirmation never changes the Networks entry. The status of an entry follows the specialization of the request: a need with a confirmed specialization and aspecializationfilter both restrict it, and two different values leave nothing. A need without a confirmed specialization searches all of them and returns each specialization separately. - Category basis. Each confirmed category of an entry carries
basisfrom the same stored row as the card. Today it issynthetic_demo, a demonstration that is not a validated measurement. The organization interface shows it as an ordinary confirmation (standard or strong) while the basis itself stays in the API response; the field is required inMatchCategory, so a category without a basis cannot exist. - Filters, all applied before scoring.
confirmed_grade,confirmed_category, andconfirmation_status: confirmedkeep only confirmed entries; a declared grade never satisfies them.declared_gradeis a separate claim.stackrequires every named tag in the card and also counts as a required skill of the request.conditions.work_formatsneeds one common format, andconditions.salary_compatibilityneeds the same value; an unknown card value never satisfies a condition. An unconfirmed category alone hides nothing: without a confirmed filter the declared specializations are listed. - Requested skills. The skills of the Cov come from the confirmed required (weight 2) and desired (weight 1) skills of the need snapshot, with the tags of the
stackfilter as required. A code is counted once however often it is repeated. A skill without a taxonomy code has no reviewed mapping, matches nothing, and is a gap. An empty request uses the neutral Cov 0.5 instead of dividing by zero. The need is read byrequirements_version(GetVersion); a general version that only changed the title is not a requirements snapshot and answers 404, and the snapshot of an older requirements version stays searchable and unchanged. - Evidence of a skill. Each requested skill takes the best product of the trust, attribution, and relation coefficients over the permitted evidence, not their sum. The evidence is the stated stack tags of the card (trust 0, a claim) and, for a confirmed entry, the one assessment fact that supports its category (trust 1, personal). The relation is exact for the same code, broader for a specialization over a technology, and narrower the other way, by the
skill_taxonomyof the policy version (demo:backendoverdocker,go,kafka,postgresql;devops_sreoverdocker); a version without a taxonomy relates only equal codes, so the version fully determines the result. The taxonomy is a demonstration mapping, not a measured one. An online Backend result is worth 0.6 * 1.0 * 0.4 = 0.24 for a requested Go and a stated Go tag 0.25; the near threshold is 0.25, so a candidate whose only evidence for a required technology is a Backend assessment is always innearfor it, and a stated tag alone is enough to be inmain. That consequence of the PRD values is an owner question. Repeating a tag or a skill adds nothing. - Components and groups.
Covis the weighted mean of the contributions;Dom = 0.5(the anonymous card carries no domain) andSem = 0.5for every entry (no ML), both named inunknown_flags;T = 0.5with a null percentile and the flagcohort_below_30, which the search proves instead of declaring: it counts the candidates who hold each returned category from a source other than a synthetic demonstration (CountRealComparableCategories, counts only) and compares the count withpercentile_min_cohort; today the count is 0 because every stored category is a synthetic demonstration, which is never mixed with real results. A real cohort at the minimum would need the theta of its members, which the organization-safe projection does not carry, so the search never fails for it: T stays the neutral 0.5, the percentile stays null, the reason becomespercentile_not_computedinstead ofcohort_below_30, and the search logs one warning for each such category. Only the categories of the entries that passed the filters are counted;V = 0because no competition data exists, which is neither a penalty nor an unknown;Fr = Rsp = 0.5with the flagsno_freshness_historyandno_response_history. A confirmed entry with a required skill below the near threshold (0.25) is innear, otherwise inmain; an unconfirmed entry is inunconfirmedwith only Fit and Coverage, computed by a separate path that never calculates theta, T, P, a percentile, or S. The absence of FSP is not scored anywhere. - Order and rounding. Scores are integers in micro units (six decimals), the shares are basis points, and the products are exact integers, so the same data and policy give the same order on every platform.
mainandnearsort by S, then Cov (both descending), then the internal candidate identifier ascending (then the specialization code, which only separates two entries of one candidate);unconfirmedsorts by Fit, then Cov, then the identifier. The identifier never leaves the server, and the groups are not merged on one scale. - Explanation. The summary and the flags are built from the same computed contributions: per skill group
supports(every skill carried by a measurement at or above the threshold),declared_only(only stated tags),partial(a mix, or measurements below the threshold), orgap(nothing), plus the confirmed category, the declared grade, the work-format match against the need or the filter, and the salary compatibility. It uses bounded codes only, never free text, a contact, a candidate location, a salary value or minimum, a failed attempt, or a reason for withheld data. An unknown component appears only inunknown_flags. - Policy. The search reads the effective
productpolicy at the application time and itsmatchingsection. A policy without the section fails closed with an internal error (the ProblemCode enum has no code for a temporarily unavailable dependency, and none is added); the error log says that the effective product policy has no matching section and names thepolicy-publishoperator command, the backend logs a warning at startup while the section is missing, and DEPLOY.md describes the command. The response does not name the policy version, and no search is stored. - Concurrency. The reservations take the exclusive organization lock of the company quota port. A membership check before them holds only a share lock on the same row, and two searches of one organization would deadlock on the upgrade, so the search takes the organization lock first (
CompanyQuotaRepository.LockOrganization, the documented order; it is FOR NO KEY UPDATE, so readers queue behind each other but the foreign-key lock of a candidate's own hide, which holds the candidate row and then needs the organization row, is not blocked, and the reservation itself still takes FOR UPDATE in the same transaction) and the charges of one organization are serialized. A change of the visible cohort while it is being locked (ErrConcurrentVisibilityChange) repeats the whole search up to three times, and its writes roll back with the failed attempt. The card read (GetOrganizationCard) and the evidence section (AuthorizeCategoriesSection) take the same exclusive lock first, before any share lock, for the same reason: before this order two simultaneous card reads of one organization deadlocked (SQLSTATE 40P01). For an E0 company,LockOrganizationtakes the lock of its holding right after the organization row (the shared E0 pool is described in Company quotas), so the order stays the same: the organization, then the holding, and no holding is taken before its organization.TestMatchSearchOverHTTPruns concurrent card reads, evidence reads, and searches of one organization and checks for no deadlock and one quota row for each candidate. - Accepted residual risks.
truncatedis one bit about the size of the visible bank (it says that more than the limit or the allowance exists) and the response time grows with the bank, so both leak a coarse size to the owner. The bit is bounded by the group limit and no count is returned; the risk is accepted for the demonstration and is listed with the owner questions. - Checks.
internal/usecase/matchingunit tests (formulas with hand-computed values, ties and ordering, filters, explanation, the cut and the charge of the output),internal/domain/policy_matching_test.go(document round trip, strictness, validation),v1/matches_test.go(mapping and problems), and the integration testTestMatchSearchOverHTTPagainst PostgreSQL: hidden candidates and two organizations, a need and its edited requirements, repeated identical responses, Backend confirmed and Networks unconfirmed for one handle, a profile published without a grade through the real profile, consent, and publication operations and removed by a C2 revocation, a candidate alone in its cohort, no contact or identifier in the body, the charge and the access history of a search, an organization with an allowance smaller than its bank, the group limit, the batch evidence read, two concurrent searches under one allowance, the demo group limit, the policy taxonomy, the denials, and the policy without the section.
Not implemented: the percentile and a real T (they need the theta of a comparable real cohort of at least 30 people); the competition value V and the FSP data; the domain of a candidate; freshness and responsiveness histories; semantic similarity and the ML fallback flag beyond the neutral value; the stored search_run snapshots, refinement, comparison, and the shortlist; paging beyond the group limit; and the use of the grade of a need as a filter. Sending an invitation from a search result is not implemented either, so the revocation of C2 after an invitation is not checked here; the draft of an invitation resolves a handle of the search result through the same visibility barrier (see Invitation drafts).
Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent. This is the first model, not an optimized or measured ranking: the plan compares keyword search, the verified-skill baseline, and an ML variant, adds a semantic signal only after an experiment, and never treats its score as a probability of hiring success.
Store each search as a search_run with its company, original need, filters, ranking version, and parent version. Refinement creates another snapshot. search_items stores order, scores, and profile versions without contacts. An old snapshot does not preserve access: hidden or removed profiles disappear, stale ranking is marked, and retention is bounded. This is planned; the implemented search stores nothing.
ML, documents, and background jobs
Planned ML operations are resume analysis, need analysis, and, after the baseline, embeddings and limited reranking. Go sends only allowed inputs and a short candidate list. Responses are limited to known IDs and validated against schema and version. ML failure falls back to the baseline. Models cannot set categories or expose contacts.
Planned PDF flow: limit size, page count, and upload rate; validate file type and owner; save a source version; create a job in the same transaction; extract text in an isolated resource-limited environment; mask contacts; request a structured result; validate its size and versions; show proposed fields for candidate approval. A scan without a text layer reports that state and offers manual entry; OCR is a separate extension. Never log full resume text or traces.
Resume text is untrusted data, not an instruction to tools. ML does not follow arbitrary links, run commands, or verify whether employment claims are true. Each proposed field records its evidence and limitations.
A standardized PDF is required in the product even when profile entry is manual. PDFRenderer consumes structured profile data. The planned approach is controlled HTML and isolated headless Chromium with Cyrillic fonts, no external network fetches, and no user-supplied HTML.
Jobs that only need to run at a due time use the implemented runtime in Scheduled jobs. Future ML and document jobs, which a user waits for, use queued, running, succeeded, failed, and cancelled states, an attempt limit, available_at, lease/heartbeat, and a safe error code. Claims are atomic. An expired lease permits retries; operation key, document version, and lease token prevent stale workers from overwriting newer results. Computation may repeat; a business effect must not. Retries are bounded and use backoff.
Long operations return 202 and a job ID. The UI polls with a widening interval and stops after completion or page exit. The browser never calls ML directly. Routine tests do not download a model or require GPU. Model, license, inference budget, and production latency are unselected.
Identity, FSP, and privacy
The initial product plan uses email/password, email verification, and server-side PostgreSQL sessions. Browser cookies are Secure, HttpOnly, and SameSite; mutating requests use CSRF protection. Hash passwords with a suitable KDF. Tokens are random and expire; store their hashes. Require email verification before publishing a candidate or sending invitations.
Future FSP identity linking requires provider verification. A manually entered identifier or matching email is not enough to merge accounts. The brief supplies no real FSP API, so development starts with a fixture provider and a project-owned DTO. If organizers provide Keycloak/OIDC, add Authorization Code + PKCE and validate issuer, state, nonce, audience, and redirect URI. Lincodex still owns roles and contact grants.
The brief references Russian Federal Law 152-FZ. The system design calls for separate processing/publication consents, revocation, transfer controls for ML, and retention/deletion periods. Architecture documentation does not prove legal compliance. Agree on data handling before using real personal data; use synthetic profiles for the demo.
Identity storage
Identity storage is implemented in migration backend/db/migrations/00002_create_identity_tables.sql, the queries in backend/db/queries/identity.sql, the domain types, outbound ports, and the PostgreSQL adapter. The backend API implements registration, verification resend, ConfirmEmail, login, and basic current-session operations. The frontend registration and confirmation screens are implemented; see the API contract.
users: UUIDv7id;email, the delivery form (trimmed ASCII, letter case as typed, returned asAccount.email), andemail_normalized, the unique comparison key (the same address with A-Z lowercased);password_hash, an Argon2id v19 PHC string;scenarioandonboarding_stepwith a CHECK that the step belongs to the scenario; nullableemail_verified_at;registration_version;last_registered_atwith a partial index over unverified accounts for the planned 7-day cleanup; the optimisticversion;created_atandupdated_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-bytebytea, unique),purpose(email_verification; a CHECK lists allowed purposes, so password reset can be added later),user_id, theregistration_versionthe token is bound to,created_at,expires_at,consumed_at, andinvalidated_at. Migration 00014 addspending_password_hash,pending_scenario, andpending_onboarding_step, so each token carries its registration data. A CHECK allows at most one of consumed and invalidated. Migration00046_add_email_verification_codes.sqladdscode_hash(HMAC-SHA-256 of the six-digit code under a server key, NULL when the token carries no code or the code has ended),code_expires_at, andcode_failed_attempts(0 to 5). The code expiry is the earlier of the token expiry and the 30-minute code lifetime, and the application checks both on every use.sessions: a UUIDv7idthat never leaves the server,token_hash(SHA-256 of the cookie value, unique),user_id,created_at,last_seen_at, the absoluteexpires_at, andrevoked_at. No IP address or user agent is stored.- Tokens and sessions reference
userswithON DELETE CASCADE. Consent records reference it withON DELETE RESTRICTinstead; see Consent ledger. CHECK constraints repeat the domain rules as a backstop: the ASCII address and its key, the PHC format, and timestamps (verification, consumption, invalidation, and revocation) not earlier thancreated_at.
Decisions:
- Email addresses are ASCII only, because the mailer has no SMTPUTF8 support.
domain.NewEmailAddressrejects any non-ASCII character, including homoglyphs and fullwidth forms, withErrInvalidEmailAddress, which the registration handler answers with 400validation_failedwhether 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 withtranslate(), which does not depend on the collation, unlikelower(). 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 withdomain.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.
byteakeeps the digest at half the size of hex text, with an exact length CHECK and no letter-case variants.domain.SecretToken,domain.PasswordHash, anddomain.EmailAddressredact themselves infmt(every verb) andslogoutput, so printing adomain.Usershows 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.
GetCurrentSessionreturns the token after a reload: the server derives it with domain-separated HMAC-SHA-256 from the cookie token andIDENTITY_KEY_SECRET, so it needs no database storage. Comparison is constant-time; the session token itself is stored in the database only as a SHA-256 hash.
What the ports guarantee:
UserRepository.CreatereturnsErrEmailTakenfor a duplicate key.UpdateRegistrationstores the result ofdomain.User.ReRegisteronly when the storedversionmatches and the email is unverified; the same statement advancesversionandregistration_versionby one, so no caller chooses the registration version, and deletes the registration C1 of the earlier registrant (see Consent ledger).MarkEmailVerifiedapplies only to an unverified account with the given registration version. Both returnErrUserVersionConflictotherwise.EmailTokenRepository.Consumeis oneUPDATE ... RETURNINGthat 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 asErrEmailTokenNotFound,ErrEmailTokenConsumed,ErrEmailTokenInvalidated(replaced, or issued for an earlier registration version), orErrEmailTokenExpired.InvalidateActivemarks 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 onErrUserVersionConflict; the rollback also restores the token, which is then superseded. The confirmation usecase maps that outcome toverification_token_invalid. SessionRepository.FindActiveandTouchtake the idle timeout from the caller and accept only an unrevoked session before its absolute deadline and within the idle timeout.Touchcoalesces writes with a cutoff equal to the smaller of one minute and half the idle timeout, so frequent requests do not rewrite the row and even the shortest supported idle timeout can be extended; it never moveslast_seen_atback or revives an ended session.RevokeandRevokeAllForUsersetrevoked_at.DeleteUnverifiedRegisteredBeforedeletes one batch of unverified accounts, oldest first, and never waits for a lock. It locks the candidate accounts, their tokens, their sessions, their mail requests, their mail deliveries, and their consent records withFOR UPDATE SKIP LOCKEDand skips every account whose row, or any token, session, mail request, delivery, or consent row, is locked by another transaction, such as a re-registration, a resend, a confirmation, the delivery consumer, or a delivery worker; skipped accounts stay for the next run. The mail requests, deliveries, and attempts go with the account by cascade; the consent records, which restrict the delete, are deleted explicitly in the same statement.postgres.IdentityStoreruns the same repositories outside a transaction. Called with a context from aTransactorcallback, it returnsErrNestedTransactioninstead of committing on a separate connection.- Unique and foreign key violations map to
ErrEmailTaken,ErrTokenHashConflict, andErrUserNotFoundby 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
InvalidateActivebefore 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 byTransactor.WithinTransactionand the identity repositories asoutbound.ErrTransactionConflict; nothing was committed, and the usecase or job may retry the whole operation with backoff while staying idempotent.
Password hashing
Implemented and tested: registration and login use the hasher created from configuration.
domain.Passwordholds the password normalized to Unicode NFKC.domain.NewPasswordapplies the registration policy, 15 to 128 code points after normalization;domain.ParseLoginPasswordaccepts 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 withdomain.ErrInvalidPassword, naming the rule but never the value. The blocklist of common or breached passwords is a separate planned check.- The
outbound.PasswordHasherport (port/outbound/password.go) hasHash,Verify, andVerifyDummy; theadapter/secondary/argon2idadapter implements it withgolang.org/x/crypto/argon2. New hashes use Argon2id v19 with m=65536 KiB, t=3, p=4 (the second recommended option of RFC 9106, above the OWASP baseline of 19 MiB, t=2, p=1), a 16-byte salt from crypto/rand, and a 32-byte key, encoded as$argon2id$v=19$m=65536,t=3,p=4$<salt>$<key>in unpadded base64, the format thatdomain.NewPasswordHashand theusers_password_hash_formatCHECK 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) ofPASSWORD_HASH_CONCURRENCYtimes 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 passesPASSWORD_HASH_CONCURRENCY=1for 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=600MiBin Compose makes the collector reclaim it before the heap reaches about 78% of the 768 MiB container limit, and the rest is left for stacks and non-heap memory. Waiting calls queue in FIFO order, bounded only by their request context; identity HTTP limits are described in the server-side sessions section. Verifyparses 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 returnsoutbound.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), returnsoutbound.ErrPasswordHashCorruptwithout any derivation, so a crafted row cannot demand unbounded memory or time.ErrPasswordHashCorruptwrapsdomain.ErrInvalidPasswordHash, which the repository returns for a stored hash that failsdomain.NewPasswordHash. On a matchneedsRehashreports parameters, salt, or key length that differ from the current ones; login does not yet update such hashes automatically.VerifyDummyrunsVerifyagainst a hash with the current parameters, a random salt, and a random digest, and returnsErrPasswordMismatch(or the context error). Login calls it for an unknown email and an invalid stored hash, so those branches also perform a full Argon2id verification.- Login answers
invalid_credentialsfor an unknown email, a wrong password, and an invalid stored hash (errors.Is(err, domain.ErrInvalidPasswordHash), from the repository or fromVerify); for an invalid hash it also logs an error and callsVerifyDummy. A valid password for an unverified account answersemail_not_verifiedand creates no session. Verification time is not uniform: unknown emails and corrupt hashes runVerifyDummy, while stored hashes with different Argon2id parameters take different amounts of time. identity.Credentials.HashNewPasswordvalidates a new password and only then hashes it; registration calls it on every branch before looking up the email.- Errors and logs never contain the password or the hash.
domain.Password,domain.PasswordHash,domain.SecretToken, anddomain.EmailAddressredact themselves infmt,slog, and JSON output, and keep their value behind a pointer, so printing an enclosing struct, even through an unexported field, shows only an address.
Server-side sessions
Login, current-session and current-account reads, and logout are implemented in the backend. Every contract-protected operation passes through the session boundary, which resolves a verified principal from an active PostgreSQL session; consent and organization handlers implement their documented operations. Contract operations without an implemented business handler answer 501 after security and request validation. Every unsafe public identity operation (RegisterAccount, ResendEmailVerification, ConfirmEmail, and Login) requires the sole Origin value to exactly match APP_PUBLIC_URL. Protected unsafe operations also require the session-bound X-CSRF-Token. Origin is checked at the HTTP boundary and does not trust Host or forwarded headers. The CSRF value is a domain-separated HMAC-SHA-256 derived from the session token, bound to that token, and compared in constant time. GetCurrentSession returns it again after a page reload. GET /api/v1/identity/sessions/current returns the current session and account, GET /api/v1/identity/me returns the current account, and DELETE /api/v1/identity/sessions/current revokes the session. Guests and unverified sessions answer 401; a valid session with missing or wrong Origin or CSRF on a protected unsafe operation answers 403 csrf_check_failed.
The cookie is named __Host-lincodex_session and has Path=/, Secure, HttpOnly, and SameSite=Strict, with no Domain; Expires and Max-Age point to the absolute session expiry. PostgreSQL stores only the SHA-256 hash of the random cookie token, never its value; IP addresses and user agents are not stored. IDENTITY_SESSION_IDLE_TIMEOUT defaults to 24h and accepts 1m to 30d; IDENTITY_SESSION_ABSOLUTE_LIFETIME defaults to 168h and accepts 1m to 365d. The idle timeout cannot exceed the absolute lifetime; invalid values stop startup. Active requests extend the idle deadline, not the absolute deadline.
IDENTITY_KEY_SECRET must contain at least 32 bytes and stay the same across backend restarts and instances. It also derives the CSRF key with the purpose label lincodex/identity/session-csrf/v1; changing the shared secret invalidates old CSRF values but does not revoke PostgreSQL sessions, and GetCurrentSession returns the new value. After a successful password check, creation of a new session and revocation of an incoming active session commit in one transaction. A failed login does not revoke the old session. Logout clears an expired or revoked cookie; an Origin or CSRF failure neither revokes nor clears a valid session.
Consent ledger
Consent storage, registration C1, and the settings read and mutation handlers are implemented: migration backend/db/migrations/00009_create_consent_ledger.sql, the deletion-request table in 00018_create_account_deletion_requests.sql, queries in backend/db/queries/consents.sql, domain types in backend/internal/domain/consent.go, ports in backend/internal/port/outbound/consents.go, and handlers in backend/internal/adapter/primary/http/v1/consent.go (api/README.en.md). Public GET /api/v1/identity/consent-texts/c1 returns only C1; verified sessions can read C1/C2/C3/C5 text and their own history, grant supported purposes, revoke consent, and request account deletion. Registration records C1 in the account creation or re-registration transaction; confirmation checks the C1 record for the token's registration version. The C4 invitation-acceptance handler and the account-deletion worker are not implemented.
The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation of one never changes another.
consent_texts holds the published texts: purpose, version (the contract's ConsentTextVersion), the exact body, body_sha256 checked against the body by a CHECK, kind (demo for synthetic texts without a legal review, operator for texts of the actual operator), and published_at. The current text of a purpose is the latest publication not after the grant time. Texts are immutable: a trigger refuses UPDATE, DELETE, and TRUNCATE (consent_texts_immutable), and a changed text is a new version. The migration publishes demo version cN-2026-10-01 of every purpose; the operator's texts arrive as new versions in a later migration before real data are accepted (PRD 7.3). Only the C4 text contains the placeholder {organization}; ConsentText.RenderForOrganization fills it in.
consent_records is the append-only ledger. One row per grant: UUIDv7 id, subject_id, purpose, text_version, text_hash (SHA-256 of exactly the text the subject saw, 32 bytes), source (registration for C1 only, consent_settings for C1-C3 and C5, invitation_acceptance for C4 only), registration_version for registration-source C1 only, granted_at, and the one-time revocation stamp revoked_at with revocation_source (consent_settings or support_request). A C4 row also has organization_id, organization_name (the name the shown text carried, a snapshot of 1-200 characters), the canonical field_set (one to four distinct ContactFieldKind values in ascending byte order), invitation_id, and invitation_terms_version; every other purpose must leave them NULL (consent_records_c4_scope). Request metadata such as IP addresses or user agents is not stored: the PRD asks for the version, hash, time, subject, and revocation event, and the extra data would be personal data without a purpose.
Decisions:
- Text binding. A foreign key on (
purpose,text_version) refuses a version that was never published for the purpose, and a BEFORE INSERT trigger refuses a version published after the grant time (consent_records_text_published). For C1-C3 and C5 a second foreign key over a generated column requirestext_hashto equal the hash of the published text. For C4 the same trigger requirestext_hashto equal the SHA-256 of the published text withorganization_namefilled in (consent_records_c4_text_hash). The domain computes that hash itself indomain.NewContactConsentGrantfrom the publishedConsentTextand the name, so no caller supplies hash bytes and a client can invent neither a version nor a hash. The stored name is the snapshot that proves the shown text; a later rename of the organization does not change it, and the read model returns it asConsentOrganization.name. - History. The only UPDATE a trigger allows is the revocation stamp on an unrevoked row with every other column unchanged (
consent_records_immutable). A newer text version is a new row next to the older one; a grant after a revocation is a new row. The state (active,superseded,revoked) is computed by the queries, never stored: among the unrevoked rows of a subject and purpose other than C4, the row granted last (bygranted_at, then ID) isactiveand the others aresuperseded, whatever their versions. The ledger therefore accepts any published version, and the grant usecaseconsent.Servicechecks that the version is the current text before it callsGrant. A partial unique index keeps one unrevoked row per subject, purpose, and version, so a repeated or concurrent grant returns the existing record; a unique index oninvitation_idkeeps one C4 row per invitation, revoked or not, so a revoked C4 never comes back. - Revocation.
ConsentLedger.Revokestamps every unrevoked row of the purpose, superseded rows included, and for C4 only those of one organization. A repeat finds nothing and keeps the first stamp. A revocation time before the grant time of a row, from clock skew between instances, is stamped at the grant time (greatest), so theconsent_records_revocation_stampCHECK stays a backstop. C1'sPOST /api/v1/me/account-deletion-requestsstores one durable active request, revokes C1, and appends an outbox event in one transaction; repeating it returns the same request, and a later C1 grant does not cancel it. Account deletion is not synchronous. C2 revocation locks a publication only when it still references one of the records revoked in that transaction, then writes a privacy-history event atomically. The stored publication remains linked to that immutable C2 record; the read model hides its fields and reports the effective state as closed with reasonconsent_revoked, and a later C2 grant cannot reopen it. Repeating a revoke or revoking a later C2 record does not create another closure event for the old publication. C3 revocation does not block account or profile use; a separate manual-assessment request is planned but is not implemented. C4 revocation is scoped to the requested organization, and each bounded outbox intent contains organization and fields copied from the revoked records. C5 revocation makesHasCurrentConsentfail closed and writes a stop intent, but there is no external FSP adapter and no external deletion is claimed. - Retention and deletion. PRD 7.3 plans to keep consents for three years, which can outlive the account, so
subject_idreferencesuserswithON DELETE RESTRICT, and a BEFORE DELETE trigger refuses deleting a row whose subject is a confirmed account (consent_records_retained). Rows of an unconfirmed account may be deleted, because a registration that the email owner never confirmed is not evidence of anyone's consent: the unverified account cleanup deletes the rows of the accounts it removes in the same statement, andUpdateRegistrationdeletes the registration C1 of the account it re-registers (see below). TRUNCATE fires no row trigger and stays allowed for test isolation. The durable C1 request record and event are implemented, but the worker that performs account deletion and the policy for ledger retention after that deletion are not; the request does not delete an account or ledger by itself. - Re-registration. An unverified account keeps its
users.idwhen the same email registers again, so the earlier registrant's C1 would otherwise stand for the new one. TheUpdateUserRegistrationstatement deletes the C1 rows with the sourceregistrationof the account it updates, and only when the update applies. This is a binding requirement for registration: the registration usecase callsUpdateRegistrationand records the new C1 withconsent.Service.GrantAtRegistration, strictly afterUpdateRegistration, in the same transaction (see Consent usecase). - C2 and the published field set. A C2 row proves the consent to the publication text, not which fields were published. The published field set and its changes are kept with their times and the C2 record behind each in the candidate visibility history (
candidate_publicationsandcandidate_privacy_events, see Candidate visibility). Adding a field scope to C2 rows later is an additive migration and contract change. - C4 in a business transaction.
UnitOfWork.ConsentLedger().GrantContacttakes adomain.ContactConsentGrant, which onlydomain.NewContactConsentGrantbuilds and which requires the C4 text, the organization and its name, a non-empty field set, the invitation, and its terms version;domain.NewConsentGrantrefuses C4. The invitation-acceptance handler is not implemented. When it is added, it must call this port in the transaction that accepts the invitation and writes its audit event; a repeated acceptance must compare the existing scope, and an invitation whose C4 belongs to another subject must returnErrConsentInvitationTaken. - Cleanup race. The cleanup checks consent rows in its statement snapshot. A consent committed for a candidate account after that snapshot but before the account lock fails the restricting foreign key at the end of the statement (SQLSTATE 23001); the adapter reports it as
ErrTransactionConflict, nothing is deleted, and the next run sees the consent. - Scoping. Every read and revocation takes the subject, and the contract operation takes it from the session, so the read model returns only the caller's own records. Errors of the adapter keep the SQLSTATE and constraint name only, and
domain.ConsentRecord,ConsentGrant,ContactConsentGrant, andConsentRevocationshow no subject, organization, name, or fields infmtandslogoutput.
Legal check items, not decided by this storage: deleting the C1 of never-confirmed accounts against the three-year retention of consents in PRD 7.3; whether C2 is a consent to the distribution of personal data under article 10.1 of 152-FZ, which requires its own consent with the categories of data and may need a field scope on the C2 record; and the operator texts that replace the demo texts.
What the ports guarantee (outbound.ConsentRepositories, available on UnitOfWork and as postgres.ConsentStore outside a transaction):
ConsentTexts().GetandCurrentread published texts and verify the stored hash on every read.ConsentLedger().GrantandGrantContactreturn the new record withcreatedtrue or the existing one withcreatedfalse. An unknown subject returnsErrUserNotFound, an unknown versionErrConsentTextNotFound, a version published laterErrConsentTextNotPublished, and a hash that does not match the published text (for C4 with the stored name)ErrConsentTextMismatch; these come from the database and abort a surrounding transaction. A duplicate does not. A grant whose conflicting record was revoked between its two statements returnsErrTransactionConflict.Revokereturns the rows it stamped.Currentreturns the newest unrevoked C1-C3 or C5 record orErrConsentNotFound;CurrentContactreturns the unrevoked C4 records of one organization.Listpages the subject's ledger newest first, optionally by state.ConsentRevocationEffects.Applyruns in the sameUnitOfWorktransaction as the ledger revocation. It closes the current publication's effective C2 access only when that publication references one of the revoked records, appends its privacy-history event once, and writes bounded outbox intents from the exact revoked records. The contact grants of the revoked records are closed in this transaction (C4 by record, C2 for every grant of the candidate; see Contact reads and revocation); a later grant may open only a new record-bound grant, never reopen an old one. C5 readers and importers must check the current ledger and fail closed; an outbox message alone does not authorize access or prove that an external system deleted data.
Consent usecase
consent.Service in backend/internal/usecase/consent/ is wired through bootstrap and used by registration to check the text version and grant C1 in the create or re-registration transaction. It is built with consent.NewService(transactor, clock), the Transactor and application clock the other usecases receive. A nil transactor or clock panics at construction.
- Entry points fix the source.
GrantAtRegistrationrecords C1 with sourceregistration; settings grants record C1, C2, C3, or C5 with sourceconsent_settings.RevokeInSettingsInNewTransactionstamps the subject-scoped ledger rows and applies the publication/history and outbox effects in the same transaction.RequestAccountDeletionInNewTransactionstores or returns the one active durable request, revokes C1, and appends its event atomically; a later C1 grant does not cancel that request. Neither operation accepts a source or time from the client.GrantInSettingsInNewTransactionand the mutation operations retry transaction conflicts up to three attempts with a short jittered wait, ending immediately when the context is canceled. - Re-registration order. For an unverified account that registers again, call
GrantAtRegistrationstrictly afterUserRepository.UpdateRegistrationin the same transaction.UpdateRegistrationdeletes the registration C1 of the earlier registrant, and a grant that ran before it would find that record, return it withCreatedfalse, and leave the account without any C1 once it is deleted. The integration test shows both orders. - C1 registration version. Migration
00016_bind_registration_consent.sqladdsregistration_versiononly to registration-source C1; other grants must leave it NULL. It backfills old C1 rows from the current account version without using tokens. Re-registration deletes the prior registration C1, so an older grant time or multiple active registration C1 rows for one account are inconsistent and stop the migration. The partial unique indexconsent_records_registration_version_keyallows at most one unrevoked registration C1 for an account and version. The insert trigger fills the current version when an old backend omits it and rejects a mismatch from the new backend; the immutability trigger also protects the version during revocation. - Version check before the email branch.
CheckTextVersion(ctx, repositories, purpose, version)returns the current text whenversionis current and fails like a grant otherwise, without writing anything. The registration must call it with C1 and the submitted version before it branches on a new or an existing email; otherwise a stale version would be refused only for new addresses, and the difference would reveal which accounts exist. - Current text only. A grant reads
ConsentTexts().Currentat the application time and refuses any other version with*StaleConsentTextError, which matchesErrStaleConsentTextand carries the purpose, the requested version, and the current one, so a handler can map it to one problem code and show the new text. An older version, a version that is scheduled but not yet published, and a version that never existed are all stale. The ledger accepts any published version, so this check is what keeps a grant of an outdated text out. The check and the insert are not locked against a publication between them: texts are published by migrations, and a grant that named the current text when it was checked is valid. - Server time. The input has no time field. The grant uses one reading of the injected clock for the check and for the record time; a client cannot choose the time. The database still refuses a version published after that time.
- Idempotency. A repeat of the same subject, purpose, and current version returns the existing unrevoked record with
Createdfalse, keeps its first time, stores nothing, and does not abort a surrounding transaction. A grant after a revocation is a new record. A repeat that names an older version after a newer text was published is stale, not a repeat: the subject has to see the new text, and the ledger keeps its one record. - C4 only through its scope.
GrantInSettingsrefuses C4 withErrScopedConsentRequiredbefore it reads anything.GrantContact(ctx, repositories, input)is the explicitly scoped operation for the invitation acceptance: the input carries the organization and the name shown, the field set, the invitation, the invitation terms version, and the C4 text version. It checks that the C4 text is current, letsdomain.NewContactConsentGranthash the text as shown, and callsConsentLedger().GrantContactin the caller's transaction. A repeat of the same subject and invitation returns the existing record withCreatedfalse; the caller compares its scope. The text check comes first, so a repeat after a newer C4 text was published is stale; the acceptance that wants to answer such a repeat with the earlier result must find its existing record before it calls. - C3 may be withheld. The purposes are independent: no grant requires, implies, or changes another, and no implemented account or profile operation requires active C3. A subject without C3 has no C3 record, and
CurrentreturnsErrConsentNotFound; this is not an account error. A separate manual-assessment request is planned, but its endpoint is not implemented. - Revocation and deletion request.
RevokeInSettingsInNewTransactionapplies all consent effects inside the transaction that stamps the ledger; repeating an already completed revocation does not append another event. C1 deletion requests are durable and idempotent, but they do not synchronously delete the account or cancel on a later C1 grant. - Errors keep their identity: a stale version,
ErrScopedConsentRequired,ErrUserNotFound,ErrConsentTextNotFound(the purpose has no published text),ErrConsentInvitationTaken,domain.ErrInvalidConsent, anddomain.ErrInvalidConsentText.outbound.ErrTransactionConflictis the one that needs action: the ledger returns it, without aborting the transaction, when the record of a repeat was revoked between its insert and its select. A caller inside aUnitOfWorkmust return it, roll the transaction back, and retry the whole operation;GrantInSettingsInNewTransactiondoes so itself. Mapping the other errors to problem codes belongs to the handlers. - Demo texts need a release gate. The texts that the migration publishes have the kind
demo: synthetic, without a legal review. Nothing in the usecase distinguishes them from texts of the operator, so a deployment that accepts real data would record consent to a demo text. Before real data are accepted (PRD 7.3), a release gate must check that the current text of every purpose has the kindoperator; the owner is the release gate or consent revocation, and neither exists yet.
Registration, email verification, and resend
Implemented: RegisterAccount and ResendEmailVerification are served by backend/internal/usecase/identity/register.go (identity.Registration) behind the handler backend/internal/adapter/primary/http/v1/auth.go. Without DATABASE_URL both answer 501 as before. The router mounts middleware.ClientIP with TRUSTED_PROXY_CIDRS.
One transaction. A new address creates the account (scenario and the first onboarding_step of the scenario), the C1 record (GrantAtRegistration, current text version and hash, source registration), the SHA-256 hash of a one-time token bound to the registration version, the keyed digest of its six-digit code, and the verification delivery (ServiceMailer.EnqueueVerification); the sending worker sends it later through the mail transport. C4 and every other purpose are never recorded: the body accepts only C1. Re-registration of an unverified address follows the lock order of the identity repositories (invalidate tokens, then AdvanceRegistration, then the new C1). An address that is already verified changes nothing and receives nothing: the "you already have an account" notice is not implemented, because any message to a verified address needs its own template and its own limit, and silence cannot reveal the account.
Pending credentials (pre-hijack protection). Every registration, the first and each repeat, stores its password hash, scenario, and first onboarding step on its own verification token (columns pending_* of email_tokens, migration 00014). A repeat registration of an unverified address never changes the credentials, scenario, or onboarding step of the users row: UserRepository.AdvanceRegistration only advances the registration version and the registration time (and discards the earlier registration C1), and the new token carries the new pending credentials. A resend copies the pending credentials of the newest token of the registration. The password_hash, scenario, and onboarding_step of an unverified account row are not authoritative until a verification applies the clicked token's pending data: they hold the first registrant's values only because the columns are mandatory, and no code may authenticate with them or trust them (see the comment on domain.User). Invalidating a token (InvalidateActive) clears its pending_* columns, and a CHECK constraint keeps an invalidated token from holding a pending hash. A resend that finds no pending credentials for the registration issues nothing.
Email confirmation (ConfirmEmail) is implemented. It requires the password saved with that token's registration and checks it against the pending hash. In one transaction the backend checks the current registration version and its C1 record, consumes the token, verifies the address, applies the token's password hash, scenario, and onboarding step to the account, clears pending_*, and records exactly one secret-free identity.email_verified event. Any refusal leaves the account and token unchanged. Unknown, used, replaced, or superseded tokens, a wrong password, and missing pending credentials answer verification_token_invalid; an expired token answers verification_token_expired. The Origin must match exactly APP_PUBLIC_URL. Confirmation does not create a session. The frontend confirmation screen is implemented and covered by the local registration browser flow.
Confirmation by code (ConfirmEmailByCode) is implemented in backend/internal/usecase/identity/code_confirmation.go. It takes the address, the six-digit code, and the password chosen for the registration. The checks run in this order. First the rate limits: per client (IDENTITY_CLIENT_HOURLY_LIMIT) and per normalized address, which shares the login counter (IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT). Then the newest open verification token of the unverified account at that address, with the current registration version and a code. Then the password against the token's pending hash, then the keyed digest of the code (compared in constant time) and the code expiry. The password is checked on every branch with the same hashing work; with no open code a dummy hash is used, so the response time does not reveal the account. A successful check runs the same transaction as the link confirmation, so one token is consumed once: a code after the link is refused, and a link after the code is refused. Every failed check of an open code (a wrong code, a wrong password, or an expired code) adds one to code_failed_attempts in a single conditional UPDATE. The database serializes these updates, so concurrent wrong attempts never count more than five. The fifth failure invalidates the token and clears its code and pending credentials, so the link stops working too, and the user must request a new message. A resend invalidates the earlier codes together with the earlier tokens. Every refusal (an unknown address, no open code, a wrong code, an expired code, a wrong password, or an invalidated token) answers 400 verification_token_invalid with the same body, so the answer does not show which addresses have a pending registration. Success answers the same body as the link confirmation and creates no session. The verification message uses the template verification.v2; the earlier link-only template verification.v1 is no longer rendered.
Login accepts only a verified email and checks the account's stored password, never pending registration credentials. An unknown address, wrong password, and invalid stored hash receive the same invalid_credentials; unknown addresses and invalid hashes also run VerifyDummy, and an invalid stored hash is logged without the email or hash. A correct password for an unverified account answers email_not_verified and creates no session. Successful login creates a new session; if the request carried a valid session cookie, the backend revokes it and creates the new session in one transaction. Failed login does not revoke an existing session, and a malformed cookie cannot become a principal.
Order of checks in registration: validation of the whole body and the C1 text version, replay check, rate limit, password hash (on every branch, before the account is read), transaction. A validation error (400) never depends on the stored accounts and consumes no limit.
Idempotency. The key is scoped by HMAC(secret, operation | key | normalized email) and the request is fingerprinted by HMAC(secret, canonical body) (identity.Keyring, secret IDENTITY_KEY_SECRET; required; a development stand may set IDENTITY_ALLOW_EPHEMERAL_KEY=true to draw a random one per process, which loses records and counters on restart). The record lives in idempotency_records (migration 00014) for 24 hours and is written in the registration transaction, so a visible record always belongs to a committed registration. A retry with the same key and body replays the neutral 202 and consumes no limit; the same key with another body answers 422 idempotency_key_reused. A concurrent identical request waits on the row of the first and is then replayed, so this implementation never answers 409 idempotency_in_progress. Each registration purges up to 10 expired records, which keeps the table bounded without a job.
Rate limits (Redis, fixed windows, outbound.RateLimiter, redis.Cache.Take, one atomic Lua script per take). The counters are keyed by the HMAC of the normalized address and count every request whether or not an account exists, so a 429 reveals nothing about the account. Registration and every resend share the per-address counters: at least VERIFICATION_MAIL_MIN_INTERVAL (default 60 s) between two messages and at most VERIFICATION_MAIL_DAILY_LIMIT (default 5) per window of 24 hours that starts with the first. Confirmation allows five attempts per token per hour. A per-client counter, IDENTITY_CLIENT_HOURLY_LIMIT (default 30 per hour), applies to registration, confirmation, resend, and login; it is keyed by middleware.LimiterKey of ClientAddr, hashed with the secret, and is skipped when the address is unknown (a shared bucket would let one client lock out everyone). Login also uses IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT (default 10 per hour) for normalized email, whether or not an account exists. Both configurable identity limits accept values from 1 to 10000. A rejected Take does not increase its own counter; if an earlier limit check passed, its counter already records the attempt even when the next check refuses it. A refusal answers 429 rate_limited with Retry-After in whole seconds rounded up. Counters are ephemeral: a Redis restart resets them, and the mail provider quota remains the last bound. A Redis failure answers 500 and never lets the request through. Neither address nor token is logged.
Token replacement policy. Every issue of a verification token (registration, re-registration, resend) first invalidates all unused verification tokens of the account and then stores the new one, so at most one link works at a time. A resend keeps the password, the scenario, the consent record, and the registration version; only the token changes. The message of an invalidated token is cancelled by the sending worker, so only the current link is delivered. The token lifetime comes from the product policy (identity.verification_token_lifetime_hours, 24 in the demo version), not from configuration.
Targeted lockout. Because the per-address counters count every request whether or not the account exists, anyone can use up the address's 5 messages per 24 hours and so block the owner's registration and resend for up to 24 hours without knowing the address's state. This is the price of answering 429 identically for every address; it is accepted as a known limitation of the anti-enumeration design. It is bounded (the per-client limit slows one source), and visible: lincodex_identity_rate_limit_refusals_total{scope="address"} rises. A large share of scope="client" refusals instead hints at a broken proxy chain (every client resolved to the proxy address); alert on the ratio of client to address refusals and check TRUSTED_PROXY_CIDRS. The label has two fixed values and never holds an address. No alerting rule is shipped yet.
Without a resolved client address (the ClientIP middleware did not run) the per-client limit is skipped and only the per-address limits apply: a shared "unknown" bucket would let one client lock out everyone, the worse failure. IDENTITY_KEY_SECRET is required; IDENTITY_ALLOW_EPHEMERAL_KEY=true lets a development stand draw a random one. The limiter keys carry a Redis hash tag ({key}), so the multi-key script is cluster safe.
Known limits. A resend for an unknown or verified address skips the token and message work, so its time differs from an unverified account by a few database statements; registration hides the difference behind the password hash. The password blocklist of the contract is not implemented yet; only the length rules of domain.NewPassword apply.
Organizations and memberships
Organization creation, reads, and owner edits are implemented in backend/internal/usecase/organization/, backend/internal/adapter/primary/http/v1/organization.go, and backend/internal/bootstrap/organization.go. Storage and membership ports remain in backend/internal/port/outbound/organizations.go and the PostgreSQL adapter. Migration 00019_create_organization_creation_results.sql preserves the original create result. General tenant context and the paginated directory of the current account's organizations are also implemented. See backend documentation for behavior and validation.
The middleware in backend/internal/adapter/primary/http/company_context.go checks the verified employer account and active owner membership after session, CSRF, and parameter decoding, before the business handler or its 501 fallback. All 14 organization, need, and invitation operations are classified explicitly; a contract test requires new paths with org_id to be classified. Candidate-owned company hiding and C4 revocation retain their separate authorization. Request context is not cached and never replaces authorization repeated inside a business transaction. Other roles receive 403; foreign or ended memberships receive 404. ListMyOrganizations returns only the current employer's active memberships; a company appearing in that directory does not itself grant owner authority.
Tables:
organizations: UUIDv7id(theorg_idof every organization path),name(1-200 characters, the bound of the consent snapshot),description,sphere(free text; the PRD has no taxonomy), four public contact columns (contact_website,contact_email,contact_phone,contact_telegram), the verification columnsverification_level,verification_basis, andverification_changed_at, the profileversion, and the times. Every text column has a CHECK for the same format and bounds as the contract (no surrounding whitespace, no control characters,httpswebsite without credentials).organization_representatives:organization_id,ordinal(0 to 9, so at most ten),name, andjob_title; deleted with the organization row. The list is replaced as a whole with a profile update.memberships: UUIDv7id,organization_id,user_id,role,state, and the times.UNIQUE (user_id, organization_id)allows one membership per pair in any state, andUNIQUE (organization_id, id)is the target of the composite foreign keys that later tables (the assignments of needs) use to bind a membership to its organization. Both foreign keys areON DELETE RESTRICT.holdings: UUIDv7id(internal; the API never shows it),founder_account_id, the account that created the first organization of the holding, withUNIQUEand a foreign key touserswithON DELETE RESTRICT, andcreated_at. The columnorganizations.holding_idis required, references the holding withON DELETE RESTRICT, and has an index; migration00041_create_holdings.sqlfills it from the account of the earliest membership of each organization.
Decisions:
- Active context. It is not a server-side session attribute. The organization is the
org_idin the path, and the server derives the right from the active membership on every request, so a removal, a suspension, or a leave closes the next read with nothing to invalidate.ListMyOrganizationsis the directory a client picks from; remembering the last choice is a browser convenience. The context comes only from the caller's active memberships, and a terminated membership closes reads at once. A switch clears the client's tenant queries. - Role and state in the membership only.
OrganizationRoleisowner,recruiter,hiring_manager, ortechnical_expert(PRD 2.2, Q3, and the FR07 matrix), andMembershipStateisactive,suspended,removed, orleft, each a CHECK constraint, not a PostgreSQL enum, so a later value is a constraint change in a migration. There is noinvitedstate: PRD 6.4 listsMemberInviteas its own entity, an invitation to an email address that may have no account yet, and a membership row appears when its owner accepts it.organizationshas no role, owner, or member column (an integration test reads the catalog to prove it), andOrganization,OrganizationCreate, andOrganizationUpdatehave no such field. Only the owner manages the company (OrganizationRole.CanManageOrganization); the rest of the matrix is applied by the operations it governs, and in the MVP the other roles grant nothing. - Verification level.
verification_levelise0toe3withverification_basis(confirmed_email,corporate_domain,requisites_and_authority,manual_review,partner_status), and one CHECK ties each level to its own bases. The columns are separate from the profile:UpdateOrganizationProfilenever names them,domain.NewOrganizationcannot choose a level and starts every organization ate0onconfirmed_email,Organization.ApplyProfilekeeps the verification, and the contract has no operation or request field that sets it. A test updates a profile after a process moved the level and checks that it stays. E1 to E3 are set by the verification processes that do not exist yet; the planned verification flow adds E0/E1 with evidence, a scope, and an append-only history, and it will update these columns together with its history row and must first write a history record from the current row of every existing organization (level, basis, and time as stored), so the history has no gap before its first process.OrganizationVerificationLevel.QuotaTiermapse0toe2to the quota tiers of the product policy and has none fore3, which the PRD gives a separate policy (quota enforcement reads the tier and must fail closed on ane3organization: no quota granted, the action refused, never a fallback to another tier). - Holding. The organizations of one founder account form a holding.
CreateWithOwnerstores the organization in the holding of its owner account in the same transaction, and creates the holding with the first organization of the account (INSERT ... ON CONFLICT (founder_account_id) DO NOTHING, then a read), so concurrent creations of one account end in one holding. A holding carries no profile and no right: it only defines the scope of the shared E0 quota pool (invitations and card views). The number of organizations per account is not limited; merging holdings of different owners is not modelled. The pool and lock rules are in Company quotas. - An organization has an owner. A deferred constraint trigger (
organizations_owner_required, SQLSTATE 23514) refuses at commit an organization with noownermembership in theactivestate, so creating an organization without its owner fails whichever code inserted it, andCreateWithOwnerstores the organization, its representatives, and the owner in one transaction. Removing or demoting the last owner later is a rule of the member management, not of this constraint, which would otherwise block a platform decision about an abusive organization. - Update.
UpdateProfileis one statement that applies only when the stored version equals the version the caller read, and advances it by one. The same statement requires an active membership of the actor with a manager role (the roles come fromdomain.ManagerRoles, not from SQL), so a membership that ended after the caller's read still stops the write. When the statement matches nothing, the adapter reads the membership to answerErrOrganizationNotFound(unknown organization or no active membership),ErrOrganizationManagerRequired, orErrOrganizationVersionConflict, in that order, so a stale version never tells an outsider anything. The representative list is then replaced in the same transaction under the row lock of the update. The statement locks the organization row (FOR UPDATE) and then the actor's membership rowFOR SHARE, so a revocation that commits while the statement waits for the membership lock is re-evaluated and stops the write (an integration test holds a revocation open, queues the update behind it, and commits it). The lock order of every writer is organizations, then memberships: the member management, which changes a membership and the organization together, and the tenant repository must take the locks in that order, or two transactions can deadlock. - Foreign keys and deletion.
membershipsrestricts the deletion of an organization and of an account, so an account with memberships cannot be deleted until a procedure ends them, in the same way as the consent ledger restricts the account. The application never deletes an organization. The consent ledger does not referenceorganizationsyet:consent_records.organization_idis still a plain column with the snapshot name beside it. Adding the foreign key now would force the consent ledger tests to create real organizations, and theinvitation_idkey needs real invitations; both arrive with the acceptance of an invitation, the first writer of C4 rows that name a real invitation. The invitation tables (migration 00037) and the needs reference organizations, accounts, and policy versions withON DELETE RESTRICT, so an organization with needs or invitations stays undeletable, which is the intended protection of consent evidence (PRD 7.3). - Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees:
OrganizationRepresentativehides its fields behind a pointer and redacts itself infmtandslogoutput,Organizationlogs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself.StoredRepresentative,OrganizationRepresentativeInput,OrganizationProfileInput, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store ofCreateOrganizationkeeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and remove it through bounded opportunistic cleanup after the replay window; physical deletion may happen later when create traffic resumes; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and itsrepresentativesmay be absent. The open questions (the publication of representative names, a sphere taxonomy) and the owner's decision on the number of organizations per account (no limit; the E0 quotas of a holding are shared) are in api/README.en.md.
What the ports guarantee (outbound.OrganizationRepositories, available on UnitOfWork only, because a write needs the transaction):
Organizations().CreateWithOwnerstores the organization and its owner membership and validates that the owner is the active owner membership of that organization. The organization joins the holding of the owner account, and the holding is created in the same transaction when none exists yet. An unknown account returnsErrUserNotFoundand aborts the surrounding transaction.GetForMemberreads the organization, its representatives (aggregated as JSON in the same statement), and the caller's active membership from one snapshot, and returns them orErrOrganizationNotFoundfor an unknown organization, an account without a membership, and asuspended,removed, orleftmember alike.ListForUserpages the active organizations of one account, newest membership first, with the organization identifier as the tie-breaker.UpdateProfileis described above.Memberships().InsertreturnsErrMembershipExistsfor a repeated pair in any state,ErrOrganizationNotFoundfor an unknown organization, andErrUserNotFoundfor an unknown account;Getreturns the membership in any state orErrMembershipNotFound, and the caller checksGrantsAccess. There is no method that changes a role or a state yet.
Candidate profile
Own GetMyProfile and SaveMyProfile operations are implemented through backend/internal/usecase/profile/, the transactional CandidateProfileRepository port, backend/internal/adapter/secondary/postgres/candidate.go, and backend/internal/adapter/primary/http/v1/profile.go. The use case rechecks the verified candidate account inside the transaction; the owner identifier comes only from the server session. Without DATABASE_URL, the operations retain their 501 fallback. Schemas and full-replacement rules live in api/core/components/schemas/candidate_schemas.yml and api/core/routes/candidate_profile.yml. No ML service, resume file, or FSP account is required.
Migration 00020_create_candidate_profile_history.sql adds overlapping-period confirmations and version history. experience_overlaps lists intersections of inclusive calendar months. An explicit confirmation binds two indices to their exact dates in the current request and its expected_version; an earlier confirmation carries forward only for the same indices and dates. Editing an employer or description alone does not invalidate the confirmed periods. A stored unconfirmed overlap permits only an exact no-op; a changed profile requires confirmation or corrected dates.
The changed version, complete claim set, period confirmations, and private history snapshot commit in one transaction. Each snapshot is bounded to 256 KiB; a trigger refuses history UPDATE, and deleting the profile cascades to its history. There is no automatic retention expiry. A no-op creates no history. A successful save, including a no-op, advances only candidate_profile to candidate_questionnaire, leaving later steps unchanged. Confirmed categories are read in the same transaction as the profile (GetMyProfile, SaveMyProfile): one per specialization in catalog order, from candidate_assessment_categories. The profile form never writes them.
Tables:
candidate_profiles:user_id(the primary key and a foreign key touserswithON DELETE CASCADE),version(positive; the first save creates version 1, and the contract's version 0 is the absence of a row), and times. The profile is personal data of the account and goes with it; retention rules are an open legal question.candidate_profile_claims: one row per stored claim - a single field (full_name,contact_email,contact_phone,contact_telegram,terms_location,terms_relocation,terms_salary_minimumatordinal0) or a list item (stackup to 30,roleup to 9,experienceup to 20,soft_skillup to 10, by position). Columns:valuejsonb,status(confirmedorextracted),origin(manual,extracted_from_resume,imported),trust_level,quote,extraction_version, andconfirmed_at. A field without a value has no row, so the contract'sunknownis the absence of a row. The foreign key points atcandidate_profileswithON DELETE CASCADE.
Decisions:
- Claims, not columns. Every value has a status, a source, and a confirmation time, so one claims table replaces fifty columns; jsonb holds the shape of the value (a string, a boolean, or an object), and each kind has its own CHECK for the format and bounds of the contract (E.164 for the phone, the
@of a Telegram name, a multiple of 1000 for the salary,YYYY-MMand the order of the period for experience, the known specialization and grade codes). The domain validates a value in full before it is written, andRestoreCandidateProfileContentapplies the same rules on read, so a row changed outside the application is rejected. - Trust level 0 in the schema.
trust_levelis stored in a column withCHECK (trust_level = 0), and the insert statement supplies 0 itself and takes no level from the caller. A confirmed value requiresconfirmed_at, an unconfirmed suggestion does not and is always an import (extraction_versionis not NULL); a manual value is always confirmed and carries no quote. Raising trust is a property of evidence, which is not stored here. - No confirmed category. The tables have no column for a confirmed grade or a category, and the value of a role admits only the keys
specializationandself_assessed_grade, so neither a form nor an import can write a confirmed category; it is read from thecandidate_assessment_categoriesrows, which only an assessment result writes (confirmed_categories, with itsbasis). - No mandatory link to a file, ML, or FSP. The tables have no column or foreign key to a resume file, the object storage, ML, or an FSP account, and the only foreign keys point at
usersandcandidate_profiles. A profile typed by hand is complete; a future import adds its own columns or tables additively (TestCandidateProfileStoragechecks the set of columns and foreign keys). - Version.
AdvanceCandidateProfileVersionis one statement that advances the version only when the stored one equals the one the caller read; for a stale version no row returns, and the caller answers 412version_conflict. The update time isGREATEST(stored, application clock), so an instance clock that runs behind never violates the CHECKcandidate_profiles_updated_after_creation(which would be a 500). Version monotonicity is enforced by these queries only: there is no trigger, so no other code may writeversion.InsertCandidateProfilewithON CONFLICT DO NOTHINGtells a lost first save apart (concurrent first saves: one wins, the rest get a version conflict). Replacing the set of claims (delete all, insert the new ones) runs in one transaction with the version advance.domain.CandidateProfile.Replace(input, expectedVersion, at)fixes the order: a version above the current one is a conflict; body rules are 400; a decisionextractedthat depends on the stored claims, against a stale version, isErrCandidateProfileVersionConflictrather than 400; a body that changes nothing does not advance the version; any other change over a stale version is a conflict. - Consistent read.
ReadCandidateProfilereads the profile row and every claim in one statement (a LEFT JOIN), that is, from one snapshot; two separate queries could return version N with the claims of N+1 when a save commits between them. The adapter must use only this query and never replace it with two; a write reads the profile in the same transaction as the replacement, and the version condition protects against a lost edit. - Privacy. The values are personal data of the candidate:
ProfileClaim,ProfileExperience,ProfileSalaryMinimum,CandidateProfileContent, andCandidateProfilehide themselves infmtandslogoutput,CandidateProfilelogs only the account identifier and the version, domain errors name the field and the rule but never the value, and metric labels are never taken from the profile. No query selects the profile of another account: every statement is scoped byuser_id. The adapter must never log or wrappgconn.PgError.Detail(it contains the failing row with names and phones) and reports only the SQLSTATE and the constraint name, as the organizations adapter does.
Candidate visibility
Implemented as storage, domain, and the source contract: the migration backend/db/migrations/00015_create_candidate_privacy.sql (number 00014 belongs to the idempotency records of the registration task), the queries in backend/db/queries/privacy.sql, the domain types in backend/internal/domain/visibility.go, the schemas in api/core/components/schemas/privacy_schemas.yml, and nine operations of the tag privacy in api/core/routes/candidate_privacy*.yml under /api/v1/me/privacy (api/README.en.md). There is no port, adapter, or handler yet: the operations answer 401 unauthenticated while there are no sessions and 501 not_implemented after validation. The port and the adapter come with the handlers and must join UnitOfWork; the queries and the domain conversion of rows (RestorePublication, RestoreSearchStatus) are ready and covered by an integration test.
Four independent pieces of state, each with its own table and its own version. No statement of one table writes another, and the consent C2 is neither copied nor replaced:
candidate_publications: one row per candidate, created by the first explicit publication, so a new profile has no row and is closed. Columns:state(publishedorclosed),fields(a canonical array of card field codes, empty exactly when closed),consent_record_id,published_at,closed_at,version, and times. The card field codes are a closed set (categories,stack,experience,soft_skills,location,relocation); the full name, a contact, and the lowest salary have no code, and the functioncandidate_card_fields_are_canonicalwith a CHECK refuses anything else, so no row can publish them.candidate_search_statuses: one row per candidate who ever set the status.statusislookingornot_looking;lookingstoresconfirmed_at,lapses_at, andpolicy_version_id, andnot_lookingstores none of them (a CHECK ties the three together). The only foreign key isusers, and a trigger checkspolicy_version_idagainstpolicy_versions(SQLSTATE 23503, constraint namecandidate_search_statuses_policy_fkey), because a real foreign key would make PostgreSQL refuse TRUNCATE of the immutable policy table before its own trigger could answer: the table has no consent column and no reference to the ledger, and a test reads the catalog to prove it.candidate_hidden_organizations: the primary key(user_id, organization_id)makes a hiding unique per candidate and organization;organization_idreferencesorganizationswithON DELETE RESTRICT. A BEFORE INSERT trigger (candidate_hidden_organizations_enforce_limit) bounds one candidate to 1000 records, serializing the inserts of one candidate through a no-key-update lock on the account row, and fails with SQLSTATE 23514 and the constraint namecandidate_hidden_organizations_limit. The index on(organization_id, user_id)serves the organization side, which has to exclude hidden candidates without learning who hid it.candidate_privacy_events: the append-only history (a trigger refuses every UPDATE withcandidate_privacy_events_immutable, and refuses DELETE only while the account is verified, withcandidate_privacy_events_retained; TRUNCATE stays allowed for test isolation). It holds the kind, the time, the published field set and the C2 record of a publication event, and only the organization identifier for a hiding event (the candidate's read joins the current name, so the table holds no text about an organization); a CHECK fixes the shape of every kind. It never holds a profile value or a name. A trigger refuses DELETE while the account is confirmed (candidate_privacy_events_retained, the same condition asconsent_records_refuse_delete, to be extended by the retention rule and the account deletion procedure), a trigger onusersrefuses deleting a confirmed account that has history with the same constraint name (the cascade runs after the account row is gone, so the row trigger alone cannot see it), and the account reference cascades, so the unverified account cleanup removes the rows of an account it deletes. The hide and unhide records are sensitive: they say which employer a candidate avoids.
Decisions:
-
A profile is closed by default. Nothing in the account, the profile, the questionnaire, or an assessment creates a row, and the integration test saves a profile and checks that all four tables stay empty. The domain reads a missing row as version 0, closed with the reason
never_published, not looking, and hiding nobody. -
C2 stays in the consent ledger; the publication references it. Duplicating the consent state would let two tables disagree about whether a candidate agreed.
candidate_publicationstherefore holds only what the ledger deliberately does not carry (which fields and when) and a reference to the C2 record behind them. The composite foreign key(consent_record_id, user_id, consent_purpose)over the unique indexconsent_records_id_subject_purpose_key(added by this migration; the record id is already unique, so it restricts nothing) accepts only a C2 record of the same account, and a record that a publication refers to cannot be deleted. The effective state is computed:ReadCandidatePublicationjoins the revocation stamp of the record in one statement, and the card ispublishedonly while the stored state ispublishedand the record is unrevoked. A revocation of C2 closes the card at once without any write here, and a later C2 grant opens nothing: the publication stays bound to the revoked record, so the candidate publishes again explicitly and the new publication binds to the new record. The body of the publish operation carries no consent identifier; the usecase binds the account's current unrevoked C2 record in the same transaction as the write, and it MUST take it with the port method that issuesLockCurrentC2Record(SELECT ... FOR SHARE), not withConsentLedger().Current, otherwise the race with a revocation returns, and without one answers 409state_conflict. -
The search status is not a consent. It has its own table, its own version, and no reference to the ledger, and
domain.SearchStatusknows neither the publication nor the hidden organizations, so applying a status cannot change them. The integration test sets, confirms, and clears the status in a fixture and compares the raw rows of the consent ledger, the publication, and the hidden organizations before and after: they are equal. -
The lapse of
lookingcomes from the versioned policy and only narrows. The 30 days aresearch_status.searching_confirmation_interval_daysof the effectiveproductpolicy version (demo version 1: 30), so the owner changes them by publishing a new policy version, not by a constant or configuration. A confirmation fixeslapses_atand storespolicy_version_id, so a later policy change moves no stored time and every row names the policy it was made under, as the policy section requires. The lapse itself is computed (SearchStatus.Effective(now)islookingonly whilenowis beforelapses_at) and never written: no process, job, or clock skew can turn an expired status into anything more public, the stored row keeps what the candidate said, and the read model showsvaluenot_lookingwithlapsedtrue. The candidate confirms again withlooking, which replacesconfirmed_at. A reminder before the lapse is a planned notification, not part of this task. -
Versions. Each setting has its own
version(0 is the absence of a row), checked in the statement like the profile:UpdateCandidatePublicationandUpdateCandidateSearchStatuschange a row only when the stored version equals the one the caller read, and no row returns for a stale one (412version_conflict). The domain order is the contract's: a version above the current one is a conflict, an unchanged effective setting is a success even over a stale version, any other change over a stale version is a conflict, and a publication needs an active C2. Because the settings are independent, a change of one never makes another stale. -
Hidden organizations belong to the candidate and are safe against enumeration. The record is the candidate's: no organization-visible query selects it, and an organization cannot tell a hidden candidate from an unpublished one. Hiding by identifier must not become a way to ask whether an organization exists. The foreign key refuses an unknown organization (SQLSTATE 23503), and the usecase must answer that exactly like an organization the candidate cannot see: the same 404
not_foundwith the same body, without a different timing or code. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup lists (planned, an open question), so a hiding reveals nothing the candidate could not already read. Lifting a hiding is a DELETE that answers 204 for any well-formed identifier, so it reveals nothing at all, and its history event is written only when a row was deleted. The identifiers are random UUIDv7 values, and the general rate limit covers the probing that remains. -
Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke the grant with the reason
visibility_closedin the same transaction as the change (the invitation contract fixes the reason). The closing is implemented; see Contact reads and revocation. The search status never closes a grant. -
History instead of a field scope. The C2 record proves the consent to the publication text, and
candidate_privacy_eventskeeps what the consent ledger note asked for: the published field set and its changes with their times and the C2 record behind each. A revocation of C2 and a lapse are computed, not events. Whether C2 needs its own field scope as a consent under article 10.1 of 152-FZ is still a legal question (see the consent ledger). -
Privacy. The tables hold identifiers, card field codes, and times; no profile value, name, contact, or file (a test lists the columns).
Publication,SearchStatus,HiddenOrganization, andPrivacyEventlog only identifiers, versions, and kinds. No query selects another account's row: every statement is scoped byuser_id. The adapter must report only the SQLSTATE and the constraint name, as the others do. -
One structural barrier for organization-facing reads. The view
candidate_effective_publicationsis published AND backed by an unrevoked C2 record. Every read on behalf of an organization (the search, the card, the contact read) must select from this view and addNOT EXISTSovercandidate_hidden_organizationsfor the reading organization, asReadPublicationVisibleToOrganizationdoes; no row means "nothing to read" whichever reason applies, so an organization cannot tell a hidden candidate from an unpublished one. Readingcandidate_publicationsdirectly is reserved for the candidate's own settings queries, andbackend/db/privacy_queries_test.gofails when any other query indb/queriesnames the table. -
Closing over a revoked C2. A closing sent over a stored
publishedrow whose C2 was revoked is a real change: the row is normalized toclosed,publication_closedis recorded, and the contact grants are revoked withvisibility_closedlike for any closing. Only a storedclosedrow makes a closing a repeat. The C2 revocation path must itself close the stored publication and revoke the contact grants of the account in its own transaction; the computed state closes the card at once, but it does not revoke grants. -
Publish and revoke race. The publish transaction takes the current C2 with
LockCurrentC2Record(SELECT ... FOR SHARE) and writes the publication under that lock, then re-reads the effective state withReadCandidatePublicationin the same transaction to build its response. The revocation stamp is an UPDATE of the same row, so it either commits first (the lock returns no row and the publication is refused with 409) or waits until the publication commits and closes the card right after; an integration test holds the lock and proves both orders. -
Verified email. Publishing, hiding, and the history exist only for accounts with a verified email (a usecase requirement). The unverified account cleanup (
DeleteUnverifiedUsersRegisteredBefore) deletes its consent records explicitly and would meet the restricting reference of a publication to its C2 record, so that no unconfirmed account holds a publication is a usecase requirement, not a physical impossibility: the cleanup also works over an unverified account that does hold a C2, a publication, and history, and over a C2 revoked and granted again (an integration scenario verifies it, and it depends on the order in which the data-modifying statements of the cleanup apply). Hiding records and history cascade. -
Two kinds of 409
state_conflictare told apart byerrors[]:{in: body, pointer: /state, code: consent_required}for a publication without an active C2, and{in: path, pointer: /org_id, code: limit_reached}for the 1001st hidden organization. The hiding limit is enforced by the trigger under a lock on the account row; when an insertion fails with SQLSTATE 23514 andcandidate_hidden_organizations_limit, the adapter must re-read the pair before answering 409, because a concurrent PUT of the same pair at 999 records can have created it, and the idempotent answer is 200; an integration test fires eight concurrent insertions at 999 records and expects exactly one success. -
A new card field is a contract change and a migration. The codes are listed in the function
candidate_card_fields_are_canonicaland the CHECK constraints of the publication and event tables, as well as in theCardFieldenum,domain.CardField, and the card builder.
Content of the card (hard requirements for its builder):
- Only values that the candidate confirmed ever reach the card; an unconfirmed suggestion (status
extracted) and an unknown value never do, whatever the field set says. - A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped, never published.
domain.CardTextLooksLikeContactis the check the builder must apply to every free text; it errs on the side of dropping. - Quasi-identifiers (a rare combination of location, stack, and experience) and the generalization of rare features are an acceptance criterion for the card builder, not decided here (see the open question in the API README).
The anonymous card for organizations is not built here: AnonymousCardContent is the closed set of properties that a published card can hold (confirmed categories, stack, total months of experience, soft skills, location, relocation), with no name, contact, employer, salary, or identifier, and a contract test walks the references of the card and the preview and fails on any profile, contact, consent, or organization schema. The card of an organization's search result must reuse it. GetMyCardPreview and ListMyCardAccessHistory are contract-only: the preview needs the profile, the confirmed categories, and the publication read together, and the access records are written by the search and contact-read tasks, so the table for them comes with those tasks.
Invitation drafts
Implemented: the organization side of the invitation draft, that is ListOrganizationInvitations, CreateOrganizationInvitation, GetOrganizationInvitation, and UpdateOrganizationInvitation (contract). A draft is invisible to the candidate and produces no inbox entry, no event, and no quota charge; the send is described in Sending invitations. Withdrawal, the salary raise, and the cancellation still answer 501 after the common checks; the contact read is described in Contact reads and revocation; the candidate's read, view, decline, and acceptance are described in Candidate view and decline and Candidate acceptance. Code: domain/salary_range.go, domain/invitation_terms.go, domain/invitation.go, usecase/invitation/, adapter/primary/http/v1/invitation.go, the PostgreSQL adapter adapter/secondary/postgres/invitations.go with db/queries/invitations.sql, and migration 00037_create_invitations.sql.
Tables:
invitations: UUIDv7id,organization_id, the internalcandidate_id(never serialized, logged, or printed), the optional need link (need_idwithneed_requirements_version, bound by composite foreign keys to a stored version of a need of the same organization),state(all fourteen states of the contract, so the later operations need no constraint change),expiry_reason,version,terms_version,response_period_days(3, 7, or 14),policy_version_id(the product policy version that allowed the period),response_deadline_at,salary_raise_used,created_by, andcreated_at,updated_at,delivered_at,viewed_at,responded_at. CHECK constraints tie the deadline to the delivery (both set or both null), keep a draft free of delivery, view, answer, and raise, and tie the expiry reason to the state. A trigger keeps the identity columns, makes every UPDATE advanceversionby exactly one andterms_versionby at most one, and refuses to undo a raise or to move the delivery, the deadline, or the period after a delivery. A second trigger refuses DELETE. The foreign keys to organizations, accounts, and policy versions areON DELETE RESTRICT, so an account with invitations is undeletable until a deletion procedure settles them.invitation_terms_versions:(invitation_id, version), the terms as a JSONB snapshot, and the salary again in typed columns (salary_from,salary_to,salary_currency,salary_period,salary_tax_basis). Constraints repeat the money rules in integers: both bounds from 1000 to 100 000 000 rubles in steps of 1000,salary_from < salary_to,20 * (B - A) >= A + Band5 * (B - A) <= A + B(a width of 10% to 40% of the midpoint), RUB, month, andnetorgross. The snapshot must hold all twelve terms and its salary must equal the typed columns. A trigger refuses UPDATE and DELETE: a version of the terms is immutable, and a change appends the next version. The invitation points at its current version by a deferred composite foreign key, so the first version is inserted in the same transaction.invitation_events: one audit event for each committed invitation version (UNIQUE (invitation_id, version)) with the kind (draft_created,draft_updated, since migration 00038delivered, and since migration 00039viewedanddeclined, and since migration 00040accepted), the version and terms version, the actor, the parts that changed (terms,need,response_period_days), and the time. It holds no content and is append-only.invitation_creation_results: the original response of an idempotent create, bound to the generic idempotency record and removed with it. It holds the terms, the alias, and no candidate identifier.
Decisions:
- Money. Amounts are whole rubles in
bigint, as in the contract: there are no minor units and no floating-point column or comparison.domain.SalaryRange.Validateis the single implementation of the rule for needs and invitations; it checks the bounds, the step, the currency, the period, the base,A < B, and the width with the integer pair above. A violation of the order or the width is attributed tosalary_to. The database repeats the rule, so another writer cannot store a range the API would refuse. - Terms are complete from the first draft.
InvitationTerms.Validaterepeats the schema rules a stored value must also satisfy and adds the cross-field rules: a place of work for theofficeorhybridformat, a technology that is not repeated ignoring letter case, and a package in which every condition is either provided with a description or explicitly not provided. Text fields reject control characters, including NUL, which JSONB cannot store. A stored snapshot is decoded strictly and validated again on every read. - The candidate. A draft names the candidate only by the card handle.
candidateview.Service.ResolveCandidateHandleresolves it in the create transaction with the checks of a card read: the active membership, the effective C2 publication, the hiding of this organization, the locks of the visible cohort, and the minimum cohort of five. An unknown handle, a handle of another organization, a candidate who revoked C2 or hid the profile from the organization, and a card that the cohort rules suppress all fail with the same 400 at/candidate_handle. The resolution charges no card-view quota and writes no access history, because it returns an identifier to the server only and shows no card content. Responses derive the alias again with the key of the cards, so the handle of an invitation is the handle of the card; the same candidate has another alias in every organization. - Owner only. The HTTP boundary lists the operations in
ownerCompanyOperations, and the usecase repeats the check in its transaction: a verified employer account with an activeownermembership. Another role gets 403; an outsider, an unknown organization, an unknown invitation, and an invitation of another organization get the same 404. A membership alone grants nothing. - Idempotent create. The scope of
Idempotency-Keyis the operation, the key, the account, and the organization; the fingerprint is that of the canonical request body. The original 201 is stored ininvitation_creation_resultsand replayed for 24 hours, even after the draft changed or the candidate stopped being visible. A different body under the same key gives 422idempotency_key_reused. Every failure rolls the whole transaction back, so a 400 is never stored. - Update. The body replaces the fields it sets, and
termsis always replaced as a whole. The order is the one of the contract: a body that changes nothing returns the current invitation with 200 even when the version is stale, then the version (412version_conflict), then the state (409state_conflict, only a draft changes), then the rules (400 with a pointer). A change of the terms appends the next terms version; a change of the period or the need keeps it. A new period is checked against the policy in force and records its version. - Response period. The options and the default come from the
invitationssection of the effective product policy (3, 7, 14; default 7), and the draft stores the version it used. - Locks. A create and an update both take the exclusive organization lock first (
CompanyQuotaRepository.LockOrganization), like a card read and a search, and only then the share lock of the membership check, the cohort locks of a create, or the invitation row lock of an update, so commands of one organization queue instead of deadlocking on a lock upgrade, and a later command that also charges the organization, such as sending, keeps the same order. An update locks the invitation row with a statement of its own (LockInvitation) and reads it afterwards: a locking read joined to the terms table would, after waiting for a concurrent commit, pair the newterms_versionwith the terms row it fetched before the wait and find nothing. A create repeats a bounded number of times when the visible cohort changed while it was locked. - The indicator.
salary_fitis alwaysnot_available;contact_accessis derived from the grant (Contact reads and revocation). The indicator needs the candidate's minimum, and computing it before the limit of three settings a day and the seven-day withholding exist would let an organization probe the minimum by editing a draft, so neither is computed or enforced yet.
How the later operations plug in: the pair rules read the index on the organization and the candidate. The contact grant arrives with the acceptance (Candidate acceptance). The C4 columns of the consent ledger still have no foreign keys to organizations and invitations; that is a follow-up.
Not implemented: the salary limit and the withheld counter, the indicator against the candidate's minimum, the raise, the withdrawal, the candidate side beyond the list of invitations, the card of the organization for the candidate, the reading of earlier terms versions, and the handling of invitations when an account is deleted. The role and assignment matrix beyond the owner is planned.
Tests: domain/salary_range_test.go and domain/invitation_test.go (exact width at 10% and 40%, steps, caps, terms rules with pointers, versions, immutability of earlier values, redaction), usecase/invitation/service_test.go (owner policy, handle refusals, order of checks, replay, rollback, versions), adapter/primary/http/v1/invitation_test.go (mapping, no candidate field, failure statuses, cursor), and the integration tests TestOrganizationInvitationDraftsOverHTTP, TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates, TestInvitationTablesRefuseMoneyAndHistoryViolations, and TestInvitationMigrationRollbackKeepsStoredInvitations against a real PostgreSQL.
Sending invitations
Implemented: SendOrganizationInvitation and the candidate's list of invitations ListMyInvitations (contract). Code: domain/invitation_delivery.go, usecase/invitation/send.go and candidate_inbox.go, usecase/notification/invitation.go, the HTTP handler adapter/primary/http/v1/invitation.go with the cursor in invitation_cursor.go, the adapter adapter/secondary/postgres/invitation_delivery.go with db/queries/invitation_delivery.sql, the wiring in bootstrap/invitation.go, and migration 00038_send_invitations.sql.
- One transaction. A send takes the organization lock (
CompanyQuotaRepository.LockOrganization), the owner check of the membership, the Idempotency-Key, and the invitation row lock, in the order of every invitation command, and then the locks of the visible cohort. It runs the visibility barrier of the card read again, spends one invitation of the organization quota, moves the draft todeliveredwith one conditional UPDATE (state,versionplus one,delivered_at,response_deadline_at,updated_at; the terms version stays), appends the audit eventdelivered, and writes the outbox events:invitation.deliveredfor the in-platform notification andnotification.mail_requestedwith itsmail_requestsrow for the email. The internal sending step is never stored: when the answer arrives, the invitation isdelivered, it is in the candidate's list, and the charge is recorded. A failure of any step rolls everything back. - The candidate's inbox entry is the delivered invitation itself.
ListMyInvitationsreads the rows with the candidate of the session and adelivered_at, newest first by(delivered_at, id)over the partial index of migration 00037, with the current name of the sending organization; a draft has no delivery and is never listed, and listing records no view. The notification ofnotification_inbox_eventsis written by the inbox consumer from the outbox event, seconds later (Internal notifications); the invitation does not wait for it. - Deadline.
response_deadline_at = delivered_at + response_period_daysin whole days, set by the same UPDATE as the first delivery. The trigger of migration 00037 refuses to change the delivery, the deadline, or the period afterwards, and the mail path never touches the invitation, so neither an email nor its retries move the deadline. The mail request becomes a delivery when the delivery consumer handles it; sending notification email is planned. An unverified address, a stopped transport (EMAIL_PROVIDER=disabled), or a failed attempt never affects the invitation or the answer of the send. - Content. The email says only that an employer sent an invitation and links to
/candidate/invitations: it names neither the organization nor the terms and holds no contact or identifier of the candidate. The notification shows the organization and the role while the candidate has not hidden the organization. The payload ofinvitation.deliverednames the recipient and the organization, as the inbox contract requires, and stays on the internal event bus. - Visibility. A draft keeps its candidate after a C2 revocation, a hiding, or a cohort that fell below its minimum. The send derives the card handle of the stored candidate and resolves it through
candidateview.Service.ResolveCandidateHandleagain; a candidate the organization may no longer see answers 409state_conflictwithout saying which rule applied. - Quota. The charge goes through the existing company quota port (
companyquota.Service.ReserveInvitation) intocompany_invitation_quota_usage, keyed by the invitation, so it is written once. Migration 00038 adds the composite foreign key(organization_id, invitation_id)toinvitations. An exhausted quota answers 429 withRetry-After, nothing is stored, and the draft stays. The port counts the pool of one organization; the shared E0 pool of a holding is not implemented in the port yet. - Idempotency. The scope is the operation, the key, the account, and the organization; the fingerprint covers the invitation of the path and
expected_version.invitation_send_resultskeeps the outcome under the key for 24 hours together with the generic idempotency record: the original 200, a 404 of an unknown invitation, and a 409. A 400, a 412, and a 429 are not stored, so the corrected request can reuse the key. A send of an invitation that is already delivered answers 200 with its current state even with a new key or an older version and charges nothing. - Access. Owner only, as for drafts:
ownerCompanyOperationsat the HTTP boundary and the same check in the transaction; no other role may send. The candidate's list requires a verified candidate account, and an employer gets 403. - Order of checks after the boundary: the owner, the key (422 or a replay), the invitation (404), a completed send (200), the version (412), the state and the visibility (409), then the quota (429).
Not implemented: the pause after a no deal (no operation produces the no_deal state yet), the cancellation (the view, the decline, and the acceptance are in Candidate view and decline and Candidate acceptance), the sending of notification email, the shared E0 pool of a holding in the quota port, and the role and assignment matrix beyond the owner. The pending limit and the pause after a decline are in Pending limit, cooldown, and expiry.
Tests: domain/invitation_delivery_test.go, usecase/invitation/send_test.go, usecase/notification/inbox_test.go (the invitation notice), adapter/primary/http/v1/invitation_test.go (statuses, Retry-After, the candidate cursor), and the integration tests TestOrganizationInvitationSendOverHTTP (the inbox before any email, repeats with one row of each kind and one charge, a 3-day deadline with the mail stopped and its job retried, visibility, a stale version, owner only, the quota, paging) and TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage.
Candidate view and decline
Implemented: GetMyInvitation, ViewMyInvitation, and DeclineMyInvitation (contract). Code: domain/invitation_answer.go, usecase/invitation/view.go and decline.go, the HTTP handler adapter/primary/http/v1/invitation_candidate.go, the adapter adapter/secondary/postgres/invitation_answer.go with db/queries/invitation_answers.sql, and migration 00039_answer_invitations.sql.
- Read without a side effect.
GetMyInvitationreads a delivered invitation by the candidate of the session and the invitation, with the current terms and the current name of the sending organization, and it records no view. The one change a read can cause is the expiry: a read at the deadline or later first moves the invitation toexpired(Pending limit, cooldown, and expiry). The view is the explicit commandViewMyInvitation, as the contract requires, so a prefetch, a retry, or a cache refresh never changes what the organization sees. A draft, an invitation of another candidate, and an unknown identifier answer the same 404; an employer account answers 403. - View. In
deliveredbefore the deadline the command moves the invitation toviewedwith one conditional UPDATE (state,versionplus one,viewed_at,updated_at), keepsresponse_deadline_at, and appends the audit eventviewed. At the deadline or later the due expiry is applied first, and the 200 answer showsexpiredwith no view recorded; in every other state the command changes nothing and answers 200 with the invitation as it is. It takes neither a key nor a version; concurrent views queue on the row lock, and the first one wins. - Decline. Allowed from
delivered,viewed, and the plannedcounterbefore the deadline. One transaction moves the invitation to the terminaldeclined(responded_at,versionplus one), stores the reason and the optional comment ininvitation_declines, appends the audit eventdeclined, and keeps the outcome under the key. It writes no consent, no contact grant, and no outbox event. The comment follows the schema rule with the Unicode notion of white space and refuses control characters other than a line break or a tab, because PostgreSQL text cannot hold NUL (400 at/comment). - Responsiveness. The
declinedevent (kind,version, the candidate asactor_id,occurred_at) is the candidate's answer that the planned responsiveness metrics of the organization count. It is always in time, since a late decline is refused, and it is never a consent or a hire. It holds neither the reason nor the comment. - Privacy of the decline. The organization reads only
declinedandresponded_at: none of its operations readsinvitation_declines, and the audit event names no reason. The comment is never logged, notified, or copied into the stored outcome; the candidate reads both back indecline. - Order of checks after the boundary: the candidate (403), the key (422 or a replay), the invitation (404, stored), the same decline of a declined invitation (200 with a new key or an older version), another reason or comment on a declined invitation, any other terminal state, or a passed deadline (409 whatever the version, stored), the version (412, not stored), then a state without an open answer (409, stored).
invitation_decline_resultskeeps only the outcome and the invitation: a declined invitation and its decline never change, so a replay rebuilds the same answer and the comment is stored once. - Deadline. A command at the deadline or later first applies the due expiry: the invitation moves to
expiredwith the reasoninvitation_timeout, and only then are the state and the version checked. A decline at the deadline or later answers 409state_conflict, as the contract requires for a late command. The conditional UPDATEs repeat the deadline, so a command cannot cross it between the check and the write. The lock order and the expiry rules are in Pending limit, cooldown, and expiry. - Consent and grant. A decline creates neither a consent nor a grant, so
contact_consentandcontact_grantare null after it. The acceptance is described in Candidate acceptance. - Hiding. The candidate's read shows the sending organization even after the candidate hid the profile from it: the hiding keeps the organization from seeing the candidate, while the candidate must know who sent the offer to answer it. The pushed content follows the hiding instead: the inbox notice of the invitation loses its content (
ResolveInvitationNotice). - Locks. A candidate command locks the invitation row (
LockCandidateInvitation) after the candidate's own idempotency record. A decline also takes the organization lock before the row, because it changes the pause of the pair; it never takes that lock after the row. An organization command takes the organization lock first and the invitation row afterwards, so the orders never cross. A view and an acceptance do not lock the organization. - Database rules of migration 00039: the event kinds
viewedanddeclinedwithout changed fields;invitations_answer_matches_state(a delivered invitation has no view or answer, a viewed one has its view, a declined one its answer, and neither precedes the delivery); the triggerinvitations_guard_answer, which refuses to move or undo a view or an answer and to leavedeclined;invitation_declineswith the known reasons, the comment bound, a trigger that ties the row to a declined invitation answered at the same moment, and a refusal of UPDATE and DELETE; and the deferred constraint triggerinvitations_require_decline, so a declined invitation without its decline cannot commit. The down migration refuses while a view, a decline, or a stored outcome exists. - Notification. The contract has no notification kind for an answer, so the organization gets no inbox entry for a view or a decline yet; it sees the state in its invitation list. A notice of the answer is planned as a contract change.
Not implemented: the cancellation, the counter offer that would produce counter, the decline aggregates with a minimum group size, the responsiveness metrics, and a notification of the organization about an answer.
Tests: domain/invitation_answer_test.go (the view only from delivered before the deadline, the decline from delivered, viewed, and counter, the refusal of terminal and late invitations, the comment rules, the stored answer rules, redaction), usecase/invitation/answer_test.go (no side effect of a read, the deadline kept, repeats, order of checks, foreign callers, invalid comments), adapter/primary/http/v1/invitation_candidate_test.go (statuses and a response without candidate data), and the integration tests TestCandidateInvitationViewAndDeclineOverHTTP (the read and the view with the same deadline, concurrent views with one event, a decline with other and no comment without a C4 consent, the stored answer event, replays and conflicts, the comment kept from the organization and the audit, foreign candidates and employers, CSRF and Origin, the hiding, a stale version, a late command) and TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback.
Candidate acceptance
Implemented: AcceptMyInvitation (contract). Code: domain/invitation_answer.go (Accept), domain/contact_grant.go, usecase/invitation/accept.go and view.go (the candidate's view with the consent offer and the grant), usecase/consent (GrantContact, the C4 record), the HTTP handler adapter/primary/http/v1/invitation_candidate.go, the adapter adapter/secondary/postgres/invitation_accept.go with db/queries/invitation_answers.sql and db/queries/contact_grants.sql, and migration 00040_accept_invitations.sql.
- One transaction. The candidate accepts the current terms with the consent C4 from
deliveredorviewed, before the deadline, at the invitation version and the terms version that the candidate read. The transaction takes its own idempotency record, then only the invitation row (LockCandidateInvitation), and then, in order: it moves the invitation toacceptedwith one conditional UPDATE (responded_atis the answer time,versionplus one; the deadline and the terms stay), records the consent C4 in the consent ledger throughconsent.Service.GrantContact(the published text, the organization name as it was shown, the selected fields, the invitation, and its terms version), stores the contact grant of exactly those fields, and appends the audit eventaccepted, which names no field. A failure of any step rolls the whole transaction back. - Order of checks. The contract order: the candidate (403), the key (422 or a replay), the invitation (404, stored), a repeat of an accepted invitation (200), a terminal state or a passed deadline (409
state_conflict, stored), the versions (412version_conflict, not stored), any state other thandeliveredorviewed(409, stored), and the consent rules (400 at/consent_c4/text_versionfor a text that is not the published one, and at/consent_c4/fields/Nfor a kind that the profile does not hold). A kind is held when the profile has it as a confirmed claim; a suggestion that nobody confirmed is never disclosed. - Repeats. An accepted invitation whose grant has the same terms version and the same set of fields answers 200 with the same invitation, under the same key or a new one and with an older
expected_version, and records nothing. Another terms version or set of fields answers 409state_conflict, stored under the key. The outcomes under a key areaccepted,not_found, andstate_conflict; a stale version and a consent refusal are not stored. - The grant.
contact_grantsholds the organization, the candidate, the source invitation (one grant per invitation), the consent record (one per grant), the canonical field set, the terms version, the consent text version, the grant time, and the revocation stamp (revoked_atandrevocation_reason). This change never sets the stamp; the revocation is a later operation. Composite foreign keys tie the grant to its invitation of the same organization and candidate, and to its C4 record of the same subject, organization, invitation, and terms version. A trigger checks that the fields, the text version, and the grant time equal those of the record; a second trigger refuses DELETE and every change other than the one stamp. A deferred constraint trigger refuses to commit an accepted invitation without its grant. The grant holds kinds only, never contact values. - The candidate's view. While an acceptance is possible,
contact_consentholds the rendered C4 text and the kinds that the profile holds, in the order of the contract, with nothing preselected; it is null when the profile holds no confirmed kind. After the acceptance,contact_grantholds the selected kinds, the status, the terms version, the consent text version, andreadable.readableis true only while the organization may read the profile: the publication is effective and the candidate has not hidden the organization. Otherwiseblocked_byisvisibility. A declined invitation keeps both fields null. - Visibility decision. The acceptance is allowed while the profile is hidden from the organization or not published, as the contract's example of a blocked grant shows. It never publishes the profile, never changes the publication, and never lifts or adds a hiding. The grant stays stored and becomes readable when the candidate publishes the profile or unhides the organization;
readableis recomputed on every read, so the grant itself never changes. The organization seescontact_accessasclosedwhile the grant is blocked, and asavailableonce it becomes readable (see Contact reads and revocation). - Concurrency. The candidate command never takes the organization lock. Two concurrent acceptances of one version make one transition: the second waits for the row and then answers as a repeat, which is 200 with the same answer for identical terms and fields and 409 for another field set.
- Clocks. The answer time comes from the invitation service and the grant time from the consent service. In production both read the process clock, so they can differ by microseconds; the grant keeps the consent time. A replay of a stored acceptance rebuilds the response from the invitation and the grant. The outcome table keeps no copy of the response, so a later state change would show in a replay, as it would for a decline.
- Ledger keys. The C4 columns of the consent ledger still have no foreign keys to
organizationsandinvitations: the ledger tests write C4 records with synthetic identifiers. The composite keys of the grant keep an acceptance consistent without that change; the ledger keys need fixtures with real invitations and are a follow-up.
Not implemented: the counter offer and the cancellation, including the revocation of a grant after the participation is cancelled (the other revocations are in Contact reads and revocation).
Tests: domain/contact_grant_test.go (the grant from its record, the scope and revocation rules, the visibility view, the offer rendering, and Accept), usecase/invitation/accept_test.go (the order of checks, repeats, stale terms, late commands, consent pointers, visibility without a change of the publication), adapter/primary/http/v1/invitation_candidate_test.go (failure statuses), and the integration tests TestCandidateInvitationAcceptOverHTTP (an email-only grant, repeats and conflicts, a stale terms version and the raised terms, concurrent acceptances, a hidden profile, a late acceptance, consent and kind checks, the server log) and TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback against a real PostgreSQL.
Pending limit, cooldown, and expiry
Implemented: the limit of invitations that wait for an answer per need, the pause of the organization and candidate pair after a decline, and the expiry of an invitation at its response deadline. Code: usecase/invitation/pending_limit.go (the send checks), usecase/invitation/expire.go (the handler of the job invitation.response_deadline, the shared expiry function, and the scheduling at delivery), domain/invitation_expiry.go (Expire and ExpiryEvent), usecase/invitation/send.go, decline.go, accept.go, and view.go (the expiry before a candidate answer), the adapter adapter/secondary/postgres/invitation_expiry.go with db/queries/invitation_pending.sql, invitation_cooldowns.sql, and invitation_expiry.sql, the registration in jobHandlers() (bootstrap/jobs.go), and migration 00043_expire_invitations.sql.
- Limit. A send counts the invitations of the need that wait for an answer (
delivered,viewed,counter) and answers 409state_conflictwhen there are alreadymax_pending_per_needof them in the effective policy (20 in the demo policy). The count is exact: the send takes the organization lock before anything else, and only a send can move an invitation into the waiting states. An invitation without a need has no need limit; the quota bounds it. Leaving the waiting states (a decline, an expiry, an acceptance) frees the place but never returns the weekly quota: the quota is charged at the send and does not change. - Pause. A send answers 409
state_conflictuntilrepeat_after_decline_days(30 days) have passed since the latest decline of the candidate by this organization. The pause belongs to the pair of the organization and the candidate, not to a need and not to a member: another need or another owner of the same organization gets the same refusal. The pause after a no deal does not apply yet: no operation produces theno_dealstate. - Lock order. A candidate's decline takes the organization lock before the invitation row, like every command that can change the pause of a pair. The decline and a send of the same pair are therefore ordered: a send never misses a decline that committed before its check. The order is the same as in sending: the organization, then the invitation rows.
- Deadline. A send schedules the job
invitation.response_deadlinein the same transaction as the delivery: the key is the invitation identifier, the due time isresponse_deadline_at, and the payload holds only the identifier. The handlerResponseDeadlineJobruns in a transaction that locks the invitation row. If the invitation still waits for an answer, it moves toexpiredwith the reasoninvitation_timeout; otherwise the handler changes nothing. A repeat of the job is safe: a second run finds no invitation that waits for an answer. - Candidate commands at or after the deadline. The view, the decline, and the acceptance lock the row and read the time while they hold the lock; the read (
GetMyInvitation) locks the row only when the deadline has passed. In both cases, when the deadline has passed, the expiry is applied first with the same conditional UPDATE and the same audit event. The read and the view then answer with the invitation in the stateexpired, with no view recorded; the decline and the acceptance answer 409state_conflictand keep the outcome under the key. The list of the candidate's inbox and the organization's reads do not apply the expiry: they show the stored state until the job or the next candidate command applies it. - What the expiry writes. The transition writes only the audit event
expiredwith its version, no field, and no actor (actor_idis empty, because the server made the change). No consent C4, contact grant, decline record, or quota change is created or changed. The deadline and the terms are kept. The constraintinvitation_events_system_actorallows an empty actor only forexpired, the triggerinvitations_guard_expiryallows the transition only fromdeliveredorviewedand not before the deadline, andinvitations_expiry_reasonrequires the reason. - Race with the acceptance. An acceptance at or after the deadline always refuses: the acceptance and the job both decide by a time that is known while the row is held. Whichever path takes the row first, the outcome is one: an
expiredinvitation with no grant. An acceptance before the deadline that commits before the job leaves the job without effect. The testsTestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres(the race) andTestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres(the job first) check it. - Clock. The deadline and the limits are decided by the application clock, injected into the usecases and into the job handler; the database clock decides nothing. A handler whose clock has not reached the deadline returns an error, so the job is retried with backoff instead of completing without the expiry.
- Running. The worker that runs the job is the one enabled by
JOBS_ENABLED; without it the job waits in the database. The candidate commands apply the expiry without the worker, so the candidate's answer stays correct. - Migration 00043. The new event kind
expired; the constraintsinvitation_events_expiry_changes_no_fieldandinvitation_events_system_actor; the triggerinvitations_guard_expiry; the partial indexesinvitations_pending_need_idx(the waiting invitations of a need) andinvitations_declined_pair_idx(the declines of a pair); and the backfill of the expiry jobs for invitations delivered before the migration, keyed by the identifier withON CONFLICT DO NOTHING. The rollback refuses while expired invitations exist and removes the jobs of this kind.
Not implemented: the pause after a no deal (it needs an operation that moves an invitation to no_deal and sets the end of the pause), the expiry of the counter state (no operation produces it yet), the reason negotiation_timeout, and a limit for invitations without a need, should one be introduced.
Tests: domain/invitation_expiry_test.go (the expiry of a waiting invitation only after its deadline, the kept deadline and terms, and the event without an actor); usecase/invitation/pending_limit_test.go (the limit at 20 waiting and the 21st, two concurrent sends at 19, the freed place without a quota return, the pause at day 29 and day 30 for another owner and another need, and no pause for another candidate or an expired invitation); usecase/invitation/expire_test.go (the expiry by a read, a view, an acceptance, and a decline at the deadline, the job and its repeat, and the job refusal of a payload that names no invitation); the integration tests TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres, TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres, TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres, TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres, and TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries in integration_test/invitation_expiry_test.go.
Contact reads and revocation
Implemented: GetOrganizationInvitationContacts (contract) in usecase/invitation/contacts.go and adapter/primary/http/v1/contacts.go; the disclosure type in domain/contact_disclosure.go; the grant lock ContactGrantRepository.LockForRead in adapter/secondary/postgres/invitation_accept.go; the closings in consent_revocation.go (ConsentRevocationEffects.Apply), privacy_view.go (CloseForVisibility), and contact_grant_closure.go; the queries in db/queries/contact_grants.sql; and migration 00042_index_contact_grants_by_candidate.sql, which adds the candidate-wide index that the candidate-wide closings use. The organization's contact_access is derived in usecase/invitation/contact_access.go, through the same readableContactGrant check that the read uses (usecase/invitation/contacts.go).
- Access. The company middleware checks the session, the active owner membership, and the path before the handler. A non-owner member answers 403, an account without a membership answers 404, and a candidate account answers 403. The usecase repeats the owner check inside its transaction. In the MVP no other role reads contacts.
- Lock order. The read takes, in this order: the organization and the membership (
LockActiveMembership, share locks), the candidate account, the newest active C2 record, the publication with its C2 record (which also applies the organization's hiding), the C4 record of the grant, and the grant itself. The unlocked grant read before the locks only names the candidate, which a grant never changes. A C4 revocation locks the record and then the grant in the same order, so the two cannot wait for each other in opposite orders. The visibility locks come first, so a hiding or a C2 revocation that commits first is seen, and one that waits runs after the read commits. - Decision. The read answers 200 only when the grant is active, its C4 record is unrevoked, and the organization may read the publication now. Every other case answers 404
not_foundand does not say which one applies: no grant of this invitation for this organization, a revoked grant or C4 record, or a profile that is closed or hidden from the organization. A kind returns its value only when the profile holds it as a confirmed claim; any other kind is null, and a suggestion that nobody confirmed is never disclosed. The response hasCache-Control: no-store. - Closings. Each closing runs in the transaction of the change, stamps the revocation time and its reason, and never reopens a grant:
- Revoking C4 for an organization (
consent_revoked) closes the grants that name the revoked records. The grants of other organizations and of other invitations stay open. - Revoking C2 (
visibility_closed) closes every active grant of the candidate, including when the candidate has no publication row to close. - Closing the publication (
visibility_closed) closes every active grant of the candidate. - Hiding an organization (
visibility_closed) closes the active grants of that organization, including on a repeated hide. Unhiding and publishing again close nothing and reopen nothing: a closed grant keeps its first stamp, which the guard trigger allows once. - A grant stored while the profile is not readable is not closed by that state. It stays active and blocked by visibility, becomes readable when the candidate publishes or unhides, and the next closing event closes it.
- Withdrawing an invitation by the organization changes no grant. Cancellation of the participation by the candidate (
participation_cancelled) is not implemented. A C1 revocation closes no grant, because the contract names no reason for it.
- Revoking C4 for an organization (
- Organization view. Each organization response that carries
contact_accessderives it from the grant of the invitation, in the transaction of the request:GetOrganizationInvitation,ListOrganizationInvitations, and the responses of the draft create, update, and send. No grant answersnot_granted, and a revoked grant answersclosed. An active grant runs the read's visibility locks and checks, then its C4 record and the grant, so the view saysavailableexactly when a read would succeed at that moment, andclosedotherwise. The view lists the granted kinds only while it isavailable;closedcarries no reason, and no contact value is ever part of the view. The derivation reads the grant of every state, so a withdrawn invitation keeps the state of its grant, as the contract requires. A declined or expired invitation has no grant and answersnot_granted. The idempotent replays of a create and of a send return the stored original response, so theircontact_accessis the state at the first answer. The derivation costs one grant lookup per invitation, and it takes the share locks only for an invitation with a grant. - Quota and audit. A successful read writes one
contact_readrow tocandidate_card_access_eventsin the same transaction, with the granted kinds and never a value. It does not consume the card-view quota, because the contract does not count contact reads against it. The candidate's own history read stays a contract-only operation. - Not implemented: the candidate's cancellation, and the organization's withdrawal.
CurrentContactFieldsinusecase/candidateviewstays closed, because the card-handle read has no contract operation.
Tests: domain/contact_disclosure_test.go (confirmed values only, refused revoked grants, redacted formatting), usecase/invitation/contacts_test.go (owner and role checks, visibility, revoked grant and C4 record, unknown invitations), usecase/invitation/contact_access_test.go (the organization's states, their agreement with the read in each closing state, a blocked grant that opens once it is visible, and a revoked grant that never reopens), and the integration test TestOrganizationContactReadsAndRevocationOverHTTP over the real router and PostgreSQL. It covers the email-only read, the repeated read, the refusals of another organization, a recruiter, and a candidate, C4 revocation with an independent organization, hiding and unhiding without reopening, C2 revocation with republication, closing the publication, and the index. It also checks contact_access of the single read and of the list after each change, a declined invitation, and an expired one, which runs last because it moves the clock. TestCompanyIsolationAndRevocationOverHTTP walks every organization-scoped operation of the minimal path with the valid session of another company, on the path of the owning company and on its own path with the identifiers from the owner's responses, and checks that each one answers the documented refusal, the same as for an identifier that does not exist, and changes nothing. It does the same for a candidate with the invitation and the notification of another candidate. It also checks that hiding the organization, revoking C4, and withdrawing C2 close the next card, evidence, draft, search, and contact read through the handles of an earlier search, that neither a new C2 nor a new publication revives a grant that C4 revocation closed, that the MVP serves no PDF, selection snapshot, or stored search result, and that the server log, the outbox payloads, the inbox rows, and the stored email requests carry no contact, name, or profile value of the candidates.
Frontend
The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need.
The shared API wrapper owns base URL, cookies, AbortSignal, and error parsing. MSW is for development and tests; it is not a real integration check. Logout/account switch clears private query cache. Screens need loading, empty, error, retry, and forbidden states.
The target screen stack is React Router, TanStack Query, React Hook Form, and Zod, with CSS Modules and CSS variables. Radix UI can be added for complex accessible menus and dialogs. Add Next.js only for a demonstrated SSR or indexable-catalog need; Bun does not replace the selected stable Node and pnpm setup. Vite builds static assets served by Nginx, so production does not need a Node frontend process. These are target choices, not a claim that product libraries are already wired into the scaffold.
Future extensions
Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node. The outbox table, its transactional writer, the relay, and the consumer runtime are implemented (see "Transactional outbox", "Outbox relay", and "Event consumers" above); one product consumer, notification_delivery, is registered; further consumers and additional topics are planned. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI.
k3s is outside the critical path. Consider it only with an operated cluster or measured multi-node need. A single-node cluster does not provide HA. A transition needs probes and resource limits, secrets, storage backup, ingress, and verified NetworkPolicy.
Vacancies and voluntary applications, recurring assessments, employer complaints/verification, ATS adapters, and deeper matching are future scope. Employer verification and ATS integration are not implemented or required for the first prototype.
First product API slice
| Group | Initial target |
|---|---|
| identity | register, verify/resend email, login, logout, me; password reset can wait until the final phase |
| candidate | own profile, questionnaire, consent, publish and hide |
| documents | resume upload, analysis request, job status, confirmation of proposed fields, PDF retrieval |
| assessment | available tests, attempt start, answer save, submit, history, and eligibility |
| company | company profile and current user membership |
| matching | need, confirmation of extracted fields, search create/refine/read |
| invitation | send, list, view, accept/decline, withdraw, and authorized contact access |
| achievement | FSP link state and achievement history; fixture provider for demos |
Examples of stable operations are POST /api/v1/searches, POST /api/v1/searches/{id}/refinements, POST /api/v1/candidates/{id}/invitations, and POST /api/v1/invitations/{id}/accept. These are target examples, not implemented endpoints. Every business operation, response, and error belongs in OpenAPI with a stable operationId.
Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amounts for the MVP, and bounded cursor pagination. Distinguish null from absent fields. Errors have a stable code, safe message, optional field errors, and request ID. Use idempotency keys for invitation creation, analysis start, and assessment submission; scope keys by actor and operation, and reject reuse with a different body. Check access for every object ID, job, search run, and PDF. Never include contacts in common errors or public examples. The contract fixes the error model, Idempotency-Key, If-Match, pagination, and time format in api/README.en.md; of these, only the problem-based error mapping is implemented.
Metrics, telemetry, and alerts
The Go service exports standard Go/process metrics and the product metrics on an internal /metrics listener outside /api/v1:
- API:
lincodex_http_requests_total{method,route,status},lincodex_http_request_duration_seconds{method,route,status_class}, andlincodex_http_problems_total{route,code}.routeis the chi route template of an operational route and, under/api/v1, the OpenAPI path template of the matched operation, such as/api/v1/me/invitations/{invitation_id}, which the router resolves with the generated server'sFindPath; a path or method without an operation keeps the mount pattern/api/v1/*or/api/*, and a path outside every route isunmatched.status_classis1xxto5xx.codeis the RFC 9457 problem code:problem.Newrecords it from the closed catalogue through the request-scopedobservepackage (adapter/primary/http/observe/), the middleware counts it only for a 4xx or 5xx response, and the adapter counts a code outside its mirrored list asother. An error without a problem body, such as/readyz503, is counted by status only. The request log (middleware.RequestLog, which replaces the go-httpkit logger) uses the same route template and logs the request ID, method, status and class, problem code, latency, response size, and the number of query parameters, never the raw path, a query key or value, a header, the client address, or the user agent;/healthzand/readyzare not logged. - Outbox and events: the relay, consumer, and scheduled job metrics in Outbox relay, Event consumers, and Scheduled jobs. Outbox lag is
lincodex_outbox_relay_oldest_pending_age_seconds. - Mail:
lincodex_mail_deliveries{kind,status}for every kind and the statusespending,waiting_quota,unknown,accepted,rejected, andcancelled, zero included;lincodex_mail_sender_running, 1 while this process's mail sending loop runs and 0 otherwise (per process, so aggregate it withmax; it stays 0 withEMAIL_PROVIDER=disabled, where no loop starts);lincodex_notification_sender_runningreports the same for the notification loop;lincodex_mail_delivery_oldest_due_pending_age_seconds, which counts only service mail (domain.ServiceMailKinds), so a notification backlog never looks overdue;lincodex_mail_sender_cancelled_total{reason}, deliveries the sending worker ended without sending, by the closed set of cancel reasons, zero included; and, for an active transport,lincodex_mail_quota_used_recipients,lincodex_mail_quota_limit_recipients, andlincodex_mail_quota_provider_exhausted, each withproviderandwindow(dayormonth). The sampler inbackend/internal/worker/deliverymetrics/reads them every 30 seconds on its own one-connection pool:postgres.DeliveryStatisticsStoreaggregatesdeliveriesby kind and status, andMailQuotaUsageReader.Usagereads the current windows of the configured account. The delivery aggregate is the sqlc queryGetDeliveryStatisticsindb/queries/delivery.sql. It scans the table, which suits the current volume; add an index or per-status counters before the table holds millions of rows.EMAIL_ACCOUNTis not a label: it is free operator text that can name a person, and each process reports only its own account. Every instance reports the same database-wide values; aggregate them withmax. A failed read keeps the previous values and logsdelivery metrics could not be read; the gauges are stale;lincodex_mail_metrics_last_success_timestamp_secondsshows the last read in which every aggregate was read (0 from the sampler start until the first one), and the age gauge exists only after the first successful read. There is no attempt outcome counter yet; the delivery states, the logs of the sending worker, and thedelivery_attemptshistory show outcomes. - Assessment answers:
lincodex_assessment_answer_saves_total{format,outcome}with the outcomesstored,unchanged,rejected, andfailed. PRD 6.6 asks to observe the saving of answers; this is read as the assessment answer commandSubmitMyAssessmentAnswer. The command is implemented, but nothing calls the hookMetrics.ObserveAssessmentAnswerSaveyet, and no series appears until the usecase calls it once per command. A value outside the closed sets becomesother. The HTTP latency and errors of the command already appear under the route/api/v1/me/assessment-attempts/{attempt_id}/answers.
Do not use user, candidate, delivery, or request IDs, full URLs or query strings, addresses, or resume content as labels. Unit tests drive the real router and every metric hook with email and UUID fixtures and fail when the exposition contains an email-like or UUID-like value. Go runtime, PostgreSQL, Redis, SeaweedFS, Linux, and Lincodex product dashboard JSON files are maintained project sources, not imported dashboard IDs. Inference metrics are not implemented in the current scaffold.
Planned observability work includes bounded measurements for queued jobs, oldest ready age, wait and run duration, retries, and terminal failures; pgxpool state should use bounded nonblocking reads inside Go. Nginx stub_status does not provide latency by HTTP status; access logs can provide request_time and upstream_response_time. cAdvisor is optional if the selected runtime supports it. Redis exporter is included in the separate monitoring Compose project; Prometheus scrapes its internal port 9121. SeaweedFS metrics are scraped directly on internal port 9327, retaining only selected aggregate series without object paths. DCGM exporter is only needed with a local NVIDIA model.
The planned browser path is Faro Web SDK -> same-origin /telemetry -> Alloy faro.receiver -> Loki. The React SDK is not connected yet. Collect cleaned Web Vitals, JavaScript errors, release, and normalized route; exclude console logs, form content, resume text, and session replay. Remove query strings, fragments, and identifiers from URLs. Limit receiver size, rate, and origin. Request/trace IDs remain log fields, not labels; complete span storage needs a separate backend such as Tempo and is not currently supported.
Alert rules in observability/prometheus/rules/lincodex.yml cover an unavailable backend target, a 5xx share above 5% with at least 15 requests in 5 minutes, outbox lag, dead letters and stalled consumers, dead and lagging scheduled jobs, deliveries with an unknown outcome, stale delivery and quota gauges, a used-up mail quota, and overdue deliveries; the last one also requires lincodex_mail_sender_running to be 1 on some instance, so it stays silent where no sending loop runs, for example with EMAIL_PROVIDER=disabled. It counts only service mail, the kinds the worker sends, so a due notification does not fire it. LincodexMailCancelledBroken fires on an increase of lincodex_mail_sender_cancelled_total with the reason content_invalid or processing_failed, the cancellations that mean a broken row or a defect rather than a user action; the rights reasons of notifications (rights_revoked, recipient_ineligible, source_closed) are normal and do not fire it. promtool test rules gives every alert a firing case and every guard a silent one. Prometheus evaluates them and shows their state on its /alerts page and in Grafana; no Alertmanager or notification channel is configured, so no alert reaches a person. Future alerts cover latency budget breaches, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure No Data and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested.
Requirements coverage
| Brief requirement | Target decision | State |
|---|---|---|
| Two portals and verified email, pp. 3-4 | identity, roles, company, access checks | Implemented (no password reset) |
| Manual or PDF resume, p. 3 | Manual profile first; PDF and ML extend it | Manual profile implemented; PDF and ML import are not |
| Standard PDF, p. 3 | PDFRenderer with Cyrillic and access checks | Not implemented |
| Questionnaire, grade, test, category, pp. 1-3 | assessment, variants, grade history | Implemented on a demonstration bank; categories are uncalibrated |
| Comparable tests and leak resistance, pp. 1-2 | Families, blueprint, rubrics, rotation, pilot | Planned |
| No forced grade decrease and change frequency, pp. 2-3 | verified/claimed, retry, cooldown, eligibility | Planned |
| Candidate search and explanation, pp. 3-4 | Hard filters, matching evidence, score components | Basic deterministic search implemented; ML, competition data, and snapshots are not |
| Refine search without losing prior results, p. 4 | Versioned search runs and server snapshots | Planned |
| Invitation without a vacancy, p. 3 | Optional vacancy_id | Not implemented |
| RUB salary range and employer contact, p. 4 | Required bounds and explicit period/tax basis | Implemented |
| Status for both sides, p. 4 | State machine and event history | Partial: draft, delivered, viewed, accepted, declined, expired; later stages, withdrawal, and cancellation are not |
| Contacts after acceptance/application, pp. 3-4 | Contact grant, separate DTOs, file access check | Contacts after acceptance implemented; files and candidate applications are not |
| Privacy and access to own records, pp. 3, 6 | Consent, object/company authorization, cache and snapshot checks | Consents, publication, hidden organizations, history, and access checks implemented; no match snapshots |
| 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.