1029 lines
179 KiB
Markdown
1029 lines
179 KiB
Markdown
# Local deployment and Compose
|
|
|
|
This guide describes the checked-in configuration. Compose provides a local technical stack; it does not establish a production deployment.
|
|
|
|
## Running the MVP: quick start
|
|
|
|
This section is for anyone who starts the MVP on their own machine: the jury, the team, or a reviewer. Run the commands from the repository root; the other sections of this guide describe each setting in detail. The scenarios below were run on a fresh clone with the example files `.env.example` and `deploy/demo/demo.env.example`.
|
|
|
|
### Implemented and planned
|
|
|
|
Implemented in this build (backend API and frontend screens):
|
|
|
|
- Candidate and employer registration with consent C1, email confirmation with the six-digit code or the link from the message, sign-in, sign-out, and resuming from the saved step. Mail is sent only with `EMAIL_PROVIDER=resend`.
|
|
- Candidate cabinet: consents C1-C5, a manual profile without a resume and without an FSP ID, the questionnaire with specializations and self-assessment, and the home page with the next step.
|
|
- Skill assessment: the `demo_express` demonstration express run without a grade and the `demo_basic` full test with a result, result history, and skill evidence. On the demo stand a passed full test receives an uncalibrated synthetic category. The operator can read the [review band](#assessment-review-band).
|
|
- Privacy: publication of the anonymous card (C2), preview, search status, hidden organizations, and the history of changes and card views.
|
|
- Employer cabinet: organizations (one account can own several and be a recruiter in others), the company profile, needs with a salary range, deterministic candidate search over the bank or by a need without ML, with an explanation of the components, and the anonymous card with its evidence. Only an organization owner can search.
|
|
- Support cases in both cabinets, including a manual assessment request after a C3 refusal.
|
|
- The notification inbox in both cabinets. A delivered invitation creates a notification for the candidate; the mail about it is sent only with `EMAIL_PROVIDER=resend`.
|
|
- Invitations: the organization creates a draft from a search result, changes the terms with versions, and sends the invitation. The candidate sees it in the incoming list and accepts it with the consent C4, choosing the contacts, or declines it. After the acceptance the organization reads the disclosed contacts on the invitation page. The company's invitation list is still a placeholder.
|
|
|
|
Planned and not working: withdrawing an invitation and the candidate's cancellation of participation, salary raise (the API answers 501 `not_implemented`), password reset, mail for other product notifications, resume upload and parsing, PDF, FSP integration, ML inference and semantic search, the adaptive test, sandbox practice, percentiles and calibrated grades, and the SMTP transport.
|
|
|
|
### Requirements
|
|
|
|
Docker Engine with the Compose plugin, GNU make, python3 (the `deploy` targets run check scripts), and openssl to generate a secret. No GPU, external inference key, or FSP access is needed: no target reads one. The first start builds the backend and frontend images and pulls base images, so it takes several minutes; later starts use the cache.
|
|
|
|
### Stand parameters
|
|
|
|
| Stand | Command | Compose project | Address | Data |
|
|
| --- | --- | --- | --- | --- |
|
|
| Core | `make -C deploy up` | `APP_PROJECT`, default `app` | http://localhost:8080 (`APP_HTTP_PORT`, bound to `APP_HTTP_BIND=127.0.0.1`) | Migrations and the startup policy version 1; no assessment bank, matching section, or accounts |
|
|
| Demo | `make -C deploy demo-seed DEMO_MODE=isolated` | `DEMO_PROJECT`, default `lincodex-demo` | http://localhost:8090 (`DEMO_HTTP_PORT`, `DEMO_PUBLIC_URL`) | Synthetic accounts, organizations, assessment bank, and prepared attempts |
|
|
| Technical smoke | `make -C deploy smoke` | `lincodex-smoke`, removed after the run | 127.0.0.1:18080 during the check | None |
|
|
| ML | `make -C deploy ml-up` | `ML_PROJECT`, default `ml` | http://127.0.0.1:8000 (`ML_HTTP_PORT`) | No model; `/readyz` answers 503 |
|
|
| Monitoring | `make -C deploy monitoring-up` | `MONITORING_PROJECT`, default `monitoring` | Grafana http://127.0.0.1:3000 | Metrics and logs of the core stack |
|
|
|
|
- Open a stand exactly at the address in `APP_PUBLIC_URL` or `DEMO_PUBLIC_URL`, that is through `localhost`. The backend compares the Origin of every changing request with this address, so signing in from a page at http://127.0.0.1:8090 is refused with 403 `csrf_check_failed`. The session cookie has the `Secure` flag; browsers accept it at http://localhost, and another host needs HTTPS (see [Edge proxy, HTTPS and tunnel](#edge-proxy-https-and-tunnel)).
|
|
- Make takes the project name from the command line or the environment, not from `.env`. To run a stack under another name, pass the same value to every target: `make -C deploy up APP_PROJECT=<name>`, then `logs` and `down` with that value. The port and bind address come from `.env`.
|
|
- The core and demo stands use different subnets and ports and can run at the same time.
|
|
|
|
### 1. Core stack
|
|
|
|
cp .env.example .env
|
|
# replace every replace-this-... value with your own;
|
|
# POSTGRES_PASSWORD takes URL-safe characters only, for example hex
|
|
# IDENTITY_KEY_SECRET= paste the output of: openssl rand -base64 48
|
|
make -C deploy config
|
|
make -C deploy up
|
|
curl http://localhost:8080/api/v1/healthz
|
|
|
|
The last command answers `{"status":"ok"}`; then open http://localhost:8080. Compose does not start with an empty `IDENTITY_KEY_SECRET`, and the backend refuses a value that starts with `replace-this`. `make -C deploy smoke` is a separate throwaway technical check: it starts its own stack with the values of `.env.example`, checks the health routes, dependency failures, and storage isolation, and removes its containers and volumes. It does not check the running stack and does not prove a business workflow.
|
|
|
|
The core stack is a clean base for a working stand. Without further steps it serves the public pages, registration, and the health checks. No assessment bank is loaded, so a test cannot start, and search answers 500 until an operator publishes the matching section (see [Match search policy on a stand](#match-search-policy-on-a-stand)). Use the demo stand to show the product.
|
|
|
|
### 2. Mail: Resend or disabled
|
|
|
|
- `EMAIL_PROVIDER=disabled` (the `.env.example` value) sends nothing. Registration is accepted (202), but the address cannot be confirmed, so signing in with such an account answers 403 `email_not_verified`. The prepared accounts of the demo stand need no mail.
|
|
- `EMAIL_PROVIDER=resend` sends confirmation mail through Resend. Set `RESEND_API_KEY` in the server environment only and never commit it, set `EMAIL_FROM` to an address on a domain verified in the Resend account, and set `APP_PUBLIC_URL` to the origin the user opens, because the link in the message leads there. Then run `make -C deploy up` again. Only confirmation mail and the mail about a new invitation are sent; the default quotas are 100 recipients per day and 3000 per month (see [Mail](#mail) and [Mail quotas](#mail-quotas)). The repository does not test real Resend: the browser test `make -C deploy test-e2e-registration` registers through a local Resend-compatible inbox.
|
|
- `EMAIL_PROVIDER=smtp` stops the backend at startup in this build.
|
|
|
|
### 3. Demo stand
|
|
|
|
make -C deploy demo-seed DEMO_MODE=isolated
|
|
|
|
The target needs the root `.env` from step 1: the stand takes the secrets and the mail transport from it and overrides the project name, port, address, and subnet. The command starts a separate project, waits for backend readiness, fills the database with synthetic data, and prints the list of logins; a repeated run creates nothing and prints the same list. Open http://localhost:8090; the jury guide is at http://localhost:8090/demo.
|
|
|
|
Every prepared account uses `DEMO_ACCOUNT_PASSWORD` from `deploy/demo/demo.env`, or from `deploy/demo/demo.env.example` when that file does not exist. The example value is a published demo credential of synthetic accounts, not a secret. For a stand reachable from outside, copy the example to `demo.env`, set a new password, run `make -C deploy demo-reset DEMO_MODE=isolated`, and give the password to the jury separately.
|
|
|
|
| Login | Purpose |
|
|
| --- | --- |
|
|
| `candidate@demo.lincodex.test` | Self-guided run: the express run and the Backend Junior full test with Go |
|
|
| `prepared-1@demo.lincodex.test` - `prepared-6@demo.lincodex.test` | Candidates with a completed full test, a synthetic Backend Junior category, evidence, and a published card |
|
|
| `employer-alpha@demo.lincodex.test` | Owner of the "Alpha" organization and recruiter in "Beta" |
|
|
| `employer-beta@demo.lincodex.test` | Owner of the "Beta" organization |
|
|
|
|
The full inventory and the seed rules are in [Isolated demo stand](#isolated-demo-stand).
|
|
|
|
### 4. Demonstration route
|
|
|
|
1. Candidate: sign in as `candidate@demo.lincodex.test` and open the skill assessment (`/candidate/assessment`). The express test has three items and ends with the result "Экспресс-тест без грейда" (express test without a grade): no grade, category, percentile, or evidence, and it does not appear in the real result history. This is the express run without a grade.
|
|
2. On the same page start the Backend Junior full test with Go: 25 items, a 72-hour deadline, two work sessions, no practice. After it completes, the result is compared with the pass mark of the demo policy; a passed test receives an uncalibrated synthetic category, a failed one the result `not_confirmed`. The result and the history open at `/candidate/results`.
|
|
3. Prepared candidate: sign in as `prepared-1@demo.lincodex.test` and open the results, the skill evidence, and the privacy settings with the published card.
|
|
4. Employer: sign in as `employer-alpha@demo.lincodex.test`, select "Alpha", create a need, and open the search (`/employer/candidates`). The main group holds the six prepared cards with the flags `ml_unavailable` and `cohort_below_30`; a card and its evidence open from the results. In "Beta" the same account is a recruiter, and search answers 403: in the minimal release only the owner can search.
|
|
5. Invitations: the company creates an invitation with the "Invite" button of the first card of the main group, fills in the tasks and the team description (the need does not fill them), sends it, and keeps the address of the invitation page: it holds `invitation_id`. Equal cards keep a fixed order, and the first one belongs to `prepared-1@demo.lincodex.test`. This candidate accepts the invitation at `/candidate/invitations`, choosing the contacts and the consent C4, and the company reads the disclosed contacts on the same invitation page. The company's invitation list is still a placeholder, so keep the page address.
|
|
|
|
The eight-minute step-by-step guide with links to the screens and the logins is on the stand at `/demo`; the start page has the button "Open the jury guide". The guide exists only in the demonstration stand build.
|
|
|
|
### 5. FSP, ML, and data
|
|
|
|
- FSP: there is no integration in any mode. This build has no off or mock switch, no fixture provider, and no call to an external API. The profile is filled in manually, linking an FSP ID is optional and not available yet, and the path to a category goes through the questionnaire and the test. The project has no official access to FSP data and does not promise it; an FSP link through a fixture provider is planned (see [ARCHITECTURE.md](ARCHITECTURE.md#identity-fsp-and-privacy)).
|
|
- ML: by default the core and demo stands do not start ML and do not call it; search uses the neutral semantic similarity 0.5 with the `ml_unavailable` flag. Semantic matching is enabled separately: the ML service with the Giga-Embeddings-instruct-480M and Qwen3-Embedding-0.6B models (the ML Compose project on CPU or the [ML service on a GPU host](#ml-service-on-a-gpu-host)), the shared token `ML_SERVICE_TOKEN`, `SEMANTIC_MATCHING_ENABLED`, the semantic policy, and a backfill (see [Semantic matching](#semantic-matching)). No external inference keys are needed or read.
|
|
- Data: the demo stand holds synthetic data only. Addresses on the reserved domain `@demo.lincodex.test` never receive mail, names are marked as synthetic, categories have the source `synthetic_demo` and are uncalibrated, and the item families are synthetic and had no subject review. Do not register real people on this stand. Synthetic categories are enabled (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`) only by the demo overlay and by the overlay of the isolated registration browser suite (see [TESTING.md](TESTING.md#minimal-path-from-registration-to-disclosed-contacts)); `.env.example` sets `false`.
|
|
|
|
### 6. Checks
|
|
|
|
| Command | What it shows |
|
|
| --- | --- |
|
|
| `make docs-check` | Documentation structure and local links |
|
|
| `make -C deploy config` | Rendering of every Compose file without starting it |
|
|
| `make -C deploy smoke` | Technical smoke on a throwaway stack |
|
|
| `make -C frontend install`, then `make -C deploy test-e2e` | The Playwright browser suite on a throwaway stack |
|
|
| `make -C deploy test-e2e-registration` | Browser registration, confirmation, and sign-in through a local Resend-compatible inbox |
|
|
| `make -C deploy check-demo` | The guards of the demo stand targets without starting services |
|
|
| `make test`, `make check`, `make verify` | The full check set, see [TESTING.md](TESTING.md#commands) |
|
|
|
|
The smoke and the browser suites do not start the demo stand; an integration test covers its seed (see [Demo seed tests](TESTING.md#demo-seed-tests)).
|
|
|
|
### 7. Stop and clean up
|
|
|
|
make -C deploy down
|
|
make -C deploy demo-down DEMO_MODE=isolated
|
|
make -C deploy ml-down
|
|
make -C deploy monitoring-down
|
|
|
|
These targets stop the containers and keep the volumes. `make -C deploy demo-reset DEMO_MODE=isolated` recreates the demo stand with its initial data only when it holds no ordinary account; otherwise the reset refuses and deletes nothing. Removing a demo project together with its data is a deliberate manual decision only: `docker compose -p lincodex-demo down --volumes` with the name of your project. The `<project>-backend`, `<project>-frontend`, and `<project>-demo-seed` images built by these targets stay local; remove them with `docker image rm` when they are not needed.
|
|
|
|
## Core application
|
|
|
|
Install Docker Engine and the Docker Compose plugin. At the repository root, copy .env.example to .env, replace every placeholder password, and keep the file local. Then run:
|
|
|
|
make -C deploy config
|
|
make -C deploy up
|
|
|
|
deploy/docker/docker-compose.yml starts PostgreSQL, Redis, SeaweedFS, Kafka, the Go backend, and the frontend container. Nginx in the frontend container serves static assets and proxies /api to Go. PostgreSQL, Redis, SeaweedFS, Kafka, Go, and Nginx communicate on the Compose network.
|
|
|
|
Before it opens its listeners, the backend applies the database migrations embedded in its binary; a migration error stops the container. Compose does not pass `DATABASE_MIGRATE_ON_START`, so the deployed backend always migrates at startup, and the PostgreSQL role in `DATABASE_URL` needs DDL rights on the application schema. That flag is a local development option; a separate least-privilege migration role is future work. Right after the migrations, and only when they run, the backend seeds the demo product policy: when the `product` policy family has no version, it publishes version 1 and logs `demo product policy published`; otherwise it logs that the seed was skipped and changes nothing. With `DATABASE_MIGRATE_ON_START=false` the seed is skipped too. A database error during the seed stops the container like a migration error. See [DEVELOPMENT.md](DEVELOPMENT.md#database-migrations) and [ARCHITECTURE.md](ARCHITECTURE.md#product-policy-versions).
|
|
|
|
Consent texts are published by migrations, not at startup: migration 00009 publishes the demo texts `c1-2026-10-01` to `c5-2026-10-01` with `kind` `demo`. The database refuses to change or delete a published text, so a new text is a new version in a new migration, and the texts of the actual operator must be published that way before real personal data are accepted. An account with consent history cannot be deleted with a plain `DELETE FROM users` (SQLSTATE 23001 on `consent_records_subject_id_fkey`), and the consent records of a confirmed account cannot be deleted at all (SQLSTATE 23000, `consent_records_retained`); only the unverified account cleanup and the re-registration of an unverified account remove consent records. See [ARCHITECTURE.md](ARCHITECTURE.md#consent-ledger).
|
|
|
|
The backend build context is `backend/`, so Docker applies `backend/.dockerignore`. Local tools, caches, environment files, and build outputs are excluded from that context.
|
|
|
|
The current `postgres:alpine` volume mounts at `/var/lib/postgresql`; the image stores data in a subdirectory for its major version. When the tag advances to a new major version, migrate an existing database with `pg_upgrade` or backup/restore. Updating the image alone does not convert the data.
|
|
|
|
Open http://localhost:8080, the address in `APP_PUBLIC_URL`: from another origin, changing requests, including sign-in, are refused. The host port binds to loopback. Nginx handles /healthz, proxies /api/v1/ to Go, and uses the SPA fallback for other paths; see [Public perimeter and client address](#public-perimeter-and-client-address). The public API health route is /api/v1/healthz through Nginx /api/v1/. On the internal port 8080, Go also serves /healthz for the process and /readyz, which checks PostgreSQL with SELECT 1, Redis with PING, and the SeaweedFS bucket with HeadBucket; any dependency being unavailable produces 503. The internal backend port 9090 serves /metrics.
|
|
|
|
This Nginx configuration has no production TLS. The current bind does not expose the app directly to the public network. Remote access needs a selected TLS reverse proxy, firewall rules, and environment-specific configuration.
|
|
|
|
Useful commands:
|
|
|
|
make -C deploy config
|
|
make -C deploy up
|
|
make -C deploy logs
|
|
make -C deploy down
|
|
make -C deploy smoke
|
|
|
|
Redis uses `redis:alpine`, the `REDIS_PASSWORD` value from `.env`, and the internal `redis:6379` address; it publishes no host port. Data is limited to 128 MB with `allkeys-lru` eviction, and the container memory limit is 256 MB. RDB and AOF are disabled with no persistent volume: restarting Redis clears the cache. Do not keep the only copy of a record there. The backend and Redis exporter both require its password.
|
|
|
|
Backend settings are `REDIS_ADDR`, `REDIS_PASSWORD`, `REDIS_DB`, and `REDIS_TIMEOUT`. Compose supplies `redis:6379`; a directly launched Go process defaults to `localhost:6379`, DB 0, and a 1s timeout. Provide a separately reachable Redis address for direct execution because the current Compose does not publish Redis outside its network.
|
|
|
|
SeaweedFS uses `chrislusf/seaweedfs:latest` with `weed mini`: master, volume, filer, and S3 API share one container. The named `seaweedfs_data` volume mounts at `/data` and preserves object content and metadata. S3 is reachable only inside the network at `http://seaweedfs:8333`, with no published host port. WebDAV, Admin UI, IAM API, Iceberg, and Lance are disabled. Nginx continues to serve the frontend and `/api`; there is no direct object route.
|
|
|
|
Set `SEAWEEDFS_ACCESS_KEY` and `SEAWEEDFS_SECRET_KEY` in `.env`, replacing the example values. Compose passes them to the server as `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`, and passes `SEAWEEDFS_BUCKET` as `S3_BUCKET` to initialize the bucket at startup. This is one administrative credential pair for the local stack, not production service-level access separation. Never provide it to browser clients.
|
|
|
|
SeaweedFS joins only the internal `storage` network (`APP_STORAGE_NETWORK`, by default `<APP_PROJECT>_storage`). The backend joins it and the default network; the monitoring Prometheus joins it to scrape port 9327, so start the core project before monitoring. No other container can resolve or reach SeaweedFS. This network is the primary control, because the container also serves filer, master, volume, and admin APIs and unauthenticated gRPC that ignore S3 credentials; see [ARCHITECTURE.md](ARCHITECTURE.md#private-file-storage) for the list and the remaining risk. Do not add other services to the storage network.
|
|
|
|
The S3 credentials make S3 itself private: SeaweedFS answers unsigned S3 requests with 403, and Compose refuses to start with empty values because SeaweedFS without any identity accepts anonymous S3 requests. `-s3.iam=false` removes only the IAM management API. As defense in depth, the service entrypoint exports fresh random `WEED_JWT_*` signing keys at every start, so filer and volume HTTP requests need a token that never leaves the container, and `-ip=127.0.0.1` with `-whiteList=127.0.0.1,@` limits master and volume HTTP to in-container callers. The keys are not configuration and need no rotation; restarting the container replaces them. Smoke checks that the frontend cannot reach SeaweedFS by name or by its storage address, that S3 refuses an unsigned request, and that the filer, master, and volume HTTP APIs refuse a caller that is not inside the container.
|
|
|
|
The stack publishes no object URLs. The bucket has no public read policy or anonymous ACL, and the backend creates no public or presigned links; future downloads go through an authenticated backend endpoint that streams the file. Size and content type limits are per feature policy in `backend/internal/usecase/files/` rather than deployment settings, so there is no extra environment variable. Keep the Nginx request body limit from the upload route aligned with the largest policy when such a route is added.
|
|
|
|
Backend settings are `SEAWEEDFS_ENDPOINT`, `SEAWEEDFS_ACCESS_KEY`, `SEAWEEDFS_SECRET_KEY`, `SEAWEEDFS_BUCKET`, `SEAWEEDFS_REGION`, and `SEAWEEDFS_TIMEOUT`. Compose supplies endpoint `http://seaweedfs:8333`; a directly launched Go process defaults to `http://localhost:8333`, bucket `lincodex`, region `us-east-1`, and timeout `10s`. `SEAWEEDFS_TIMEOUT` bounds connection setup, the TLS handshake, the wait for response headers, and whole deletion and readiness calls; it does not bound object upload or download bodies, which follow the caller's context. Credentials are required. Direct execution needs a separately reachable private endpoint. Readiness checks the bucket; the backend does not create it.
|
|
|
|
Ordinary `down` preserves the SeaweedFS volume. Losing the volume loses both objects and metadata; prepare a verified backup before changing the image or deleting the volume. This is one node without HA, cross-node replication, or configured off-host backups.
|
|
|
|
Kafka uses the official `apache/kafka:latest` image as one KRaft node that combines the broker and controller roles; there is no ZooKeeper. Clients use the PLAINTEXT listener at `kafka:9092`, which is reachable only inside the Compose network and publishes no host port. The controller listener binds to `127.0.0.1:9093` inside the container, so other containers cannot reach it. The client listener has no TLS, authentication, or ACLs: any container attached to the Compose network, including monitoring services that join it, can produce and consume. Keep the network private and do not publish the port.
|
|
|
|
The named `kafka_data` volume mounts at `/var/lib/kafka/data` and stores topic logs, consumer offsets, and KRaft metadata, so events survive container restarts and an ordinary `down`. `KAFKA_HEAP_OPTS` bounds the JVM heap to `-Xms256m -Xmx512m`, and the container memory limit is 1 GB. The image's default JMX agent is disabled, so no JMX port is open. Topic data is kept for 7 days or up to 1 GiB per partition, whichever limit is reached first, in 128 MiB segments. Replication factors and the minimum in-sync replica count are 1 because there is one node. This node provides no HA or replication; losing the volume loses all events and consumer offsets.
|
|
|
|
`KAFKA_CLUSTER_ID` in `.env` is required. It identifies the KRaft cluster that formatted the volume. It is not a credential and grants no access, so `.env.example` contains a sample value. Generate your own value once before the first start:
|
|
|
|
docker run --rm apache/kafka:latest /opt/kafka/bin/kafka-storage.sh random-uuid
|
|
|
|
Changing the value after the volume is formatted stops Kafka from starting with that volume.
|
|
|
|
Automatic topic creation is disabled: writing to a missing topic fails instead of creating it. The backend creates its events topic itself (see [Outbox relay](#outbox-relay)); create any other topic explicitly. Kafka CLI tools inherit the broker's `KAFKA_HEAP_OPTS`, so give them a small heap when running them in the container. For example, a manual technical check with the default `app` project:
|
|
|
|
docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \
|
|
exec -e KAFKA_HEAP_OPTS=-Xmx128m kafka /opt/kafka/bin/kafka-topics.sh \
|
|
--bootstrap-server localhost:9092 --create --topic lincodex.technical.probe \
|
|
--partitions 1 --replication-factor 1
|
|
|
|
The Compose health check runs `kafka-broker-api-versions.sh` against `localhost:9092`, so Kafka is healthy only after the broker answers API requests. `make -C deploy smoke` waits for that health check together with the other core services; it does not check the relay or read events.
|
|
|
|
The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` bootstrap addresses. Compose supplies `kafka:9092`; a directly launched Go process defaults to `localhost:9092`. An explicitly empty value, an empty list entry, a missing or zero port, or a URL scheme fails configuration. The outbox relay connects to these brokers in the background: the backend does not wait for Kafka at startup, and `/readyz` does not check Kafka. The advertised address `kafka:9092` resolves only inside the Compose network, so direct execution needs a separately reachable broker. Redis stays a cache and is not used as a queue.
|
|
|
|
`PASSWORD_HASH_CONCURRENCY` sets the Argon2id memory budget in derivations of 64 MiB and four lanes each (from 1 to 4). Compose passes the value from `.env`, default 1, because the backend container has 1 CPU and 768 MB: a second derivation would only add 64 MiB while sharing the CPU. A directly launched backend without the variable uses the smaller of 2 and GOMAXPROCS. Further registrations and logins wait for memory until their request context ends. Compose also sets `GOMEMLIMIT=600MiB`, about 78% of the container limit, so the Go collector reclaims finished derivations before the container runs out of memory; change it together with the memory limit. The value is read and validated at startup; registration and login use it. See [ARCHITECTURE.md](ARCHITECTURE.md#password-hashing).
|
|
|
|
`IDENTITY_KEY_SECRET` is required in the production `.env` (at least 32 bytes; generate it with `openssl rand -base64 48` and keep it between restarts and across instances). It keys idempotency records and rate limits, and derives the session CSRF key; Compose refuses to start without it, and the backend refuses to start without it unless `IDENTITY_ALLOW_EPHEMERAL_KEY=true`, which is for development stands only. Changing it changes the lookup keys for the last 24 hours of counters and idempotency records and invalidates existing CSRF values, but it does not revoke sessions stored in PostgreSQL. `VERIFICATION_MAIL_MIN_INTERVAL` (default `1m`) and `VERIFICATION_MAIL_DAILY_LIMIT` (default `5`) bound verification mail per address; an empty value means the default. `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to `30` and accepts `1` to `10000`; it limits registration, confirmation, resend, and login attempts per client address when that address is resolved through the trusted proxy chain. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to `10` and accepts `1` to `10000`; it limits login attempts per normalized email whether or not an account exists. Confirmation is also limited to 5 attempts per token per hour. `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 must not exceed the absolute lifetime; invalid values stop backend startup. The metric `lincodex_identity_rate_limit_refusals_total{scope}` counts refusals; a large share of `scope="client"` hints at a broken proxy chain (see `TRUSTED_PROXY_CIDRS`). See [ARCHITECTURE.md](ARCHITECTURE.md#registration-email-verification-and-resend) and [server-side sessions](ARCHITECTURE.md#server-side-sessions).
|
|
|
|
down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop.
|
|
|
|
### Public perimeter and client address
|
|
|
|
Only three things are reachable through the frontend container: the SPA (static files and the `index.html` fallback, so a refresh of a deep link works), the versioned API under `/api/v1/`, and the same-origin `/telemetry` receiver (POST only, 1 MB, 30 requests per minute per client; the React SDK does not send to it yet). Everything else is refused: `/metrics`, `/readyz`, `/debug/`, `/actuator/`, dotfiles, `/api`, `/api/v1`, and any other path under `/api/` answer 404 and are never proxied. Backend `/metrics` listens on port 9090, which no Nginx location reaches. The only host port of the core project is the frontend bind (`APP_HTTP_BIND`, loopback by default); PostgreSQL, Redis, Kafka, SeaweedFS, and the backend publish nothing. Grafana and ML publish on loopback only (the monitoring and ML projects).
|
|
|
|
- Headers (`deploy/nginx/snippets/security-headers.conf`): `Content-Security-Policy` with `default-src 'none'`, same-origin scripts, styles, fonts, images, and `connect-src`, no inline code, `frame-ancestors 'none'`, `base-uri 'none'`, `object-src 'none'`; `X-Content-Type-Options: nosniff`; `Referrer-Policy: strict-origin-when-cross-origin`; `X-Frame-Options: DENY`; `Cross-Origin-Opener-Policy` and `Cross-Origin-Resource-Policy` `same-origin`; `Permissions-Policy` denying camera, microphone, geolocation, payment, and USB. `index.html` and the deep-link fallback carry `Cache-Control: no-cache`, so a release is picked up at once; `/assets/` (hashed names) carries `public, max-age=31536000, immutable`, and a missing asset is a 404, never the fallback page. Redirects are relative (`absolute_redirect off`, `port_in_redirect off`), so a forged `Host` cannot steer them. If the SPA later needs an external host (analytics, fonts, a map), add that host to the matching CSP directive in the same change. No CORS header is sent: the API is same-origin and a browser refuses cross-origin reads; the backend still checks `Origin` on unsafe methods.
|
|
- Body limits: `client_max_body_size` is 1 MB for `/api/v1/` (the contract's JSON bodies are small). The contract has no upload operation yet, so there is no 5 MB resume route; the change that adds it raises the limit in that route's own `location` in `deploy/nginx/conf.d/app.conf` and keeps `EDGE_MAX_BODY` at or above it. A larger body gets 413 with an `application/problem+json` body (`payload_too_large`, with `trace_id` equal to the `X-Request-ID` response header) from Nginx, in the same shape as the backend's own 413.
|
|
- Timeouts: edge read 60 s, then app Nginx read 30 s, then the backend (storage and mail calls time out after 10 s, `Redis` after 1 s, the header read after 5 s). Each outer hop waits longer than the inner one, so the backend answers first.
|
|
- Coarse rate limits in the app Nginx: 20 requests per second per client with a burst of 60 and 40 concurrent connections on `/api/v1/`. They exist to absorb floods and are far above normal use. They do not replace the domain quotas (per-account, per-route, per-email limits), which the backend owns and which keep counting on their own. The limiter key is the client address, with an IPv6 address folded to its /64 (as `middleware.LimiterKey` does). A limited request gets 429 with `Retry-After: 1` and the contract's `rate_limited` problem (with `trace_id`). Rejections are logged at `notice`, below the `warn` threshold of the Nginx error log, because a rejection line names the client address.
|
|
- Client address chain: the edge replaces `X-Forwarded-For` with the connecting address; the frontend container trusts only the edge tunnel address (`set_real_ip_from`, equal to `AWG_EDGE_IP`) and takes the client from the right end of the header, so a value put in front by the client is never reached. For a peer that is not the edge it ignores the header altogether. `X-Forwarded-Proto: https` is likewise believed only from that peer. It then sends the backend a single `X-Forwarded-For` entry, the resolved client, replacing the header, and drops `Forwarded`. The core Docker network has a pinned subnet (`APP_SUBNET`, default `172.29.79.0/24`) and the frontend container a fixed address on it (`APP_FRONTEND_IP`, default `172.29.79.10`; change both together if the range collides, and recreate an existing network with `make -C deploy down` and `up`). The backend trusts `X-Forwarded-For` only from `TRUSTED_PROXY_CIDRS`, which defaults to that one address as a /32, so no other container of the network (Prometheus, exporters, Alloy) is trusted; leave the variable unset, and an empty value trusts nobody. The throwaway smoke, e2e, and metrics-check stacks use their own subnets (172.29.81 to 83) so they can run next to a development stack. The backend walks the header from the right, skipping trusted proxies; the first untrusted entry is the client. If the edge reaches the container under another address than `AWG_EDGE_IP`, the header is ignored and clients share one limiter bucket (fail closed); see the rollout checklist below.
|
|
- The client address is used only to key limiters, in Nginx shared memory and in the backend's limiter keys (`middleware.LimiterKey`, IPv6 reduced to /64, expiring with the window). It is not logged and not stored. The app Nginx log format and the backend request log have no address field; the edge access log records `$remote_addr`, as before, and is rotated by logrotate.
|
|
|
|
Check it with `make -C deploy check-perimeter` (renders the Compose files and asserts the published ports; reads the Nginx files for denied paths, limit order, headers, and the trusted peer; runs inside `make -C deploy check`) and `make -C deploy perimeter-test` (starts throwaway Nginx containers on a private Docker network with stub upstreams, publishes on 127.0.0.1 only, and checks over HTTP: SPA refresh, denied paths, headers, no CORS, 413 and 429 problems, spoofed `X-Forwarded-For` from an untrusted and from a trusted peer, and that the Nginx log has no client address). It also checks the cache and cross-origin headers, relative redirects, encoded and dot-segment variants of denied paths, and per-/64 IPv6 buckets. It runs `nginx -t` on the committed files unchanged. It does not start the Compose stack, so it does not exercise the real backend or the TLS edge. Rollout checklist for the first deployment behind the edge (not done yet; the tests above cannot prove it): (1) from two external client addresses, request `/api/v1/healthz` in a loop until one gets 429 and confirm the other still gets 200, which shows that the app Nginx sees the edge as `10.79.0.1` and resolves real clients; if both are limited together, the peer address differs from `AWG_EDGE_IP` and the header is being ignored; (2) confirm `X-Forwarded-Proto: https` reaches the backend (the session cookie carries `Secure`); (3) confirm `curl http://<app-host-tunnel-ip>:8080/metrics` answers 404. Manual browser step on a running stack: open a deep link and refresh it (the SPA loads), open the developer tools and confirm the response headers and no CSP violations in the console, and send a file larger than the limit with `curl -i -X POST --data-binary @big.bin -H 'Content-Type: application/octet-stream' http://127.0.0.1:8080/api/v1/<operation>` to see 413.
|
|
|
|
### Outbox relay
|
|
|
|
The backend runs the outbox relay in its own process next to the HTTP servers. The relay publishes committed outbox events to Kafka; its design is in [ARCHITECTURE.md](ARCHITECTURE.md#outbox-relay). Compose passes none of the settings below, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. A directly launched backend reads them from its environment. An invalid value stops startup.
|
|
|
|
| Variable | Default | Meaning |
|
|
| --- | --- | --- |
|
|
| `RELAY_ENABLED` | `true` | `true` or `false`. With `false`, or without `DATABASE_URL`, the relay does not run and events stay in the outbox. |
|
|
| `RELAY_BATCH_SIZE` | `100` | Events one pass locks and publishes, from 1 to 1000. |
|
|
| `RELAY_POLL_INTERVAL` | `1s` | Wait after a pass that found no pending event, from 10ms to 5m. |
|
|
| `RELAY_PRODUCE_TIMEOUT` | `10s` | Longest wait for the broker acknowledgements of one pass and for topic creation, from 1s to 2m. The pass keeps its transaction open for that long at most. |
|
|
| `RELAY_STATEMENT_TIMEOUT` | `5s` | Server-side `statement_timeout` of each SQL statement of a pass, from 100ms to 1m. The pass transaction also gets `idle_in_transaction_session_timeout` of `RELAY_PRODUCE_TIMEOUT` plus this value, so PostgreSQL ends the transaction of a frozen or disconnected backend and releases its locks. |
|
|
| `RELAY_BACKOFF_INITIAL` | `500ms` | Wait after the first failed pass; it doubles with each consecutive failure. |
|
|
| `RELAY_BACKOFF_MAX` | `30s` | Longest wait between retries, from `RELAY_BACKOFF_INITIAL` to 10m. |
|
|
| `KAFKA_EVENTS_TOPIC` | `lincodex.domain.events` | Topic for all domain events: up to 249 letters, digits, dots, underscores, or hyphens. |
|
|
| `KAFKA_EVENTS_TOPIC_PARTITIONS` | `3` | Partitions of a topic the relay creates, from 1 to 1000. |
|
|
| `KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR` | `-1` | Replication factor of a topic the relay creates: -1 takes the broker's `default.replication.factor`, otherwise from 1 to the broker count. |
|
|
| `KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS` | unset | `min.insync.replicas` of a topic the relay creates, at least 1 and not above an explicit replication factor. Unset leaves the broker default. |
|
|
| `KAFKA_PROVISION_TOPICS` | `true` | With `false` the relay never creates the topic, and every publish fails until the topic exists. |
|
|
|
|
`SHUTDOWN_TIMEOUT` also bounds the relay: a pass in progress at shutdown has that long to finish, otherwise it rolls back and its events stay pending. Compose gives the backend `stop_grace_period: 30s`, which covers the whole shutdown budget described under [Event consumers](#event-consumers), so Docker does not kill the process while a pass commits; raise it together with `SHUTDOWN_TIMEOUT`.
|
|
|
|
The single-node stand creates the topic with the broker defaults of the Compose Kafka: replication factor 1 and `min.insync.replicas` 1. That is acceptable only for this stand: one broker cannot replicate, and losing its volume loses the events. A production cluster needs at least three brokers, a replication factor of at least 3, and `min.insync.replicas` 2, either as broker defaults or through `KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR=3` and `KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS=2`. The producer always uses acks from all in-sync replicas, so with these values an acknowledged event survives the loss of one broker, and writes stop rather than land on a single replica when two of three brokers are down.
|
|
|
|
The relay creates a missing topic and never changes an existing one; when the existing topic has another partition count or replication factor than configured, the relay logs one warning. Adding partitions to the topic later moves aggregate keys to other partitions, so per-aggregate order is not guaranteed across that change.
|
|
|
|
When Kafka is unavailable, the backend still starts and serves the API. The relay logs warnings such as `outbox relay could not prepare the event bus` or `outbox relay pass failed` with the retry delay and keeps retrying; events stay in `outbox_events` until Kafka answers. In Compose the backend does not wait for the Kafka health check, so these warnings are expected during the first seconds after `make -C deploy up`. Relay logs carry the `outbox_relay` component and contain event IDs, counts, and broker errors, never payloads.
|
|
|
|
The internal /metrics endpoint shows the backlog: `lincodex_outbox_relay_pending_events` and `lincodex_outbox_relay_oldest_pending_age_seconds` are refreshed at most every 15 seconds, and `lincodex_outbox_relay_events_total` counts the `published` and `failed` outcomes. A growing age with a flat `published` count means the relay is stuck; the relay warnings name the event IDs, and [ARCHITECTURE.md](ARCHITECTURE.md#outbox-relay) describes the causes. Every backend instance reports the same backlog, so aggregate it with `max`. Published rows stay in `outbox_events`; their retention is not implemented yet.
|
|
|
|
### Event consumers
|
|
|
|
The backend runs one event consumer per registered handler in its own process next to the HTTP servers and the relay. A consumer reads `KAFKA_EVENTS_TOPIC` as a member of the group `<CONSUMER_GROUP_PREFIX>.<consumer name>`, applies each event once, and commits its offset only after the effect committed in PostgreSQL. The design is in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers). Current state: two product handlers are registered, `notification_delivery` (mail deliveries) and `notification_inbox` (internal notifications), so the backend runs one consumer in each of the groups `<CONSUMER_GROUP_PREFIX>.notification_delivery` and `<CONSUMER_GROUP_PREFIX>.notification_inbox` (`lincodex.notification_delivery` and `lincodex.notification_inbox` by default) when `CONSUMER_ENABLED` is true and `DATABASE_URL` is set. A new group starts at the earliest retained event of the topic, so the first start of `notification_inbox` after a deployment reads the retained events and ignores those of other types. Compose passes none of them, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. An invalid value stops startup, also with consumers disabled.
|
|
|
|
| Variable | Default | Meaning |
|
|
| --- | --- | --- |
|
|
| `CONSUMER_ENABLED` | `true` | `true` or `false`. With `false`, or without `DATABASE_URL`, no consumer runs, and events wait in Kafka for as long as the topic retains them. |
|
|
| `NOTIFICATION_SYNTHETIC_ENABLED` | `false` | `true` or `false`. Turns on the synthetic inbox event `notification.synthetic_delivered`: the `notification_inbox` consumer stores it and the inbox renders its fixed text. Leave it off in production; the browser E2E stand sets it. With `false` such an event is acknowledged and ignored, and a stored synthetic row is listed without content. The database CHECK allows the type either way. |
|
|
| `CONSUMER_GROUP_PREFIX` | `lincodex` | Prefix of every consumer group ID, up to 128 letters, digits, dots, underscores, or hyphens. Changing it starts new groups that read the topic from its earliest retained record; the dedup markers turn events that were already applied into duplicates. |
|
|
| `CONSUMER_MAX_ATTEMPTS` | `5` | Handler attempts for one event before it becomes a dead letter, from 1 to 20. Database failures outside the handler do not count. Must fit the rebalance budget below. |
|
|
| `CONSUMER_BACKOFF_INITIAL` | `500ms` | Wait after the first failed attempt; it doubles with each consecutive failure. |
|
|
| `CONSUMER_BACKOFF_MAX` | `10s` | Longest wait between attempts, from `CONSUMER_BACKOFF_INITIAL` to 5m. |
|
|
| `CONSUMER_HANDLER_TIMEOUT` | `5s` | Bound of one attempt and of one dead letter write, from 100ms to 5m. It is also the server-side `statement_timeout` and `idle_in_transaction_session_timeout` of the consumer transaction. |
|
|
| `CONSUMER_MAX_POLL_RECORDS` | `100` | Records of one poll, from 1 to 10000. A consumer processes them while it holds group rebalancing, so a smaller value shortens that hold. |
|
|
| `CONSUMER_COMMIT_TIMEOUT` | `5s` | Bound of one offset commit, from 100ms to 1m. |
|
|
| `CONSUMER_SHUTDOWN_GRACE` | `5s` | Time the record in progress has to commit after shutdown begins; at most `SHUTDOWN_TIMEOUT`. After it the transaction rolls back, the offset stays uncommitted, and the next member processes the record. |
|
|
| `CONSUMER_REBALANCE_TIMEOUT` | `60s` | Kafka rebalance timeout of every consumer group member, from 10s to 30m. Startup fails unless it exceeds the slowest record by 5 seconds. |
|
|
|
|
Rebalance budget. A consumer holds group rebalancing while it processes a poll, and a member that holds it longer than `CONSUMER_REBALANCE_TIMEOUT` is removed from the group, so its records are processed again by the next owner. The slowest record without a database outage takes `CONSUMER_MAX_ATTEMPTS` + 1 times `CONSUMER_HANDLER_TIMEOUT` (the attempts and the dead letter write), the longest backoff before each retry, and one `CONSUMER_COMMIT_TIMEOUT`. With the defaults that is 6 x 5s + (0.5 + 1 + 2 + 4)s + 5s = 42.5s, below 60s - 5s. A configuration that does not fit fails at startup with the computed value; lower the attempts or timeouts, or raise `CONSUMER_REBALANCE_TIMEOUT`, which also makes the group wait longer for a member that stopped responding. After every record that needed a retry or a dead letter the consumer commits at once, so only one slow record has to fit, not a whole poll.
|
|
|
|
Shutdown budget with the defaults:
|
|
|
|
1. In parallel: the HTTP servers drain within `SHUTDOWN_TIMEOUT` (10s); a relay pass gets the same 10s and up to 5s to roll back; every consumer gets `CONSUMER_SHUTDOWN_GRACE` (5s) for the record in progress, up to 5s to roll back a canceled transaction, and `CONSUMER_COMMIT_TIMEOUT` (5s) for its offsets. This phase ends after at most 15s.
|
|
2. Then all consumers leave their groups in parallel, each within `CONSUMER_COMMIT_TIMEOUT` plus 2s (7s), and the clients and pools close in about 1s.
|
|
|
|
That is about 23s regardless of the number of consumers. Compose gives the backend `stop_grace_period: 30s`, so Docker does not kill the process while a transaction commits; raise it when you raise `SHUTDOWN_TIMEOUT`, `CONSUMER_SHUTDOWN_GRACE`, or `CONSUMER_COMMIT_TIMEOUT`.
|
|
|
|
A consumer needs one PostgreSQL connection; all consumers of a process share one pool sized to their count. Several backend instances share a group's partitions, so at most `KAFKA_EVENTS_TOPIC_PARTITIONS` instances process a consumer's events at once; the others stay idle members.
|
|
|
|
Operators watch two counters on the internal /metrics endpoint. `lincodex_event_consumer_records_total{consumer,outcome}` counts finished records: `applied`, `duplicate` (expected after a redelivery), `ignored` (another event type), and `dead_lettered`. Alert on any increase of `dead_lettered`; every series exists at zero from the consumer's start, so `increase(...[15m]) > 0` fires on the first dead letter. `lincodex_event_consumer_failures_total{consumer,stage}` counts every failed operation, including the last handler attempt before a dead letter: a rising `store` count with flat `applied` means the consumer cannot reach PostgreSQL and its partition waits; a rising `handler` count means events keep failing; a rising `poll` count means the consumer cannot read Kafka (broker down, missing topic, or a group error); a rising `commit` count means offsets are not stored, so records will be delivered again after a restart or rebalance. Alert on `poll` or `commit` failures that continue for several minutes, for example `increase(...{stage=~"poll|commit"}[5m]) > 0` held for 10 minutes. Consumer logs carry the `event_consumer` component, the group, topic, partition, offset, event ID, and event type, never the record value. A dead letter is logged at error level as `event dead-lettered; the offset is committed and the record needs an operator` with the class and reason.
|
|
|
|
#### Dead letters and replay
|
|
|
|
A dead letter is a record the consumer gave up on so that its partition can continue. `error_class` says why:
|
|
|
|
- `invalid_record`: the value is not a valid event envelope. It did not come from the relay; find the producer that writes to the topic. It cannot be replayed as it is.
|
|
- `handler_rejected`: the handler reported that the event can never be applied, for example an unknown `schema_version`.
|
|
- `handler_panic`: the handler panicked; the log line `event handler panicked` with the same event ID holds the stack.
|
|
- `retries_exhausted`: the handler failed `CONSUMER_MAX_ATTEMPTS` times, for example because of a bug or a dependency it calls.
|
|
|
|
List them with psql in the database container (default `app` project):
|
|
|
|
docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \
|
|
exec postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"'
|
|
|
|
SELECT id, consumer_name, error_class, event_id, event_type, topic,
|
|
kafka_partition, kafka_offset, attempts, reason, dead_lettered_at
|
|
FROM consumer_dead_letters ORDER BY id;
|
|
|
|
The table holds no record value; `value_size` and `value_sha256` identify the value. Replay a dead letter only after its cause is fixed, usually by deploying a corrected handler:
|
|
|
|
1. Replay one event from the outbox. For a dead letter with an `event_id` and a class other than `invalid_record`, publish the event again:
|
|
|
|
UPDATE outbox_events SET published_at = NULL WHERE event_id = '<event_id>';
|
|
|
|
The relay publishes it again with the same `event_id` at a new offset. Every consumer receives it: those that applied it find their marker and count a `duplicate`, and the consumer that failed applies it, because a dead letter writes no marker. This works as long as the outbox row exists (published rows are not deleted yet), also after Kafka dropped the original record. The event can arrive after later versions of its aggregate; handlers ignore versions they have already passed.
|
|
2. Or rewind the group while Kafka still retains the record. Kafka resets offsets only for an empty group, so stop every member first (stop the backend instances or set `CONSUMER_ENABLED=false`). A member that was killed instead of stopped stays in the group until its session timeout (45 seconds by default) ends; run the command below with `--describe` instead of the reset options and wait until it lists no active member. Then:
|
|
|
|
docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \
|
|
exec -e KAFKA_HEAP_OPTS=-Xmx128m kafka /opt/kafka/bin/kafka-consumer-groups.sh \
|
|
--bootstrap-server localhost:9092 --group lincodex.<consumer> \
|
|
--topic lincodex.domain.events:<partition> --reset-offsets --to-offset <offset> --execute
|
|
|
|
The group then reads that partition again from the offset. Records it already applied are duplicates; other dead letters in the range are attempted again, and one that fails again updates its row with the new class, reason, and attempt count instead of adding another. `--describe` also shows the group's offsets and lag.
|
|
3. Check the result and close the dead letter: the event is applied when `SELECT 1 FROM consumer_processed_events WHERE consumer_name = '<consumer>' AND event_id = '<event_id>'` returns a row. Then delete the row with `DELETE FROM consumer_dead_letters WHERE id = <id>`, or keep it as a record of the incident.
|
|
|
|
To inspect an `invalid_record` while the topic retains it, read exactly that record with `kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic <topic> --partition <partition> --offset <offset> --max-messages 1` and compare its SHA-256 with `value_sha256`. The value can contain personal data, so do not paste it into tickets or chats.
|
|
|
|
### Scheduled jobs
|
|
|
|
The backend runs the scheduled job worker as a goroutine of the backend process next to the HTTP servers, the relay, and the consumers. It runs jobs that usecases scheduled in their transactions once they fall due; the design is in [ARCHITECTURE.md](ARCHITECTURE.md#scheduled-jobs). Current state: one product kind is registered, `assessment.signal_review` (see [Assessment review band](#assessment-review-band)), so the worker runs when `JOBS_ENABLED` is true and `DATABASE_URL` is set; the settings below are validated in any case. Compose passes none of the settings, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. A directly launched backend reads them from its environment. An invalid value stops startup, also with the worker disabled.
|
|
|
|
| Variable | Default | Meaning |
|
|
| --- | --- | --- |
|
|
| `JOBS_ENABLED` | `true` | `true` or `false`. With `false`, or without `DATABASE_URL`, no job runs; due jobs wait in `scheduled_jobs` and run after the worker starts again, with their original `due_at`. |
|
|
| `JOBS_POLL_INTERVAL` | `1s` | Wait after a pass that claimed less than a full batch, from 10ms to 5m. It is also the usual delay of a job after its due time. |
|
|
| `JOBS_BATCH_SIZE` | `10` | Jobs one claim leases, from 1 to 100. They run one after another under leases taken together, so a batch should finish well within one lease. |
|
|
| `JOBS_LEASE_DURATION` | `1m` | How long a claimed job belongs to one worker, from 1s to 1h. It bounds one handler attempt and is the server-side `statement_timeout` and `idle_in_transaction_session_timeout` of the job transaction. A worker that crashed delays its jobs by at most this long. |
|
|
| `JOBS_MAX_ATTEMPTS` | `5` | Attempts of a job scheduled without its own limit before it is dead, from 1 to 100. Database failures outside the handler and shutdown do not count. |
|
|
| `JOBS_BACKOFF_INITIAL` | `1s` | Delay before the first retry of a failed job; it doubles with each failed attempt. The same backoff spaces claims while the database fails. |
|
|
| `JOBS_BACKOFF_MAX` | `5m` | Longest delay before a retry, from `JOBS_BACKOFF_INITIAL` to 24h. |
|
|
| `JOBS_SHUTDOWN_GRACE` | `5s` | Time the job in progress has to commit after shutdown begins; at most `SHUTDOWN_TIMEOUT`. After it the transaction rolls back and the job is released unfinished. |
|
|
|
|
Due times and leases are compared with the backend clock, not the database clock, so keep the hosts of all backend instances synchronized with NTP. A clock ahead runs jobs early and takes over leases early; the row lock still prevents a second run while a handler is in progress.
|
|
|
|
Shutdown budget. The worker stops in parallel with the other workers: `JOBS_SHUTDOWN_GRACE` (5s) for the job in progress, up to 5s to roll back a canceled transaction, and up to 5s to release the unfinished jobs, 15s at most. This fits the first phase of the budget under [Event consumers](#event-consumers), so the total stays about 23s within `stop_grace_period: 30s`; raise that together with `JOBS_SHUTDOWN_GRACE`. If the backend is killed instead, its jobs stay `running` until their leases expire and then run on another instance or after the restart.
|
|
|
|
The worker uses its own PostgreSQL pool of at most two connections. Several backend instances share the jobs: each claim skips rows that another instance locks, and every instance can run every registered kind.
|
|
|
|
Operators watch `lincodex_scheduled_jobs_total{kind,outcome}` on the internal /metrics endpoint: `done`, `retry` (an attempt failed and the job waits for its backoff), `dead`, `lease_lost` (the job was canceled or reclaimed while this instance held it), and `released` (given back unfinished at shutdown or after a database failure). Every series exists at zero from the start, so alert on `increase(lincodex_scheduled_jobs_total{outcome="dead"}[15m]) > 0`. `lincodex_scheduled_jobs_due` and `lincodex_scheduled_jobs_oldest_due_age_seconds` describe due jobs that wait for a worker; an age that keeps growing beyond a few poll intervals means no instance claims them, for example because the worker is disabled, the database fails, or no running instance has the handler of their kind. `lincodex_scheduled_jobs_dead` counts dead jobs. Every instance reports the same database-wide gauges, so aggregate them with `max`. During a rolling deployment that adds a new kind, its jobs that already fell due wait until an instance with the handler runs, and the age can briefly look like a stuck worker; hold an age alert for longer than a deployment takes. Logs carry the `scheduled_jobs` component, the lease owner, job ID, kind, attempt, and error class, never the key or payload; a dead job is logged at error level as `scheduled job is dead; it needs an operator`.
|
|
|
|
#### Dead jobs
|
|
|
|
`last_error_class` says why a job is dead: `handler_rejected` (the handler can never run it), `handler_panic` (the log line `scheduled job handler panicked` with the same job ID holds the stack), `lease_expired` (its last started attempt stopped without finishing, usually a crash or a kill, or its failure could not be recorded because the database failed at that moment), or the class of the last failed attempt after the attempts ran out: `handler_failed`, `timeout`, `conflict`, or `effect_rejected`. `completion_conflict` means the handler changed its own job other than by canceling it. List dead jobs and jobs that are overdue with psql in the database container (see [Dead letters and replay](#dead-letters-and-replay) for the command that opens it):
|
|
|
|
SELECT id, kind, dedup_key, attempts, max_attempts, last_error_class,
|
|
due_at, available_at, updated_at
|
|
FROM scheduled_jobs WHERE status = 'dead' ORDER BY updated_at;
|
|
|
|
SELECT kind, status, count(*), min(available_at)
|
|
FROM scheduled_jobs
|
|
WHERE status IN ('pending', 'failed', 'running') AND available_at <= now()
|
|
GROUP BY kind, status;
|
|
|
|
The key identifies a product record, such as an invitation ID; the payload holds identifiers only. After the cause is fixed, usually by deploying a corrected handler, run a dead job again. Change only `available_at`, never `due_at`: the handler decides by the deadline in `due_at`.
|
|
|
|
UPDATE scheduled_jobs
|
|
SET status = 'failed', attempts = 0, available_at = now(), updated_at = clock_timestamp()
|
|
WHERE id = <id> AND status = 'dead';
|
|
|
|
A worker claims it within one poll interval and runs it with fresh attempts. To give a dead job up, set `status = 'cancelled'` with the same guard; its key stays reserved, so the product flow cannot schedule it again. Do not delete rows: a deleted key can be scheduled again and run a second time.
|
|
|
|
## Mail
|
|
|
|
The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects exactly one transport: `resend` (the Resend HTTP API, the primary provider for the working stand), `smtp` (a separate SMTP relay), or `disabled`. It has no default, and there is no fallback: when the selected transport cannot start, the backend stops instead of switching to another one. Settings of transports that are not selected are not read.
|
|
|
|
Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. With `EMAIL_PROVIDER=resend`, the backend runs a worker for service identity mail (email verification and password reset), and registration queues a verification email. Password reset is not implemented. Product notifications are sent by a separate notification worker: it leaves a quota reserve to service mail and checks the recipient's rights again before every send (see [ARCHITECTURE.md](ARCHITECTURE.md)). See [Sending service mail](#sending-service-mail).
|
|
|
|
Release compatibility: `ConfirmEmail` requires both `token` and the password selected for that registration. Clients that send only the token must be updated. Migration `00016_bind_registration_consent.sql` adds the registration version to C1 and backfills legacy records from the current account version without requiring a live token. It checks that a registration C1 is not older than the latest registration and that an account has at most one active registration C1; on inconsistency, the migration stops without partial changes. A trigger fills the version when an old backend omits it and rejects a mismatched version sent by the new backend. A partial unique index allows at most one unrevoked registration C1 per account and registration version. Apply the migration before updating the backend. To roll back, deploy the old backend before reverting the migration. No new environment variable is needed. `APP_PUBLIC_URL` also defines the Origin that confirmation requests must send. The new `ConfirmEmailByCode` operation (`POST /api/v1/identity/email-verifications/code`) and migration `00046_add_email_verification_codes.sql` are additive: existing clients keep confirming by link. The migration can be rolled back once no usable code is left; its down step refuses until then.
|
|
|
|
`resend` sends each message with one request to `https://api.resend.com/emails`. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in `EMAIL_FROM` shows up as a rejected send. One attempt is limited by `EMAIL_TIMEOUT`. The transport follows no redirects, never retries, and logs nothing; the sending worker owns retries, backoff, rate-limit pacing, and outcome records, while the quota gate schedules a known daily or monthly reset (see [Mail quotas](#mail-quotas)). Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is `unknown` (`delivery_uncertain`), not a failure. The backend process follows the standard `HTTPS_PROXY` and `NO_PROXY` variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend `environment`. The full mapping of answers is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport).
|
|
|
|
`disabled` sends nothing. Every send returns `ErrMailChannelUnavailable` without a provider message ID and is never reported as accepted or delivered. It does not confirm an email address, mark an account verified, or skip an account check. The startup log contains `mail transport selected` with `email_provider` and, for `disabled`, a `mail delivery is disabled` warning.
|
|
|
|
| Variable | Default | Validation |
|
|
| --- | --- | --- |
|
|
| `EMAIL_PROVIDER` | none, required | `resend`, `smtp`, or `disabled`, case-insensitive |
|
|
| `EMAIL_FROM` | none, required | One mailbox: `no-reply@example.com` or `Lincodex <no-reply@example.com>`. Printable ASCII only. The address follows the account address rules: unquoted local part and a DNS domain with at least two labels, no IP literal. |
|
|
| `EMAIL_ACCOUNT` | `default` | Label of the provider account that new deliveries are pinned to and that the quota is counted under: 1 to 64 lowercase letters, digits, `.`, `_`, or `-`, starting with a letter or digit. Never the key. Change it only with a real account change; renaming it resets the local quota count. |
|
|
| `EMAIL_TIMEOUT` | `10s` | Go duration from `1s` to `1m`; limits one transport attempt |
|
|
| `EMAIL_QUOTA_DAILY` | `100` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC day through the configured provider account: an integer from 1 to 1000000000. Empty counts as unset. No value turns the quota off. |
|
|
| `EMAIL_QUOTA_MONTHLY` | `3000` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC calendar month: an integer from 1 to 1000000000, not below `EMAIL_QUOTA_DAILY`. Empty counts as unset. |
|
|
| `EMAIL_SERVICE_RESERVE_DAILY` | A fifth of `EMAIL_QUOTA_DAILY`, for example 20 on the Resend Free plan | Recipients per UTC day that product notifications leave free for service mail: an integer from 0 to below `EMAIL_QUOTA_DAILY`. Empty counts as unset. A notification is admitted only while the day keeps this many recipients free after it. |
|
|
| `EMAIL_SERVICE_RESERVE_MONTHLY` | A fifth of `EMAIL_QUOTA_MONTHLY`, for example 600 on the Resend Free plan | The same for the UTC calendar month: an integer from 0 to below `EMAIL_QUOTA_MONTHLY`. Empty counts as unset. |
|
|
| `APP_PUBLIC_URL` | none, required | Public origin for mail links and exact Origin checks on unsafe public identity and protected operations: `https://host[:port]`, or `http` only for `localhost`, `127.0.0.1`, or `[::1]`. No credentials, path, query, or fragment; one trailing `/` is dropped. |
|
|
| `RESEND_API_KEY` | empty | Read only for `resend`, where it is required. Printable ASCII without whitespace. The `re_` prefix shown in Resend examples is not enforced. |
|
|
| `SMTP_HOST` | empty | Read only for `smtp`, where it is required. Hostname or IP address without a port. |
|
|
| `SMTP_PORT` | empty | Required for `smtp`. Integer from 1 to 65535. |
|
|
| `SMTP_USERNAME`, `SMTP_PASSWORD` | empty | Required for `smtp`; an anonymous relay is not supported. |
|
|
| `SMTP_TLS_MODE` | empty | Required for `smtp`. `starttls` (upgrade with STARTTLS, usually port 587) or `tls` (TLS from the start, usually port 465). Plaintext SMTP is not supported. |
|
|
|
|
Compose passes these variables from the root `.env`; it passes an unset `EMAIL_QUOTA_DAILY` or `EMAIL_QUOTA_MONTHLY` as an empty value, which the backend reads as unset. The same holds for `EMAIL_SERVICE_RESERVE_DAILY` and `EMAIL_SERVICE_RESERVE_MONTHLY`. `EMAIL_PROVIDER`, `EMAIL_FROM`, and `APP_PUBLIC_URL` are required, so Compose refuses to render the project without them; copy the mail block from `.env.example` into an existing `.env`. Keep `RESEND_API_KEY` and `SMTP_PASSWORD` in the server environment or a deployment secret store and never commit them. Configuration errors name the setting but never print its value, and the startup log names only the selected provider.
|
|
|
|
### Mail deliveries
|
|
|
|
A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; migration 00017 adds the unknown-outcome decision journal and rebuilds the due partial index under a table lock. Rolling 00017 back drops that journal and its audit history, so export the decisions before rollback. Neither migration needs a setting. Notification deliveries are sent by a separate notification worker through its own queue; the service mail worker still claims verification and password reset mail only. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line.
|
|
|
|
- Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Service mail created while `EMAIL_PROVIDER=disabled` stays pinned to `disabled` until the backend runs with a transport: the sending worker then moves it with `Rebind` (allowed only before the first attempt) and sends it if its token and account still pass the check. Do not rebind by hand. Product notifications follow the same rule, and their loop rebinds them the same way.
|
|
- The rows hold the recipient address and the rendered bodies, and a waiting `mail_requests` row holds the raw notification text; verification and password reset bodies hold a live one-time token until it is used or expires. Treat read access to `deliveries` like access to those links, and keep database dumps and backups under the same protection. Retention of finished deliveries is not implemented yet.
|
|
- To inspect deliveries, select metadata only, for example `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50`, and `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '<id>' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` shows requests the consumer has not handled yet; a growing count means the consumer is stopped or its events are dead-lettered. Do not select `recipient_email`, `subject`, `text_body`, `html_body`, or the `mail_requests` text columns, and never paste them into tickets or chats.
|
|
- Without SQL, the internal /metrics endpoint shows `lincodex_mail_deliveries{kind,status}` for every kind and status, zero included, and `lincodex_mail_delivery_oldest_due_pending_age_seconds`, the time the earliest pending delivery has been due. The backend reads them every 30 seconds with one aggregate over `deliveries`; every instance reports the same values, so aggregate them with `max`. A read that fails keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`. Notifications stay `pending` until product notification sending is implemented; they are not counted in the due age. The age series appears only after the first successful read, so a fresh start never claims that nothing is late; `lincodex_mail_metrics_last_success_timestamp_seconds` is the Unix time of the last read in which every aggregate was read (0 from the start until the first one), and `LincodexMailMetricsStale` fires when it is more than 5 minutes old for 5 minutes. The alert `LincodexMailDeliveryUnknownOutcome` fires while any delivery has an unknown outcome. `LincodexMailDeliveriesOverdue` (a pending delivery due for more than 15 minutes) also requires `lincodex_mail_sender_running` to be 1 on some instance: the sending worker exports it, 1 while its loop runs and 0 otherwise, so the alert stays silent with `EMAIL_PROVIDER=disabled` (no loop starts) and without traffic. The age counts only service mail (verification and password reset), so a backlog of notifications, which the worker does not send until product notification sending is implemented, does not fire it. The status `cancelled` is counted like the others, and `accepted` means accepted by the provider.
|
|
- Do not edit a stored delivery by hand: a trigger refuses any change to the recipient, content, or idempotency key and a change of the provider account after the first attempt, and the attempt history refuses updates. A delivery in `waiting_quota` waits for the quota reset at `next_attempt_at`; see [Mail quotas](#mail-quotas). Without `next_attempt_at` its reset is unknown and it needs an operator decision.
|
|
- Logs name a delivery only by `delivery_id` (with the event ID), never by address or subject. Skipped requests are logged at info level: `mail request skipped because it was already handled or its account was deleted` and `notification skipped because the recipient address is not verified`. A request that breaks the event contract is a `handler_rejected` dead letter of the consumer `notification_delivery`; see [Dead letters and replay](#dead-letters-and-replay). Replaying it is safe: the delivery ID keeps one delivery per request.
|
|
|
|
### Mail quotas
|
|
|
|
Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quota_reservations` at startup; it needs no setting. The sending worker calls the quota gate around every send (see [Sending service mail](#sending-service-mail)), so service mail counts against the quota and notifications do not until product notification sending is implemented. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas).
|
|
|
|
- Set `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` to the plan of the provider account named by `EMAIL_ACCOUNT`. The defaults are Resend Free: 100 recipients per UTC day and 3000 per month, as checked on 2026-10-05. Check the account's current quota in the Resend dashboard before the stand goes live and after any plan change. With `smtp`, set both to the relay's limits; startup fails without them. A changed value applies after a restart. The service reserve (`EMAIL_SERVICE_RESERVE_DAILY` and `EMAIL_SERVICE_RESERVE_MONTHLY`) keeps part of each window for service mail: product notifications are admitted only while the window keeps the reserve free after them, and they take a fifth of each limit by default.
|
|
- Change `EMAIL_ACCOUNT` only together with a real change of the provider account, that is, a key of another account. The local count is kept per account label, so renaming the label for the same account starts a new count from zero while the provider keeps the old one. At startup the backend logs `mail quota usage` with the provider, account, and the current day and month usage and limits, and warns when other labels of the same provider have usage this month.
|
|
- When a quota is used up, deliveries wait in `waiting_quota` until `next_attempt_at`: the next 00:00 UTC for the day, the first day of the next month at 00:00 UTC for the month. Nothing buys a plan, switches the account to a paid tier, or moves mail to another transport or account. The account itself can see that its mail waits and until when through the status reader described in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas); no HTTP route shows it yet.
|
|
- To see the state, select only counters and metadata, for example `SELECT provider, provider_account, period_kind, period_start, used_recipients, provider_exhausted_at FROM mail_quota_usage ORDER BY period_start DESC, period_kind LIMIT 10`, `SELECT count(*), min(next_attempt_at) FROM deliveries WHERE status = 'waiting_quota'`, and, for sends that were counted but never settled, `SELECT count(*), min(reserved_at) FROM mail_quota_reservations WHERE settled_outcome IS NULL AND released_at IS NULL`. Logs show `mail quota is used up; the delivery waits for the reset` and, when the provider itself refused, `the mail provider reported its quota used up; local sending stops until the reset`.
|
|
- The internal /metrics endpoint shows the current windows of the configured account, read every 30 seconds: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted` (1 after a quota refusal by the provider), each with the labels `provider` and `window` (`day` or `month`). `EMAIL_ACCOUNT` is not a label, because the operator chooses its text; with `EMAIL_PROVIDER=disabled` there are no quota series. The alert `LincodexMailQuotaUsedUp` (severity info) fires while a window is used up. `lincodex_mail_sender_running` reports the service loop of the process, and `lincodex_notification_sender_running` the product notification loop; both are 0 with `EMAIL_PROVIDER=disabled`.
|
|
- Choices while mail waits: wait for the reset, which needs no action; or, after a deliberate plan change with the provider, raise the limits and restart the backend, so new sends are admitted again while parked deliveries keep their stored `next_attempt_at`; or deliberately switch the transport or account (see [Mail deliveries](#mail-deliveries) for what stays pinned). Do not lower `used_recipients` or edit the journal by hand to free sends: the provider keeps its own count, so the sends would only be refused.
|
|
- `provider_exhausted_at` on a row means that the provider refused with a quota answer while the local count still had room. Possible reasons: the account also sends from elsewhere; Resend counts received (inbound) mail against the same quota; or the configured limit is above the plan. Align the limits with the plan.
|
|
- Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. The local operator command is for terminal unknown outcomes, not quota-waiting deliveries.
|
|
- Lowering a limit takes effect on the next reservation. During a rolling deploy, instances with the old and the new limits run side by side and each checks the limit it was started with, so a lowered limit holds only once every instance runs the new configuration. Switching `EMAIL_PROVIDER` to `smtp` starts separate counters for the relay under its own stated limits; deliveries pinned to the old account are refused by the gate rather than sent without a limit.
|
|
|
|
### Sending service mail
|
|
|
|
The backend process runs one sending loop for service identity mail (email verification and password reset). It starts with the backend when `EMAIL_PROVIDER` is `resend` and `DATABASE_URL` is set, shares the database with the other workers on a pool of two connections, and needs no setting of its own: the poll interval (5 seconds), the lease on a claimed delivery (`EMAIL_TIMEOUT` plus one minute), the shutdown grace (5 seconds), the retry schedule (1 minute doubling to 30 minutes), and the failure backoff (5 seconds doubling to 2 minutes) are constants in `backend/internal/bootstrap/mail_sender.go`. Migration 00012 adds its columns; the model, the checks, and the outcomes are in [ARCHITECTURE.md](ARCHITECTURE.md#sending-service-mail).
|
|
|
|
- Several backend instances may run at once. Each claims a delivery with `FOR UPDATE SKIP LOCKED` and a lease, so one delivery is sent by one instance, and the provider call carries the stable idempotency key `delivery/<id>`. During a rolling deployment the instance that stops finishes its send within 5 seconds, stores the result, and exits.
|
|
- With `EMAIL_PROVIDER=disabled` the loop does not start and the log says `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`; `lincodex_mail_sender_running` is 0, nothing is sent, and stored service mail waits for the next start with a transport. The worker never spins: after a pass that could not send it backs off.
|
|
- Before it sends, the worker checks the token and the account. A delivery that must not go out ends as `cancelled` with a `cancel_reason`, no attempt, and no quota use: `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, or `processing_failed`. The user-caused reasons are normal: a user asked for a new link, confirmed the address, registered again, or waited too long. To see the reasons: `SELECT cancel_reason, count(*) FROM deliveries WHERE status = 'cancelled' GROUP BY cancel_reason`. A user sees a cancelled mail as "not sent, request a new one".
|
|
- Provider answers: `accepted` means accepted by the provider, not delivered to a person; the backend has no delivery confirmation. A confirmed temporary or 429 refusal means the provider did not accept the message: it leaves the delivery `pending` with a later `next_attempt_at`, and the retry reuses the pinned account, key, and body. Resend's `Retry-After` is a lower bound. Such a refusal does not erase uncertainty from an earlier unknown attempt. After the 23-hour cutoff, confirmed refusals continue only under a pending manual decision; without it, the worker stops and leaves the earlier unknown for operator review. A permanent or invalid-request refusal ends it as `rejected`: read the provider code in `delivery_attempts.provider_code` (for example `validation_error` for an unverified sender domain, or `invalid_api_key`) and fix the cause. A quota answer parks it in `waiting_quota`; see [Mail quotas](#mail-quotas).
|
|
- An uncertain Resend outcome is retried automatically with the same pinned account, key, and stored body only until 23 hours after the database-recorded first send, one hour before the provider's documented 24-hour idempotency expiry. The worker checks this cutoff again immediately before the network call. After the cutoff, or after a manually authorized send-start whose result is lost, automatic retries stop and the alert `LincodexMailDeliveryUnknownOutcome` asks for review. Check the provider's own log first. For a terminal `unknown` row, use `make -C backend mail-retry ARGS='inspect --delivery <uuid>'` to see metadata and the duplicate warning, then `make -C backend mail-retry ARGS='retry --delivery <uuid> --actor operator:<handle> --acknowledge-duplicate-risk'` to schedule one audited decision. The command requires the local database credential, is available only with `EMAIL_PROVIDER=resend`, prints its warning before changing state, and never sends mail. The actor is an audit handle rather than authentication, and there is no HTTP operator endpoint. A manual decision does not restart the provider's key window: after another unknown or lost manual send result, the worker stops and requires another decision. An expired idempotency key may produce a duplicate despite the warning.
|
|
- A claimed delivery holds a lease: `SELECT id, kind, claimed_until FROM deliveries WHERE claim_owner IS NOT NULL`. A row whose `claimed_until` is long past means that its worker died; another instance takes it over by itself. Do not clear leases by hand.
|
|
- `content_invalid` and `processing_failed` are not user actions: the first means that a stored row does not match its content hash (a manual edit) or holds a message no transport accepts, the second that the worker failed on the row three times in a row (the retries are spaced by the retry schedule). The alert `LincodexMailCancelledBroken` fires on an increase; read the worker logs for the `delivery_id` and inspect the row's metadata. A row that keeps failing does not block the others: it is retried later (`failure_count`, `next_attempt_at`) and then cancelled.
|
|
- The bodies of a token mail are cleared when it is accepted, rejected, or cancelled (`body_redacted_at` is set), so database dumps and backups of finished token mail hold no token. A mail that is `unknown` keeps its body until an operator resolves it. The retry command displays no address, body, key, or token. Do not copy bodies of waiting mail anywhere.
|
|
- The lease is measured by the database clock, so clock differences between instances do not matter; only the database's clock does. The call to the provider is bounded by what is left of the lease; with `SHUTDOWN_TIMEOUT` at its default of 10 seconds a stopping instance finishes within 3 seconds of grace plus 5 seconds to store the answer. Lowering `SHUTDOWN_TIMEOUT` shortens the second part (at least 1 second); a result that cannot be stored in time is covered by the takeover.
|
|
- Logs name a delivery only by `delivery_id`, its kind, and the outcome or cancel reason, for example `service mail was not sent because it is no longer valid`; never an address, a token, a link, or a body. If a token or link appears in a log, treat it as a defect.
|
|
- The internal /metrics endpoint shows `lincodex_mail_sender_running` (1 while this instance's loop runs, 0 otherwise; no labels) and `lincodex_mail_sender_cancelled_total{reason}` (a counter per cancel reason, zero included) next to the delivery gauges, which also have the status `cancelled`.
|
|
|
|
### Mail templates
|
|
|
|
Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate/` with templates for email verification, password reset, and a short notification. The delivery consumer renders notifications when it stores a delivery, and `ServiceMailer` creates verification mail during registration. Email confirmation is implemented in the API and frontend. The password reset flow is still planned.
|
|
|
|
- Templates are embedded in the binary with `go:embed` and parsed once when the renderer is created; a broken template fails its creation. Each version has three files: `<kind>.v<N>.subject.tmpl`, `<kind>.v<N>.txt.tmpl`, and `<kind>.v<N>.html.tmpl`. The HTML part uses `html/template`, the plain-text part and the subject use `text/template`. Every transport sends the same rendering; templates hold no provider settings, keys, or sender address.
|
|
- Links start with `APP_PUBLIC_URL`, which the renderer checks again with the same rules. Verification: `<APP_PUBLIC_URL>/verify-email#token=<token>`; password reset: `<APP_PUBLIC_URL>/reset-password#token=<token>` (the page and the API for the reset are planned). The token is only in the URL fragment, never in the path or the query: a browser does not send the fragment to a server, so the nginx access log (which records `$uri`) and Referer headers never hold it. The frontend reads and removes the fragment, waits for explicit user action, then sends the token and registration password to the API. A notification link is a path inside the application, such as `/candidate/invitations`; an absolute URL, `//host`, a scheme such as `javascript:`, a query, a fragment, a percent sign, and `.` or `..` segments are rejected.
|
|
- Messages contain no name, email address, or other contact. Caller text in a notification is escaped in the HTML part; control and bidirectional characters are removed from the plain-text part, and the subject becomes one line, so CR and LF cannot add header lines. The notification subject is limited to 100 characters and the body to 2000.
|
|
- The HTML part uses table layout with inline styles only: no `<style>` block, external stylesheets, web fonts, images, or tracking pixels. Apart from the action link the message already carries, the HTML has no links. The header is dark with the text wordmark Lincodex and a blue caret; the body is a light card with dark text. Every text and background pair meets WCAG AA both with the designed colors and when a client inverts them. The footer states why the message was sent.
|
|
- Copy is in Russian. A released version is immutable: changing copy adds the next version, for example `verification.v2`, and switches the current version in code. Versions share no files, so one version cannot change the body of another. Each rendering carries its version and a SHA-256 content hash over the version, subject, and both parts; the same version and data always give the same body. A delivery stores the rendered body with the hash, and a retry sends the stored body instead of rendering again, so a new version applies to new deliveries only and an old version's files are not needed to send a stored delivery.
|
|
- The renderer does not log. A rendering and notification data print only the kind, version, and content hash in `fmt` and `slog` output; tokens, links, and bodies are never printed.
|
|
- Golden files in `testdata/` make every copy change visible in review. After an intended change, run `go test ./internal/usecase/notification/mailtemplate -update` from `backend/` and review the diff.
|
|
|
|
## Assessment review band
|
|
|
|
The server computes a manual-review band (`normal`, `attention`, `review`) for real assessment attempts from the server signals and the policy version pinned to the attempt (see [ARCHITECTURE.md](ARCHITECTURE.md#assessment-signals-and-the-review-band)). The band is a hint for a person who checks an attempt by hand. It changes no result, category, or quota, and no HTTP endpoint serves it. Until staff roles exist, an operator reads it with a local command:
|
|
|
|
```sh
|
|
make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operator:<handle>'
|
|
```
|
|
|
|
- The band is computed by the scheduled job kind `assessment.signal_review`, never in a candidate's request. The jobs are inserted into `scheduled_jobs` with the first answer (due one minute after the deadline of the attempt) and with finalization (due at once). The worker must run (`JOBS_ENABLED=true`, [Scheduled jobs](#scheduled-jobs)); with the worker off the reviews wait with their jobs and no result is affected. A failed job is retried with the worker's backoff; a dead job (see [Dead jobs](#dead-jobs)) leaves the attempt without a refreshed review and does not touch its result.
|
|
- The command needs `DATABASE_URL` and reads nothing else from the environment or a dotenv file; the local database credential is its operator boundary. `make -C backend assessment-review-build` builds `backend/bin/assessment-review`.
|
|
- It prints the attempt ID, the band, the reason codes, the policy version, the evaluation and update times, and the counts behind the band. It prints no answer, address, session, candidate, or contact data, and it never names another candidate of a duplicate match.
|
|
- Every read is recorded in `assessment_review_reads` (attempt ID, actor handle, found or missing, database time) in the same transaction as the read, also when the attempt has no review. The table refuses UPDATE, DELETE, and TRUNCATE. The actor is an audit handle, not authentication: any holder of the database credential can type any handle. Rolling migration 33 back is refused while the audit holds a row; export or resolve it first.
|
|
- A band can be missing for a real reason: the policy version of the attempt has no `assessment.signals` section, the review job has not run yet, or the attempt has neither ended nor reached its deadline.
|
|
- A review is updated in place when a later attempt matches one of its answers; the policy version and the first evaluation time stay.
|
|
- Capture hints and the one-window rule add three counts to this output (`extra_agents`, `client_screenshot_keys`, `client_devtools_opens`) and the reason `extra_agents`; they raise the band only through optional thresholds of the policy section (`client_screenshot_keys_attention`, `client_devtools_attention`, `extra_agents_attention`, `extra_agents_review`), which a version published earlier does not have and the demo policies do not set. The rows that hold them are the same kind of data as the others: keyed digests and counts, and no User-Agent, page identifier, address, or image. A screenshot or a phone photo cannot be prevented or seen, so these signals lead only to a manual check, never to an automatic downgrade ([details](ARCHITECTURE.md#capture-hints-one-open-window-and-what-they-cannot-do)). Rolling migration 50 back is refused while the new events, marks, or counts exist.
|
|
- To use thresholds other than the demo values, publish a policy version with an `assessment.signals` section through the policy publisher. `DemoProductPolicyV3` is the demo example and is published only explicitly (the isolated browser fixture does so); the startup seed publishes version 1 only. Attempts that already started keep the version they started with. The demo duplicate thresholds assume a population: a copied pair is flagged only from about 26 answers per family (attention) and 61 (review) at 13 items, or 9 and 14 at 23 items. To try the feature on a smaller stand, publish a policy version with lower `duplicate_bits_attention` and `duplicate_bits_review` (the integration tests use 4 and 6); do not edit the demo policy. A review is a point-in-time evaluation, run again by the job at the deadline. The job logs one line per run with the number of reviews and its duration (`assessment review job finished`).
|
|
- The rows hold counts, durations, and keyed digests (HMAC-SHA-256 under keys derived from `IDENTITY_KEY_SECRET`, each with a key version) and no answer text. Rotating the secret keeps the stored rows but makes new fingerprints incomparable with old ones. Deleting an account deletes its attempts and, by cascade, their facts and reviews; the audit rows keep only the attempt ID and the handle. The digests are kept for the lifetime of the attempt; no retention period is defined yet.
|
|
|
|
## Leak trace
|
|
|
|
An operator finds the attempt behind a leaked task text with a local command (see [ARCHITECTURE.md](ARCHITECTURE.md#leak-trace) for how it decides). It takes text; a screenshot has to be read by an OCR tool first, which is not part of this project:
|
|
|
|
```sh
|
|
make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --file leaked.txt'
|
|
pbpaste | make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --stdin'
|
|
make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --code 7K3QD-9XM2T'
|
|
```
|
|
|
|
- The command needs `DATABASE_URL` and `IDENTITY_KEY_SECRET`, and reads nothing else from the environment or a dotenv file. The secret must be the one of the server that served the attempts: the codes and marks are computed from it, so a different secret finds nothing, and the command refuses an unset, placeholder, or short secret and never prints it. `make -C backend assessment-leak-trace-build` builds `backend/bin/assessment-leak-trace`.
|
|
- Put the text in a file or on standard input, not in a command-line argument, so that it stays out of the shell history and the process list. The text is at most 64 KiB of UTF-8; a longer one is refused, and a document can be searched in pieces. `--code` takes a visible code that was read from a screenshot by eye, with or without the hyphen and in either case.
|
|
- It prints the search ID, `found`, `ambiguous`, or `not_found`, and for a found search the method (`invisible_mark`, `visible_code`, `wording`, or `variant`), the attempt ID, and the strength in bits, with notes that never quote the text. `not_found` is a normal outcome, not an error: the data was not enough to name an attempt.
|
|
- Every search is recorded in `assessment_leak_traces` (operator handle, database time, a keyed digest and the length of the text, the outcome, the method, the attempt of a found search, and counts) before a result is printed, whatever it finds. The table refuses UPDATE, DELETE, and TRUNCATE, keeps no text, and outlives the attempt it names. The handle is an audit label, not authentication: any holder of the database credential can type any handle. Rolling migration 51 back is refused while the audit holds a row.
|
|
- The result goes to the operator only. No HTTP operation serves it, an employer never sees it, and it changes no score, category, or quota. It is a hint for a manual review and an appeal, not a decision.
|
|
- The command reads every real attempt to compute its code and searches the stored statements, so it is meant for an operator and not for a request path; its cost grows linearly with the number of attempts.
|
|
|
|
## Demonstration categories on a stand
|
|
|
|
A category from a `demo_basic` result is assigned only on an isolated synthetic stand. It is not calibrated and must not appear in an environment with real candidates. Two independent steps enable it on a stand:
|
|
|
|
1. Set `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` in the backend environment (default `false`; Compose passes the value) and restart the backend. At startup the backend logs the warning `synthetic demonstration categories are enabled; never on a production stand`; the attestation command prints the same warning before it works.
|
|
2. Attest each opened category as an operator:
|
|
|
|
```sh
|
|
make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:<handle>'
|
|
```
|
|
|
|
- The command takes the same current selection that a new attempt will pin: the exact category opening, its published catalog manifest, and the product policy version in force. That version must be a complete demonstration policy (kind `demo`, an uncalibrated method, explicit attempt settings with `real_mode = demo_basic`, and training settings); otherwise the command refuses. The pass mark `basic_pass_mark_bp` is the policy version's own; neither the command nor the database requires a fixed value. Pass `--task-language` when the selection holds several languages.
|
|
- The command needs only `DATABASE_URL`; it reads no other environment variable and no dotenv file, validates its arguments before connecting, and stores the attestation in one transaction. A repeat for the same opening, manifest, and policy version changes nothing and prints `already attested`. The output holds identifiers, the policy version, and the handle, and no candidate data.
|
|
- An attestation pins the opening, the manifest, and the policy version. After a new policy version or a new opening of the category, attempts are not created until the category is opened again, and a new opening with a new policy version needs a new attestation.
|
|
- A row in `assessment_synthetic_category_reviews` is the audit record: it holds the `operator:<handle>` handle, the database time, and the pinned versions. The table refuses UPDATE and DELETE. The handle is an audit label, not authentication: local database access is the operator boundary.
|
|
- The attestation trigger accepts a policy of kind `demo` with `real_mode = demo_basic`. When a category is assigned, the database compares the threshold of the result with `basic_pass_mark_bp` of the policy version pinned to the attempt, so a 9000 threshold in an accepted policy works like 8000. A result decided before the attestation gets no category; only a result decided after it can assign one.
|
|
- Without either step a result that reached the threshold is stored as `not_eligible`: the candidate sees the score and no category. `demo_express` never creates a category under any setting. `make -C backend assessment-category-attest-build` builds `backend/bin/assessment-category-attest`.
|
|
|
|
## Match search policy on a stand
|
|
|
|
The match search ranks with the `matching` section of the effective `product` policy and fails closed without it: a search answers 500 `internal`, the log holds an error line that says the effective product policy has no matching section and names the command below, and no default is used. The startup seed publishes only the first demonstration version, which has no such section, so at startup the backend logs the warning `the effective product policy has no matching section` while the section is missing. Publish it once per stand as an operator:
|
|
|
|
```sh
|
|
make -C backend policy-publish ARGS='matching --actor operator:<handle>'
|
|
```
|
|
|
|
- The command takes the latest product policy version, which must be a demonstration version (kind `demo`), and publishes the next version as a copy of it with the demo matching section added. No other value changes. A latest version that already has the section changes nothing and prints `already present`; if another publication takes the next version number meanwhile, the command stores nothing and asks to run it again; a calibrated latest version, or a family without a version, is refused. `make -C backend policy-publish-build` builds `backend/bin/policy-publish`.
|
|
- It needs only `DATABASE_URL`, reads no dotenv file, validates its arguments first, and prints the version number only. The author of the version is the `operator:<handle>` label, an audit label and not authentication: local database access is the operator boundary.
|
|
- The new version takes effect at once for new searches and changes no stored result. It is also a new version of the whole product policy, so a category opening pinned to the earlier version has to be opened again (and attested again on a demonstration stand, see above) before new assessment attempts are created. Publish it before the candidates start attempts, or repeat the opening and the attestation afterwards.
|
|
- The demo values (the coefficients of the PRD, the limit of 10 entries per group, and the small specialization-to-technology taxonomy) are in [architecture](ARCHITECTURE.md#product-policy-versions); they are not calibrated. The isolated browser fixture publishes the same section itself.
|
|
- `policy-publish semantic` publishes the next version with the matching section replaced by the semantic one (`DemoSemanticMatchingPolicy`: Fit weights 0.4167 / 0.0833 / 0.5, the model, the calibration, and the explanation thresholds; see [Semantic matching](#semantic-matching)); when the latest version already has a semantic section, nothing changes. The version with the PRD point stays the previous one.
|
|
- `policy-publish semantic-ensemble` publishes the next version with the semantic section replaced by the Giga + Qwen3-Embedding ensemble (`DemoSemanticEnsembleMatchingPolicy`: two models, their weights, mean, and std, and the calibration of the fused score; the Fit weights and explanation thresholds stay the same); when the semantic section of the latest version already names both models, nothing changes. The version with Giga alone stays the previous one. The ML service must serve both models, and a backfill follows the publication (see [Semantic matching](#semantic-matching)).
|
|
|
|
## Isolated demo stand
|
|
|
|
The demo stand is a separate Compose project with synthetic data only: the jury and the team sign in with prepared accounts of both roles, without waiting for mail. It is not the working stand, and real people must not register on it.
|
|
|
|
```sh
|
|
make -C deploy demo-seed DEMO_MODE=isolated
|
|
make -C deploy demo-reset DEMO_MODE=isolated
|
|
make -C deploy demo-down DEMO_MODE=isolated
|
|
```
|
|
|
|
- Every target requires `DEMO_MODE=isolated` and refuses before any Docker command without it. It acts only on the project `DEMO_PROJECT` (default `lincodex-demo`), whose name must contain `demo` and differ from `APP_PROJECT`; the ordinary project and its volumes are never addressed. The project is `docker-compose.yml` with `docker-compose.demo.yml`, built from the current sources unless a release manifest is selected (see below). The overlay sets `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` on the demo backend, so a full test taken there assigns an uncalibrated synthetic category like the prepared ones (see [Demonstration categories on a stand](#demonstration-categories-on-a-stand)). It reads the secrets from the root `.env` (`ENV_FILE`) and overrides the project name, networks, `APP_HTTP_PORT` (`DEMO_HTTP_PORT`, default 8090), `APP_PUBLIC_URL` (`DEMO_PUBLIC_URL`, default `http://localhost:8090`), and the pinned subnet (`DEMO_SUBNET` 172.29.84.0/24, `DEMO_FRONTEND_IP`), so it can run next to the ordinary stand. The bind address stays `APP_HTTP_BIND`. Behind the edge, set `DEMO_PUBLIC_URL` to the public origin. The mail transport is the one in `.env`; the prepared accounts need no mail. The overlay also builds the frontend with `VITE_DEMO_STAND=true`: the jury guide appears at `/demo`, and the start page links to it. A stand restored from a release manifest (`RELEASE_ID`) uses the core frontend built without this flag, so it has no guide.
|
|
- `demo-seed` starts the project when needed, waits for the backend readiness (migrations and the startup policy are done by then), runs the `demo-seed seed` command in a separate container, and prints the inventory of the seeded records. A second run creates nothing and prints the same inventory. `demo-down` stops the project and keeps its volumes.
|
|
- `RELEASE_MANIFEST=<path>` or `RELEASE_ID=<id>` on `demo-seed` or `demo-reset` restores the stand from that immutable [release manifest](#release-manifest) instead of the current sources; `restore.demo.command` in the manifest gives the exact command. `release_manifest.py demo-override` first checks the manifest structure and its core and demo restore status, the hashes of the core and demo Compose files and of the data artifacts, and the exact local images, then writes a private temporary Compose override that pins every service and the `demo-seed` command to the recorded image IDs and digests. Compose starts with `--no-build --pull never`, the seed runs without `--build`, and after the readiness check the running containers are compared with the manifest. A manifest that cannot be restored stops the target before any Compose command. `demo-down` does not need the manifest.
|
|
- `demo-reset` first runs `demo-seed check-reset` against the demo database. It refuses, and deletes nothing, when the database holds any account outside the reserved domain `@demo.lincodex.test`, for example a visitor's own registration: such an account is ordinary data. Otherwise it removes the demo project with its volumes (`down --volumes` of `DEMO_PROJECT` only), starts it again, and seeds it. The demo overlay labels the PostgreSQL, SeaweedFS, and Kafka volumes with `org.lincodex.demo-mode=isolated` when it creates them; every target refuses a volume of the project without that label, so a volume of an ordinary stand is never adopted or discarded. A stand that the reset refuses can only be cleared by a deliberate manual decision of the operator.
|
|
- The password of every synthetic account is `DEMO_ACCOUNT_PASSWORD` from `deploy/demo/demo.env`, or from the checked-in `deploy/demo/demo.env.example` when that file does not exist. The example value is a published demo credential, not a secret; for a stand reachable from outside, copy the example to `demo.env` (ignored by Git) and hand the new password to the jury separately. The password applies when an account is created; change it with a reset. The commands print the logins and never the password.
|
|
|
|
What the seed creates (all names carry a synthetic marker; addresses are on `@demo.lincodex.test`, which never receives mail):
|
|
|
|
| Login | Role and state |
|
|
| --- | --- |
|
|
| `employer-alpha@demo.lincodex.test` | Employer. Owner of "Демо-компания «Альфа»" and recruiter in "Демо-компания «Бета»": full owner access in one organization and the owner-only denial of the minimal release in the other |
|
|
| `employer-beta@demo.lincodex.test` | Employer. Owner of "Демо-компания «Бета»" |
|
|
| `candidate@demo.lincodex.test` | Candidate for the jury's own run: C1 and C3, a manual profile without an FSP ID, the Backend Junior questionnaire with Go, no attempt, no publication. Runs the express and starts the full test |
|
|
| `prepared-1@` to `prepared-6@demo.lincodex.test` | Candidates with a prepared full attempt: C1, C2, C3, the same profile and questionnaire, one finished `demo_basic` attempt with its synthetic demonstration category Backend Junior and evidence, and a published card |
|
|
|
|
- Accounts are confirmed by the seed itself: it stores the account, the C1 grant of a registration, and the verification time in one transaction, like the e2e fixtures. Ordinary registration is unchanged and still needs the email link; on a stand with `EMAIL_PROVIDER=disabled` a self-registered account cannot sign in.
|
|
- Policy and bank: over the unchanged startup version 1 the seed publishes the demo policy `DemoProductPolicyV4` (explicit `demo_basic` settings, the separate express training section, the review band, and the matching section); a stand whose latest policy is anything else is refused. It imports and publishes 25 synthetic families of the category `demo-backend-junior` (author `ai:demo-seed-synthetic-bank`, reviewer label `operator:demo-seed-bank-reviewer`; the families are not subject-reviewed), opens the category for Backend Junior with Go, and attests it as a synthetic demonstration source. Express mode has its own three families in the category `demo-express` and its own training binding; an express run never creates a category, a percentile, or evidence.
|
|
- Prepared attempts run through the ordinary attempt operations: create, answer every frozen item (all but the last one correctly), and finalize, so the result, the category, the history, and the evidence projection come from the same code and triggers as a candidate's attempt. They are not three demonstration questions. They are labelled in the profile of each prepared candidate ("Полная попытка теста подготовлена командой demo-seed"), in the seed output (attempt IDs), and as uncalibrated `synthetic_demo` categories. The database has no separate provenance flag on a result yet. The answers are given within seconds, so the manual-review band of these attempts can show the speed signals.
|
|
- Six identical prepared cards exist because a card is shown only in a cohort of at least five; the sixth keeps the search non-empty after one prepared candidate hides an organization or unpublishes. The search of Alpha's owner returns the six entries; the recruiter's search in Beta answers 403. The seed creates no need: an employer creates one during the demonstration.
|
|
- The seed refuses a stand that holds ordinary accounts but none of its own, never edits a record it did not create, and leaves its own records alone on a repeat (for example a profile a visitor changed); use the reset to restore them. It refuses an address of the reserved domain that belongs to an unconfirmed or other-role account. `demo-seed` needs `DATABASE_URL` and `DEMO_MODE=isolated`, plus `DEMO_ACCOUNT_PASSWORD` for `seed`; it reads no dotenv file and checks all of them before it connects. The actor `operator:<handle>` (`DEMO_ACTOR`, default `operator:demo-seed`) is recorded as the author of the policy version, the publisher of the families, the opener of the category, and the attestor; it is an audit label, not authentication. `make -C backend demo-seed ARGS='inventory'` runs the same command from a host that reaches the database; `make -C backend demo-seed-build` builds `backend/bin/demo-seed`. The command is built by `backend/Dockerfile.demo-seed`; the backend image does not contain it, and `release-build` builds it as the separate release image `lincodex.invalid/demo-seed:<tag>`.
|
|
|
|
## Separate ML Compose project
|
|
|
|
ML uses a separate Compose file and project; it needs no Redis or SeaweedFS. It joins the external network of the core project (`APP_NETWORK`) with the alias `ml`, so the backend reaches `http://ml:8000` without a published port; start the core project first. The host port binds only to 127.0.0.1:8000 by default for diagnostics; change ML_BIND_ADDRESS only after preparing a private address and firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty.
|
|
|
|
The image is based on `python:3.14-slim` (PyTorch publishes glibc wheels only, so Alpine cannot be used; the minor version is fixed for `requires-python` and the lock). Dependencies, including the CPU build of PyTorch from the `download.pytorch.org/whl/cpu` index, are installed with uv only in the build stage; the runtime has no pip. A separate stage fetches the files of both models at the pinned revisions from `ml/model/giga-embeddings-480m.lock.json` and `ml/model/qwen3-embedding-0.6b.lock.json` into `/opt/lincodex/models/giga-480m` and `/opt/lincodex/models/qwen3-0.6b` and checks the size and SHA-256 of every file (about 0.98 and 1.19 GB of safetensors weights); at startup the service checks the SHA-256 again (`ML_VERIFY_WEIGHTS=true`, a few seconds) and runs with `HF_HUB_OFFLINE=1`. The container listens on 0.0.0.0:8000 through `python -m lincodex_ml.serve`, so the service does not start without `ML_SERVICE_TOKEN`. The expected image size is about 3.7 GB (Python and PyTorch CPU about 1.4 GB, the models about 2.2 GB); the image was not built on this machine because of free disk space.
|
|
|
|
| Variable | Default | Purpose |
|
|
| --- | --- | --- |
|
|
| `ML_EMBEDDER` | `giga,qwen3` in the image and Compose, `none` outside the image | a comma list of models (`giga`, `qwen3`), the first answers a request without `model`; `fake` - a deterministic hash encoder for stands without the models (its model id does not match the policy, so its vectors are never used), `none` - the service stays not ready |
|
|
| `ML_SERVICE_TOKEN` or `ML_SERVICE_TOKEN_FILE` | empty | the bearer token shared with the backend (at least 32 printable characters, a secret); without it the service answers loopback callers only and refuses to start on a non-loopback address |
|
|
| `ML_LISTEN_HOST`, `ML_LISTEN_PORT` | 127.0.0.1, 8000 (0.0.0.0, 8000 in the image) | address and port of `python -m lincodex_ml.serve` |
|
|
| `ML_GIGA_MODEL_DIR`, `ML_QWEN3_MODEL_DIR` | the image directories | the model files; a Hugging Face snapshot directory works too |
|
|
| `ML_GIGA_MODEL_LOCK`, `ML_QWEN3_MODEL_LOCK` | `model.lock.json` in the model directory | the lock file the files are checked against |
|
|
| `ML_DEVICE` | `cpu` | `cpu`, `cuda`, or `cuda:<index>` |
|
|
| `ML_DTYPE` | `float32` | `float16` and `bfloat16` on CUDA only |
|
|
| `ML_CUDA_MEMORY_LIMIT_MB` | 0 (no limit) | CUDA allocator limit of the process; the CUDA context adds about 130 MiB |
|
|
| `ML_EXIT_ON_LOAD_FAILURE` | false | end the process after a load failure other than a lack of device memory, so a supervisor restarts it |
|
|
| `ML_TORCH_THREADS` | 4 | torch threads; with 4 the study meets the CPU targets |
|
|
| `ML_MICRO_BATCH` | 1 | micro-batch size; 1 gives every text the same vector whatever the request holds |
|
|
| `ML_MAX_TOKENS` | 1024 | tokens a text, as in the study |
|
|
| `ML_VERIFY_WEIGHTS` | true | check the SHA-256 of the weights at startup |
|
|
|
|
Container limits: 4 CPUs and 8 GiB (on CPU in float32 Giga takes about 3.6 GiB resident and Qwen3-Embedding about 2.5 GiB more). Readiness turns 200 only after both models are loaded and warmed up. A lack of device memory never stops the process: a load is retried, a request answers 503, and `/readyz` answers 503 for 30 seconds.
|
|
|
|
make -C deploy ml-config
|
|
make -C deploy ml-build
|
|
make -C deploy ml-up
|
|
make -C deploy ml-logs
|
|
make -C deploy ml-down
|
|
|
|
For development without Docker: `make -C ml model-fetch` fetches and checks the same files into `ML_GIGA_MODEL_DIR` and `ML_QWEN3_MODEL_DIR` (defaults `~/.cache/lincodex-ml/giga-480m` and `~/.cache/lincodex-ml/qwen3-0.6b`), and `make -C ml test-model` compares the vectors of both models with the study (`ML_TEST_DEVICE=cuda` on a GPU). Giga measured on an Apple M5 (CPU, 4 threads, over HTTP, 20 requests): a need view of 887 characters p50 296 ms / p95 707 ms, a profile of 500 characters 207 / 237 ms, a short requirement 74 / 166 ms, a card job batch of 13 texts 2.2 / 5.4 s. This is one laptop with other load, not a stand measurement.
|
|
|
|
## ML service on a GPU host
|
|
|
|
On a separate GPU host the service runs without Docker: as the systemd user unit `lincodex-ml.service` of the service user (template [deploy/ml-gpu/lincodex-ml.service](../../deploy/ml-gpu/lincodex-ml.service), lingering enabled for the user) with a virtualenv and models from local files. Both models in float16 take 2.2-2.4 GiB of VRAM, so the service fits next to another user of the same card.
|
|
|
|
1. Code: the `ml/` directory of the release (`git archive`) in `~/lincodex-ml/app/ml`.
|
|
2. Virtualenv: the pinned uv 0.12.22 creates `~/lincodex-ml/venv`. `make -C ml cuda-requirements` writes the versions pinned in `uv.lock` with the CUDA build of torch (`torch==2.11.0+cu128`) to `ml/dist/requirements-cuda.txt`; install the torch line from the `https://download.pytorch.org/whl/cu128` index first, then the other lines from PyPI (`uv pip install --python ~/lincodex-ml/venv/bin/python ...`). A shared uv cache with `UV_LINK_MODE=hardlink` takes no space for wheels it already holds, but the cache is keyed by the index address: another spelling of the address downloads torch and the CUDA libraries again (about 6 GB). Exception: where disk is short, the virtualenv uses the system CPython 3.12 with the same package versions (the cp314 CUDA wheel of torch does not fit), and the package is not installed: the unit sets `PYTHONPATH` to `src`. The service unit tests pass on 3.12, but 3.14 stays the main version, so 3.13+ syntax in `ml/src` would break such a host.
|
|
3. Models: Hugging Face snapshot directories at the pinned revisions (`HF_HOME` read-only) or `make -C ml model-fetch`; at startup the files are checked against the lock files of the release.
|
|
4. Settings: copy [deploy/ml-gpu/ml.env.example](../../deploy/ml-gpu/ml.env.example) to `~/.config/lincodex-ml/ml.env` (directory 700, file 600). Generate the token on the host with a CSPRNG (`python3 -c 'import secrets; print(secrets.token_hex(32))'`); it lives only in this file and in the backend environment. The address is a private address of the host, never 0.0.0.0.
|
|
5. Start: put the unit template in `~/.config/systemd/user/lincodex-ml.service`, then `systemctl --user daemon-reload` and `systemctl --user enable --now lincodex-ml.service`. Restart after a code or settings update with `systemctl --user restart lincodex-ml.service`, check it with `systemctl --user status lincodex-ml.service`, follow the log with `journalctl --user -u lincodex-ml.service -f`. The unit sets `Restart=on-failure`, `MemoryHigh=5G`, `MemoryMax=6G`, `CPUQuota=400%`, 4 torch and OMP threads, and `ML_EXIT_ON_LOAD_FAILURE=true`: a lack of device memory never stops the process, while other load failures (for example a driver that is not ready at host startup) end it and systemd restarts it after 15 seconds.
|
|
6. Network: the unit changes no firewall or system setting. Restrict the port to the app host address at the host or network level; the traffic crosses the LAN without TLS, so the token and the texts are visible on that segment.
|
|
|
|
Precision and VRAM (RTX 5060 Ti 16 GB, measured 2026-10-11, a process budget of about 2.5 GB): in float32 Giga alone takes 1984 MiB after the load and up to 2750 MiB under a request of 1024-token texts, Qwen3 2404 and 3038 MiB, together about 4.3 GiB after the load, so float32 does not fit. In float16 both models in one process take 2252 MiB after the load and 2404 MiB under the worst request (32 texts of 1024 tokens), with the allocator capped by `ML_CUDA_MEMORY_LIMIT_MB=2300`. Quality of float16 against float32 on the study's DEV data (product views): vector cosine at least 0.99986 (Giga) and 0.99999 (Qwen3), nDCG@10 changed by -0.0004 and +0.0008, for the ensemble by +0.0002 (threshold 0.005), the ensemble top-10 is the same set for 30 of 30 DEV needs and in the same order for 28, and a repeated encode at micro-batch 1 gives the same bits. `bfloat16` was rejected: the top-10 matches for 27 of 30, the order for 14. Hence `ML_DTYPE=float16`; the mean, std, and calibration of the ensemble were computed on float16 vectors.
|
|
|
|
Latency over the LAN from the app host (40 requests, one text, micro-batch 1, CUDA float16): a need view - Giga p50 11.4 / p95 13.0 ms, Qwen3 12.5 / 14.5 ms; a profile - 11.2 / 12.9 and 12.1 / 13.8 ms; a card job batch of 13 texts - 132 / 135 and 143 / 160 ms. The process keeps about 2.6 GiB resident (peak 2.9 GiB). This is one host measured while the other model on the card was not loaded, not a load test.
|
|
|
|
## Semantic matching
|
|
|
|
The search never calls ML: it reads the vectors that background jobs computed (see [ARCHITECTURE.md](ARCHITECTURE.md#semantic-layer-and-explanations)). To enable it on a stand:
|
|
|
|
1. `make -C deploy up`, then `make -C deploy ml-up` (or the [ML service on a GPU host](#ml-service-on-a-gpu-host)), and wait for `/readyz` 200.
|
|
2. Set `SEMANTIC_MATCHING_ENABLED=true`, `ML_SERVICE_TOKEN` (the token of the ML service), and `ML_SERVICE_URL` if it differs (`http://<address>:<port>` for a GPU host) in the stand `.env` and restart the backend (`make -C deploy up`).
|
|
3. Publish the semantic policy section: `make -C backend policy-publish ARGS='semantic --actor operator:<handle>'` (with the stand `DATABASE_URL`). Like the `matching` section, a new policy version requires opening and attesting the category again on the demo stand.
|
|
4. Compute vectors for existing data: `make -C backend semantic-backfill ARGS='all --run <label>'`. The command needs only `DATABASE_URL`; it schedules jobs page by page and prints the cursor to resume with (`--after`). Repeating the same label schedules nothing twice; a new label recomputes, and unchanged texts cost no ML call. The backend worker runs the jobs.
|
|
|
|
| Backend variable | Default | Purpose |
|
|
| --- | --- | --- |
|
|
| `SEMANTIC_MATCHING_ENABLED` | false | schedule and run vector jobs |
|
|
| `ML_SERVICE_URL` | `http://ml:8000` in Compose | ML origin without a path or credentials |
|
|
| `ML_SERVICE_TOKEN` | empty | bearer token of the ML service, 32-512 printable characters without spaces; required while `SEMANTIC_MATCHING_ENABLED=true`; a secret that never reaches a log |
|
|
| `ML_REQUEST_TIMEOUT` | 30s | timeout of one ML request |
|
|
| `ML_CIRCUIT_FAILURES`, `ML_CIRCUIT_OPEN` | 3, 30s | after that many consecutive failures the client does not call ML for that long |
|
|
| `GITHUB_REPOSITORY_CHECKS_ENABLED` | false | run the checks of project repositories on `api.github.com` |
|
|
| `GITHUB_TOKEN` | empty | optional token for reading public data only; raises the GitHub limit from 60 to 5000 requests an hour; a secret |
|
|
| `GITHUB_TIMEOUT` | 10s | timeout of a GitHub request |
|
|
| `REPOSITORY_CHECK_INTERVAL` | 10m | how often a candidate may ask for a new check |
|
|
|
|
Without ML, or while it is unavailable, the search works as before: the neutral `Sem` 0.5 with the `ml_unavailable` flag; jobs retry up to 20 times and then wait for an operator (a new backfill). The isolated browser stand (e2e) does not start ML and uses policy V4; the demo stand also runs without ML by default, and enabling it takes the same steps with the project `lincodex-demo`. Metrics: `lincodex_scheduled_jobs_total{kind="semantic.candidate"|"semantic.need"|"profile.repository_check"}` in the backend, `lincodex_ml_embedding_request_seconds` and `lincodex_ml_embedding_texts_total` in ML.
|
|
|
|
The Giga + Qwen3-Embedding-0.6B ensemble (see [ARCHITECTURE.md](ARCHITECTURE.md#semantic-layer-and-explanations)) is enabled after the steps above, once the ML service serves both models (`ML_EMBEDDER=giga,qwen3`):
|
|
|
|
1. `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:<handle>'` - a new policy version with two models; the version with Giga alone stays the previous one.
|
|
2. Right after it, `make -C backend semantic-backfill ARGS='candidates --run <label>'` and `make -C backend semantic-backfill ARGS='needs --run <label>'` (or `all`). Jobs compute the vectors of every model of the effective policy: the Giga vectors do not change and cost no ML call, and Qwen3 encodes only the `whole` view of each card and need. Until the backfill ends, entries without Qwen3 vectors get the neutral `Sem` with `ml_unavailable`, so switch at a quiet time.
|
|
3. Check: `SELECT model_id, count(*) FROM semantic_vectors WHERE item_key = 'whole' GROUP BY model_id` - the Qwen3 count catches up with the Giga count.
|
|
|
|
Provenance of the policy values: the DEV judgments of the LincodexMatch study (30 needs, 3220 judged pairs), the study's profiles and needs rendered by the product view builder, ML service vectors on CUDA in float16, and the weights of step 5 of the study; the encoding and fitting scripts and their outputs are kept next to the research run on the GPU host (`lincodex-ml/eval/`). The search never reads vectors of a model that the policy no longer names; they stay for a rollback to the previous policy version.
|
|
|
|
## Separate monitoring Compose project
|
|
|
|
Start the core project first. Monitoring joins its Docker network. Monitoring starts separately and is not required to run the app:
|
|
|
|
make -C deploy monitoring-config
|
|
make -C deploy monitoring-up
|
|
make -C deploy monitoring-logs
|
|
make -C deploy monitoring-down
|
|
|
|
Grafana is available at http://127.0.0.1:3000. Credentials come from GRAFANA_ADMIN_USER and GRAFANA_ADMIN_PASSWORD in .env. Prometheus, Loki, exporters, and backend metrics publish no host ports.
|
|
|
|
The `Lincodex product` dashboard in the Lincodex folder shows API request rate, error ratio, p50 and p95 latency of successful requests by route template, problem responses by code, outbox backlog and lag, relay, consumer, and scheduled job outcomes, mail deliveries by kind and status, the oldest due pending delivery, quota usage, and assessment answer saves. The answer save panel stays empty until the answer command is implemented. Prometheus loads the alert rules from `observability/prometheus/rules/`; their state is in the Prometheus rules API `/api/v1/rules`, which Grafana reaches through the Prometheus data source (Prometheus itself publishes no host port). No Alertmanager or notification channel is configured, so no alert reaches a person.
|
|
|
|
`make -C observability verify-product-metrics` checks this end to end on throwaway stacks: it starts an isolated core project `lincodex-metrics-check` on port 18085 and, separately, the monitoring project `lincodex-metrics-check-monitoring` with Grafana on 127.0.0.1:13085 (`METRICS_CHECK_HTTP_PORT` and `METRICS_CHECK_GRAFANA_PORT` change them), sends successful and failing API requests and a fixture mail delivery through the outbox, checks the values in Prometheus and every panel query of the product dashboard through Grafana, sends the fixture address in a query through Nginx and in a path straight to the backend, provokes a unique violation on the fixture address in PostgreSQL and checks that its log line omits the key, searches the metric exposition, all series and label values, the federated samples, and the Loki logs for the fixture address (after Loki shows both backend request lines of the run), and removes both projects with their volumes. It uses `EMAIL_PROVIDER=resend` with a placeholder key so the quota gauges exist; nothing sends mail in this build. It is an explicit end-to-end check, not part of `make -C observability check`: it starts two separate Compose projects and builds the core images. It starts every monitoring service except node-exporter, which reads only host metrics and whose root mount fails on Docker Desktop. It refuses to run when volumes or networks of these projects already exist, removes the images it built, and with `METRICS_CHECK_KEEP_ON_FAILURE=1` keeps both projects after a failure for inspection.
|
|
|
|
Prometheus retains metrics for 14 days with a 4 GB size limit. Loki retains logs for 7 days. Alloy discovery filters by Compose project and collects logs only from backend, frontend, postgres, redis, and seaweedfs. Kafka logs and metrics are not collected yet; read the logs with `make -C deploy logs`. Loki labels are limited to service and environment; do not add user IDs, addresses, resume text, request bodies, or full URLs.
|
|
|
|
What reaches Loki from the core services: the backend request log (`http request`, `http request error`, `http request failed`) names a request only by its request ID, method, route template (the same as the metric label, such as `/api/v1/me/invitations/{invitation_id}`), status and status class, problem code, latency, response size, and the number of query parameters; it never logs the raw path, a query key or value, a header, the client address, or the user agent. Nginx in the frontend container logs the method, the path without the query string, status, timings, and request ID; a path that a client fills with an address would therefore appear in its log, which no API route invites. PostgreSQL runs with `log_error_verbosity=terse`, so an error line leaves out the DETAIL that quotes a duplicate or missing key, such as an address; the backend binds parameters, so the logged statement holds only placeholders. Handler logs follow the rules of their components, for example deliveries by `delivery_id` only.
|
|
|
|
Frontend telemetry is not connected in the React app yet. Nginx and Alloy provide a restricted /telemetry receiver and Faro configuration, but the UI SDK and end-to-end event check are absent.
|
|
|
|
Alloy uses docker-socket-proxy for container discovery and log collection. The proxy enables only the needed Docker API sections for containers, events, networks, ping, and version; POST is disabled. Alloy's Docker discovery reads the networks of each container for its labels; without the networks section discovery fails with 403 and no log reaches Loki. The proxy sits alone with Alloy on the internal `docker-api` network, so no other monitoring or core container can call it. What the containers section still allows to Alloy: `GET /containers/{id}/json` returns the configuration of every container on the host, including `Config.Env` with the passwords and keys of the core services, and the same path prefix also allows `GET` of `/containers/{id}/logs`, `/containers/{id}/archive` (files from a container), and `/containers/{id}/export` (a container's whole file system). A compromised Alloy can therefore read the secrets of the stack; the network keeps every other container from doing the same. The `read_only` flag of the socket mount only protects the socket file and does not restrict any API call. Set the socket path with DOCKER_SOCKET_PATH. Rootless Docker may use a path such as /run/user/<uid>/docker.sock; use the path on your own host instead of copying another developer's local path. The proxy restricts API sections, but access to the Docker socket remains privileged and its exact configuration needs review.
|
|
|
|
PostgreSQL creates a separate exporter role only while initializing an empty volume and when POSTGRES_EXPORTER_USER and POSTGRES_EXPORTER_PASSWORD are set. Set both before the first make -C deploy up. Changing them after the volume exists does not rerun the init script.
|
|
|
|
For remote ML scraping, set ML_METRICS_TARGET to hostname:port or IPv4:port and verify private routing and firewall rules. The standalone ML host does not yet have a separate Alloy config for forwarding its container logs to Loki.
|
|
|
|
## Edge proxy, HTTPS and tunnel
|
|
|
|
The Compose stack serves plain HTTP on the host. A public site puts a separate edge host in front of it: the edge terminates TLS and forwards every request through a dedicated tunnel to the app host. The files are in `deploy/edge/`; this section is the runbook. It describes the configuration in the repository. A rollout is an external action, and the test steps below show what a rollout has to prove.
|
|
|
|
browser --HTTPS--> edge nginx (EDGE_LISTEN_IP:80,443)
|
|
--AmneziaWG tunnel (10.79.0.0/30)--> app host (10.79.0.2:8080)
|
|
= frontend container (Nginx) --> backend
|
|
|
|
| Role | What runs there | Address in the reference rollout |
|
|
| --- | --- | --- |
|
|
| Edge host | nginx, certbot, the AmneziaWG server end | public `213.165.42.19` and `89.185.85.208`; tunnel `10.79.0.1` |
|
|
| App host | Docker Compose core stack, the AmneziaWG client end | LAN `192.168.10.111` behind NAT; tunnel `10.79.0.2` |
|
|
|
|
The edge host is shared with other services. Everything here only adds: nginx binds the one address in `EDGE_LISTEN_IP` and never a wildcard, the tunnel uses its own interface and subnet, and no existing interface, listener, container, or firewall rule is changed.
|
|
|
|
### Configuration
|
|
|
|
All names and addresses come from `deploy/edge/edge.env` (copy `deploy/edge/edge.env.example`; the file holds no secrets and Git ignores it). The main values are `EDGE_DOMAIN`, `EDGE_CERT_NAME`, `EDGE_LISTEN_IP`, `EDGE_ACME_WEBROOT`, `EDGE_HSTS_MAX_AGE`, `EDGE_MAX_BODY`, and the tunnel values `AWG_IFACE`, `AWG_EDGE_IP`, `AWG_APP_IP`, `AWG_PREFIX`, `AWG_EDGE_ENDPOINT_IP`, `AWG_PORT`, `AWG_MTU`, and `AWG_KEEPALIVE`. The edge proxies to `AWG_APP_IP:APP_HTTP_PORT`. The tunnel subnet must not overlap any route or Docker range on either host; `ip route` on both hosts is the check.
|
|
|
|
make -C deploy edge-config # render the templates and run nginx -t in a container
|
|
make -C deploy edge-render # write deploy/edge/rendered/nginx
|
|
|
|
`edge-config` renders the nginx templates and both tunnel templates (with throwaway keys), fails when a placeholder has no value or a `listen` directive is not bound to `EDGE_LISTEN_IP`, and runs `nginx -t` in `nginx:stable-alpine` (`EDGE_NGINX_IMAGE` changes it) with a self-signed certificate at the path the configuration expects. It needs Docker and proves syntax only, not that a certificate exists or the host is reachable. The Ubuntu edge package is nginx 1.28; keep the image close to it.
|
|
|
|
`deploy/edge/scripts/render.sh` validates every value before it substitutes it. Keys and obfuscation parameters are not part of `edge.env`: `deploy/edge/scripts/awg-keys.sh` writes them to a root-only parameters file on each host (`/etc/amnezia/amneziawg/awg-lincodex.params`), and `render.sh --params` reads that file to produce the tunnel configuration.
|
|
|
|
### One origin and the Secure cookie
|
|
|
|
The browser sees only `https://<EDGE_DOMAIN>`. The SPA and `/api` come from the same origin: the edge forwards every path unchanged, and the frontend container serves the SPA with its `try_files ... /index.html` fallback, so a deep link such as `/some/deep/link` returns the SPA, and proxies `/api/` to Go. The backend issues the `__Host-lincodex_session` cookie with `Path=/`, `Secure`, `HttpOnly`, `SameSite=Strict`, and no `Domain`; `Expires` and `Max-Age` match the absolute session expiry. The edge keeps `Host` as the public name and sets `X-Forwarded-Proto: https`; the frontend container's Nginx keeps that value for the backend (`$forwarded_proto` in `deploy/nginx/conf.d/app.conf`) and otherwise reports its own scheme. `APP_PUBLIC_URL` in the app host `.env` must be `https://<EDGE_DOMAIN>`. Unsafe public identity operations and protected unsafe operations require the sole `Origin` value to exactly match `APP_PUBLIC_URL`; protected unsafe operations also require a CSRF token bound to the session cookie. The backend does not derive the allowed origin from `Host` or trust forwarded headers for this check.
|
|
|
|
Registration, verification resend, email confirmation, login, current-session reading, and logout are available through the backend API. Protected operations require a verified account session; implemented consent operations read texts and history, grant and revoke consents, and queue C1 account deletion without deleting the account immediately. Other operations without business handlers still return 501 after the security boundary passes. Unsafe consent operations also require session-bound CSRF and exact `Origin`; public and protected Origin checks do not read `Host` or forwarded headers. Frontend registration, confirmation, sign-in, and scenario continuation are implemented and verified through the isolated local browser stack. The backend does not read `X-Forwarded-Proto` for the Origin check. The browser login path through the edge has not been verified end to end.
|
|
|
|
### Request handling at the edge
|
|
|
|
- Port 80 serves only `/.well-known/acme-challenge/` from `EDGE_ACME_WEBROOT` and answers everything else with a 301 to `https://<EDGE_DOMAIN>` plus the original path and query. The target is the configured name, not the request `Host`. A request for any other name is dropped (nginx 444) on port 80 and refused at the TLS handshake on port 443.
|
|
- Port 443 allows TLS 1.2 and 1.3 with the Mozilla intermediate cipher list, HTTP/2, no session tickets, and `Strict-Transport-Security: max-age=<EDGE_HSTS_MAX_AGE>; includeSubDomains` without `preload`. The default max-age is 180 days; raise it to a year and consider preload only after the site has stayed on HTTPS. The upstream security headers (`X-Content-Type-Options`, `Referrer-Policy`, `X-Frame-Options`, `Permissions-Policy`) pass through from the frontend container.
|
|
- OCSP stapling is off on purpose: Let's Encrypt certificates no longer carry an OCSP responder URL, so there is nothing to staple. HTTP/3 is off because it would need UDP 443, which another service on the edge host owns.
|
|
- Compression is off for `/api/` and limited to CSS, JavaScript, SVG, and the HTML shell elsewhere (no JSON). Compressing responses that mix secrets with attacker-influenced content enables BREACH; a CSRF token delivered in an API response must never be compressed. Revisit this if a secret is ever rendered into HTML.
|
|
- `X-Forwarded-For` and `X-Real-IP` are replaced with the connecting address, not appended to client values, because the edge is the first trusted hop. The frontend container trusts the tunnel address of the edge, resolves the client from that header, uses it for its coarse rate limits, and passes the backend a single replaced `X-Forwarded-For` entry (see [Public perimeter and client address](#public-perimeter-and-client-address)).
|
|
- `client_max_body_size` is `EDGE_MAX_BODY` (10 MB, the ceiling; the container allows 1 MB by default and raises it per route, never above this value). The 5 MB resume limit is a per-feature policy checked by the backend. Timeouts: 5 s to connect, 60 s to send and read (the container gives Go 30 s), 60 s for a request body.
|
|
- The access log (`/var/log/nginx/lincodex.access.log`, rotated by the package logrotate rule) records the path without the query string, so values such as addresses in a query do not reach the log.
|
|
|
|
### Rollout on the edge host
|
|
|
|
Ubuntu packages only; no system upgrade. Install nginx and certbot without starting nginx on its default wildcard site:
|
|
|
|
printf '#!/bin/sh\nexit 101\n' | sudo tee /usr/sbin/policy-rc.d >/dev/null && sudo chmod 755 /usr/sbin/policy-rc.d
|
|
sudo apt-get install -y --no-install-recommends nginx certbot
|
|
sudo rm -f /usr/sbin/policy-rc.d /etc/nginx/sites-enabled/default
|
|
|
|
1. Check that the domain resolves to `EDGE_LISTEN_IP` (`dig +short <domain> @1.1.1.1`) and that nothing listens on TCP 80 and 443 (`ss -tlnp`).
|
|
2. Copy `deploy/edge` to the host, create `edge.env`, and render: `deploy/edge/scripts/render.sh --env deploy/edge/edge.env --out deploy/edge/rendered nginx`.
|
|
3. Install the ACME directory and the first two files, then the firewall rules (ufw only gains rules; keep a second SSH session open while changing it):
|
|
|
|
sudo install -d -m 755 /var/www/certbot
|
|
sudo install -m 644 deploy/edge/rendered/nginx/00-default.conf deploy/edge/rendered/nginx/lincodex-http.conf /etc/nginx/conf.d/
|
|
sudo nginx -t
|
|
sudo ufw allow in to <EDGE_LISTEN_IP> port 80 proto tcp comment 'lincodex ACME and redirect'
|
|
sudo ufw allow in to <EDGE_LISTEN_IP> port 443 proto tcp comment 'lincodex HTTPS'
|
|
sudo systemctl enable --now nginx
|
|
|
|
4. Install the renewal hook and issue the certificate. Run the staging dry run first; the production CA limits repeated failures. The account has no email address (`--register-unsafely-without-email`), so Let's Encrypt cannot send expiry notices; add an address later with `certbot update_account --email <address>`. `--agree-tos` accepts the Let's Encrypt subscriber agreement.
|
|
|
|
sudo install -d -m 755 /etc/letsencrypt/renewal-hooks/deploy
|
|
sudo install -m 755 deploy/edge/certbot/reload-nginx.sh /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh
|
|
sudo certbot certonly --webroot -w /var/www/certbot -d <domain> --cert-name <domain> \
|
|
--register-unsafely-without-email --agree-tos --non-interactive --dry-run
|
|
sudo certbot certonly --webroot -w /var/www/certbot -d <domain> --cert-name <domain> \
|
|
--register-unsafely-without-email --agree-tos --non-interactive
|
|
|
|
5. Install the HTTPS file and reload: `sudo install -m 644 deploy/edge/rendered/nginx/lincodex-https.conf /etc/nginx/conf.d/ && sudo nginx -t && sudo systemctl reload nginx`. The site answers 502 or 504 until the tunnel and the app host are up.
|
|
6. Install the tunnel end (below), then `sudo ufw allow in to <AWG_EDGE_ENDPOINT_IP> port <AWG_PORT> proto udp comment 'lincodex tunnel'`.
|
|
|
|
### Tunnel
|
|
|
|
AmneziaWG runs in userspace (`amneziawg-go`) so that nothing depends on a kernel module for the host kernel. Both hosts use the same two pieces:
|
|
|
|
- `amneziawg-tools` (`awg`, `awg-quick`, and the `awg-quick@.service` unit) from the Amnezia PPA package for the release, downloaded and checked against the SHA-256 in the PPA package index, then installed with `dpkg -i`. The PPA is not added to apt, so the package does not update itself.
|
|
- `amneziawg-go`, built from the upstream tag `v3.1.20260828` (commit `b5928efb6ca1`) with `CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w"` and installed as `/usr/local/bin/amneziawg-go`. The reference build has SHA-256 `5e8877b58afdc4667be196aebb994839d167a4f189c5507e0155cc72ea1b14fa`. It is built off the hosts so they need no Go toolchain.
|
|
|
|
Keys and parameters are generated on the hosts and never leave them except as public data:
|
|
|
|
# edge, as root
|
|
deploy/edge/scripts/awg-keys.sh init /etc/amnezia/amneziawg/awg-lincodex.params
|
|
deploy/edge/scripts/awg-keys.sh export /etc/amnezia/amneziawg/awg-lincodex.params > shared.env
|
|
# app host, as root, after shared.env is copied over SSH
|
|
deploy/edge/scripts/awg-keys.sh init /etc/amnezia/amneziawg/awg-lincodex.params --shared shared.env
|
|
deploy/edge/scripts/awg-keys.sh export /etc/amnezia/amneziawg/awg-lincodex.params > app-shared.env
|
|
# edge, after app-shared.env is copied back
|
|
deploy/edge/scripts/awg-keys.sh peer /etc/amnezia/amneziawg/awg-lincodex.params app-shared.env
|
|
|
|
The exchanged files contain a public key and the obfuscation parameters. The parameters are shared secrets of the tunnel; delete the copies after use. Then, on each host (`awg-edge` on the edge, `awg-app` on the app host):
|
|
|
|
deploy/edge/scripts/render.sh --env deploy/edge/edge.env --out /tmp/awg --params /etc/amnezia/amneziawg/awg-lincodex.params awg-edge
|
|
sudo install -m 600 /tmp/awg/awg/awg-lincodex.conf /etc/amnezia/amneziawg/awg-lincodex.conf && rm -r /tmp/awg
|
|
sudo install -D -m 644 deploy/edge/systemd/awg-quick-userspace.conf /etc/systemd/system/awg-quick@awg-lincodex.service.d/userspace.conf
|
|
sudo systemctl daemon-reload && sudo systemctl enable --now awg-quick@awg-lincodex
|
|
|
|
The app host initiates the handshake from behind NAT and sends a keepalive every `AWG_KEEPALIVE` seconds; the edge has no peer endpoint. `AllowedIPs` lists only the other end's tunnel address, so the tunnel installs no default route and carries nothing else. Check it with `sudo awg show` (a recent `latest handshake`) and `ping <peer tunnel IP>`. The units start at boot. The userspace daemon is one process per interface; systemd does not restart it by itself, so check the handshake after an incident (`systemctl restart awg-quick@awg-lincodex` rebuilds the interface).
|
|
|
|
### Rollout on the app host
|
|
|
|
1. Install Docker Engine and the Compose plugin from the official Docker apt repository (`docker-ce`, `docker-compose-plugin`). The tunnel setup above comes first, because the next steps use its address.
|
|
2. Make Docker wait for the tunnel: `sudo install -D -m 644 deploy/edge/systemd/docker-after-awg.conf /etc/systemd/system/docker.service.d/10-lincodex-awg.conf && sudo systemctl daemon-reload`. Docker cannot publish a port on an address that does not exist yet, and containers with a restart policy start with the daemon, so the tunnel interface has to exist first.
|
|
3. Copy the committed tree of the repository to the host (`git archive HEAD`), copy `.env.example` to `.env` with mode 600, and generate the secrets on the host (passwords, S3 keys, and a `KAFKA_CLUSTER_ID` as described in `.env.example`). Set these values:
|
|
|
|
APP_HTTP_BIND=10.79.0.2
|
|
APP_PUBLIC_URL=https://<EDGE_DOMAIN>
|
|
EMAIL_PROVIDER=disabled
|
|
|
|
`APP_HTTP_BIND` is the address the frontend port is published on; the default `127.0.0.1` keeps a local stack private. `EMAIL_PROVIDER=disabled` sends no mail. To enable mail later, set `EMAIL_PROVIDER=resend`, `RESEND_API_KEY`, and `EMAIL_FROM` in the server `.env` and run `make -C deploy up` again; the key stays only in that file.
|
|
4. Start the stack with `make -C deploy up` and check `curl -s http://10.79.0.2:8080/healthz` on the app host.
|
|
|
|
### Firewall
|
|
|
|
On the edge host, ufw gains three rules: 80/tcp and 443/tcp to `EDGE_LISTEN_IP`, and the tunnel port over UDP to `AWG_EDGE_ENDPOINT_IP`. The host's other rules, WireGuard interface, and UDP 443 listener are untouched.
|
|
|
|
On the app host, ufw denies incoming traffic by default and rate-limits SSH. The rollout keeps SSH open to any source with `ufw limit`: the app host has only a private address behind NAT, and the operator's SSH source changes with the VPN path (both a LAN address and a VPN address were observed), so a source filter would lock the operator out. Narrow it to fixed sources only when they are known. The tunnel port needs no inbound rule because the app host initiates and replies are tracked connections. Arm a dead-man switch that disables ufw after five minutes, enable ufw, open a second SSH session, and only then stop the timer:
|
|
|
|
sudo systemd-run --unit=ufw-deadman --on-active=300 /usr/sbin/ufw --force disable
|
|
sudo ufw default deny incoming
|
|
sudo ufw default allow outgoing
|
|
sudo ufw limit 22/tcp comment "SSH"
|
|
sudo ufw allow in on awg-lincodex from 10.79.0.1 to 10.79.0.2 port 8080 proto tcp comment "lincodex edge to app"
|
|
sudo ufw --force enable
|
|
# From a new terminal: ssh <app-host> true, then:
|
|
sudo systemctl stop ufw-deadman.timer
|
|
|
|
Docker bypasses ufw for published ports: it adds its own NAT and FORWARD rules, so a ufw rule does not stop traffic to a published container port, and the last rule above does not govern it. The control that holds is the publish address. With `APP_HTTP_BIND=10.79.0.2`, the port answers only for packets addressed to the tunnel address, not on the LAN address or on loopback. A host on the same LAN can still send a packet addressed to `10.79.0.2` to the app host's MAC address if it adds a route for that address, so the port is protected from the network only by the tunnel being private and the LAN being trusted. Never publish the frontend port on `0.0.0.0`. Keep every other Compose port unpublished, as the stack already does.
|
|
|
|
### Renewal and reload
|
|
|
|
Ubuntu's `certbot.timer` runs `certbot renew` twice a day and renews a certificate that expires within 30 days. The renewal uses the webroot of the first issuance, so port 80 must keep serving `/.well-known/acme-challenge/`. After a renewal, the deploy hook `/etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh` runs `nginx -t && systemctl reload nginx`; it does not run when nothing was renewed. Check the pieces:
|
|
|
|
sudo certbot renew --dry-run --no-random-sleep-on-renew
|
|
systemctl list-timers certbot.timer
|
|
sudo certbot certificates
|
|
|
|
A reload starts new workers with the new certificate and configuration and lets the old workers finish their open connections, so in-flight requests and keep-alive connections are not dropped. The backend stores session state in PostgreSQL, not nginx: reloading or restarting nginx or the tunnel does not revoke a session while the backend and database remain available. The check below verifies only an in-flight request and keep-alive behavior across `systemctl reload nginx`; browser sign-in persistence after reload has not been verified end to end.
|
|
|
|
### Verification
|
|
|
|
curl -sI http://<domain>/ # 301 to https://<domain>/
|
|
curl -sv https://<domain>/ -o /dev/null # valid chain, HTTP/2, Strict-Transport-Security
|
|
curl -s https://<domain>/some/deep/link # the SPA index.html
|
|
curl -s https://<domain>/api/v1/healthz # 200 from Go through both Nginx instances
|
|
openssl s_client -connect <EDGE_LISTEN_IP>:443 -servername <domain> -tls1_1 # handshake fails
|
|
openssl s_client -connect <EDGE_LISTEN_IP>:443 -servername <domain> -tls1_2 # works
|
|
|
|
When the local resolver does not return the public address, add `--resolve <domain>:443:<EDGE_LISTEN_IP>` to the curl commands.
|
|
|
|
### Rollback
|
|
|
|
- Take the site off the air without touching the edge host's other services: `sudo rm /etc/nginx/conf.d/lincodex-https.conf && sudo nginx -t && sudo systemctl reload nginx`. Port 80 then redirects to an HTTPS address that no longer answers, so remove `lincodex-http.conf` too if the redirect is unwanted. `sudo systemctl disable --now nginx` stops nginx entirely.
|
|
- Remove the certificate: `sudo certbot delete --cert-name <domain>`, and the hook file if nothing else uses it. Disable `certbot.timer` only if no other certificate depends on it.
|
|
- Remove the firewall rules by number after `sudo ufw status numbered`, checking the rule text, never the existing ones: the 80/tcp, 443/tcp, and tunnel UDP rules carry a `lincodex` comment.
|
|
- Tunnel: `sudo systemctl disable --now awg-quick@awg-lincodex` on both hosts, then remove `/etc/systemd/system/awg-quick@awg-lincodex.service.d`, `/etc/systemd/system/docker.service.d/10-lincodex-awg.conf` (app host), `/etc/amnezia/amneziawg/awg-lincodex.*`, and `/usr/local/bin/amneziawg-go`; `sudo dpkg -r amneziawg-tools` removes the tools.
|
|
- App host: set `APP_HTTP_BIND=127.0.0.1` in `.env` and run `make -C deploy up` to publish the frontend on loopback again, or `make -C deploy down` to stop the stack (volumes are kept).
|
|
- Packages: `sudo apt-get remove nginx certbot` leaves `/etc/letsencrypt` in place; deleting it also deletes the private key.
|
|
|
|
### Limits
|
|
|
|
This is one edge host and one app host. There is no failover, no external uptime check, and no rate limiting at the edge (the frontend container applies coarse per-client limits, and the backend domain quotas are separate and not implemented yet). The certificate covers only the one name, the site is IPv4 only, and the ACME account has no contact address. The tunnel carries no authentication beyond the AmneziaWG keys, and the obfuscation parameters raise the cost of blocking but are not a security control.
|
|
|
|
## Isolated runner and lab host (LXD)
|
|
|
|
The code runner and the practical labs run as LXD virtual machines on the app host, outside the Docker stack. The layout is in `deploy/labs/`: `lxd-preseed.yaml` (storage pool, bridges, profiles) and `acls.sh` (network ACLs). Apply it once, as a member of the `lxd` group:
|
|
|
|
```bash
|
|
bash deploy/labs/acls.sh
|
|
```
|
|
|
|
```bash
|
|
lxd init --preseed < deploy/labs/lxd-preseed.yaml
|
|
```
|
|
|
|
What it creates:
|
|
|
|
- Storage pool `lincodex`: btrfs in a 40 GiB loop file, so lab nodes are cloned from prepared snapshots in seconds.
|
|
- Bridge `lxdbr-runner` (`10.80.0.1/24`) for the runner VM and bridge `lxdbr-labmgmt` (`10.81.0.1/24`) for the lab management plane. Both have no NAT, no DHCP and no DNS (`ipv4.dhcp=false`, `raw.dnsmasq: port=0`): the provisioner gives guests static addresses through cloud-init, so a guest has nothing to send towards the host.
|
|
- Network ACLs with default ingress and egress `drop`. `lincodex-runner` lets only the app network (`172.29.79.0/24`, matched before Docker masquerades it) and the host side of the bridge open TCP 8443; the token on the runner API authorizes the caller. `lincodex-labmgmt` lets only the host side open SSH and the RouterOS API (22, 8728, 8729) to the nodes. Guests can start no connection at all.
|
|
- Profiles `lincodex-runner` (2 vCPU, 3 GiB, 10 GiB disk) and `lincodex-lab-small` (1 vCPU, 768 MiB, 4 GiB disk). For a VM the memory limit is the guest RAM, so it cannot be exceeded.
|
|
|
|
The `lxd` group is equivalent to root on the host. Only the lab provisioner and the operator use it; the backend and the other containers never get the LXD socket.
|
|
|
|
Verified on the app host (TASK-592): from a guest on `lxdbr-runner` the internet, the host SSH, the bridge address, the app network and the LAN router are unreachable; from the app network only TCP 8443 of the guest is reachable; a VM with the lab profile boots under nested KVM and sees one CPU and about 700 MiB. The host `ufw` denies incoming traffic by default, which also blocks DHCP to the bridges; static addressing avoids opening it.
|
|
|
|
Cleanup before the rollout removed only the Docker build cache (`docker builder prune -af`, about 8 GB). `apt-get clean` and `journalctl --vacuum-size=100M` need sudo and are left to the operator. Docker volumes, the images of the running stack, `wg0`, `awg-lincodex` and the `ufw` rules are not touched.
|
|
|
|
## Code runner
|
|
|
|
The `runner/Dockerfile` image holds the Go supervisor, nsjail, Python from `python:alpine`, and, for Go solutions, the `compile` and `link` tools with a standard library prebuilt from `GO_IMAGE`; pip and ensurepip are removed. The base images are the `GO_IMAGE` and `RUNTIME_IMAGE` arguments, so a release build can pin their digests. The supervisor runs as root inside its own host or VM because it needs namespaces, user mapping, and writes to its delegated cgroup. Candidate programs run as uid 99999 without capabilities.
|
|
|
|
### Local (development only)
|
|
|
|
`deploy/docker/docker-compose.runner.dev.yml` is a separate dev project `runner-dev`. It gives the container `privileged: true`, because nsjail needs namespaces and a writable cgroup v2 tree inside the Docker Desktop VM, and it serves plain HTTP on 127.0.0.1 only. The file is never used by a release or in production; `make -C deploy check-runner-dev` checks that its switches stay out of the other Compose files, the production image, and the release tooling.
|
|
|
|
make -C deploy runner-dev-config
|
|
make -C deploy runner-dev-up
|
|
make -C deploy runner-dev-logs
|
|
make -C deploy runner-dev-down
|
|
|
|
`runner-dev-up` creates a local random token in `runner/.dev/api-token` (ignored by Git) when it is missing and starts the service on `127.0.0.1:${RUNNER_DEV_HTTP_PORT:-8070}`. Call it with `Authorization: Bearer $(cat runner/.dev/api-token)` and `PUT /v1/runs/<uuid>` from the `api/runner/` contract.
|
|
|
|
### Production: the runner VM
|
|
|
|
The runner runs only in the LXD virtual machine `lincodex-runner` on the `lxdbr-runner` bridge (see [the isolated runner host](#isolated-runner-and-lab-host-lxd)): a separate guest kernel, never the core host, never the dev file, and never a privileged container in place of the VM. TLS (`RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE`; the process does not start without them) and a token from a secret file (`RUNNER_API_TOKEN_FILE`) are required. `deploy/labs/runner-vm.sh` builds, updates, and checks the VM on the app host. It runs as a member of the `docker` and `lxd` groups without sudo and does not touch the Docker stack, `ufw`, `wg0`, `awg-lincodex`, or the LXD network, ACL, and profile objects. Monitoring of the VM and connecting the backend to it are not implemented yet; practice stays disabled.
|
|
|
|
make -C runner a16-bundle # on a machine with Go; copy runner/bin/a16-bundle.tar.gz to the host
|
|
make -C deploy runner-vm-up # app host: secrets, file system, VM (once), install, checks
|
|
make -C deploy runner-vm-a16 A16_BUNDLE=<path to a16-bundle.tar.gz>
|
|
make -C deploy runner-vm-check
|
|
|
|
Before practice is enabled, the A16 suite runs on the VM with `make -C deploy runner-vm-a16`: the bundle runs in a transient systemd unit with the same sandbox settings as the service, and the JSON report lands in `~/lincodex-runner/reports/`. By hand, `sh run-a16.sh` as root in the unpacked bundle with the service's `RUNNER_*` variables does the same; it needs nsjail, Python, and the Go tool directory at the configured paths, a delegated cgroup v2, and a work directory on a tmpfs with `exec`. A non-zero exit status or the verdict `fail` in the report blocks enabling practice. When the runner runs in a container, start the container with an init (`--init` or `init: true`) or under systemd, so that the rare process left after an OOM kill of nsjail is reaped.
|
|
|
|
| Variable | Default | Purpose |
|
|
| --- | --- | --- |
|
|
| `RUNNER_LISTEN_ADDRESS` | `:8443` | HTTP(S) address |
|
|
| `RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE` | none | TLS 1.3 certificate and key; required outside dev |
|
|
| `RUNNER_API_TOKEN_FILE` or `RUNNER_API_TOKEN` | none | Token of at least 32 characters; prefer the file |
|
|
| `RUNNER_DEV_ALLOW_PLAINTEXT_HTTP` | `false` | Dev Compose only: HTTP without TLS |
|
|
| `RUNNER_MAX_CONCURRENT_RUNS` | `1` | Concurrent runs; more answer 503 `runner_busy` |
|
|
| `RUNNER_MAX_REQUEST_BYTES` | `8388608` | Request body limit |
|
|
| `RUNNER_RESULT_TTL`, `RUNNER_MAX_RETAINED_RUNS` | `15m`, `256` | In-memory result retention |
|
|
| `RUNNER_RETRY_AFTER`, `RUNNER_SHUTDOWN_TIMEOUT` | `2s`, `30s` | Retry-After when busy and the wait for runs at shutdown |
|
|
| `RUNNER_WORK_DIR` | `/var/lib/lincodex-runner/work` | Run directories; emptied at startup; a tmpfs with `exec` (built Go solutions run from it), `nosuid`, and `nodev` |
|
|
| `RUNNER_CGROUP_ROOT` | `/sys/fs/cgroup` | The service's delegated cgroup v2 |
|
|
| `RUNNER_NSJAIL_PATH`, `RUNNER_PYTHON_PATH` | `/usr/bin/nsjail`, `/usr/local/bin/python3` | Paths in the image |
|
|
| `RUNNER_GO_TOOL_DIR` | `/usr/local/lib/lincodex-runner/go` | `compile`, `link`, `importcfg`, and the prebuilt Go standard library in the image |
|
|
| `RUNNER_SANDBOX_UID` | `99999` | Program user, never root |
|
|
| `RUNNER_SANDBOX_MAX_PROCESSES` | `16` | Processes and threads of a run |
|
|
| `RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES` | `4194304` | Memory allowance for nsjail above the task limit |
|
|
| `RUNNER_SANDBOX_TMPFS_BYTES`, `RUNNER_SANDBOX_FILE_SIZE_BYTES`, `RUNNER_SANDBOX_OPEN_FILES` | `16777216`, `8388608`, `64` | `/tmp` size, file size, and open files |
|
|
| `RUNNER_LOG_LEVEL` | `info` | JSON log level |
|
|
|
|
#### Steps of the VM script
|
|
|
|
| Target | What it does |
|
|
| --- | --- |
|
|
| `runner-vm-secrets` | In `~/lincodex-runner/secrets` (`RUNNER_VM_STATE_DIR` moves it; directory 0700, files 0600): a private ECDSA P-256 CA for 5 years, a server certificate for `IP:10.80.0.10` with `serverAuth` for 397 days (the next run reissues it when it expires within 30 days), the token (`openssl rand -hex 32`), and the `Authorization` header file for curl. Existing files are kept. The CA key never leaves the host. |
|
|
| `runner-vm-rootfs` | `docker build` of `runner/Dockerfile` on the host and `docker export` of its file system to `~/lincodex-runner/runner-rootfs.tar.gz`. The image is not needed afterwards: `docker image rm lincodex-runner-vm:<version>` and `docker builder prune` free the space. |
|
|
| `runner-vm-create` | `lxc init images:debian/12/cloud --vm` with only the `lincodex-runner` profile (no default profile, so no other NIC or disk) and `boot.autostart=true`. cloud-init gets a static `10.80.0.10/24` matched by the MAC address, without gateway, DNS, or DHCP. After the first boot cloud-init is disabled and `security.devlxd=false` turns off the guest API. |
|
|
| `runner-vm-install` | Masks SSH and the apt and maintenance timers and disables IPv6 in the guest; pushes the file system to `/opt/lincodex-runner/root` and the TLS pair and token to `/etc/lincodex-runner` (root, 0600); writes `lincodex-runner.service`, swaps the root, restarts the service, and waits for `/readyz`. |
|
|
| `runner-vm-a16` | Runs the A16 suite in the VM (see above). |
|
|
| `runner-vm-check` | Prints PASS or FAIL per check and fails on any FAIL: the instance type, devices, and limits; health, readiness, 401 without or with a wrong token, TLS 1.2 refused, and plain HTTP not served from the host side; a harmless Python and Go run accepted; readiness and 401 from a throwaway curl container on the app network; and in the guest the service, CPUs, memory, delegated cgroup, mounts, Docker socket, secret files, the service environment, an empty work directory and no run cgroup after the runs, no default route, IPv6 off, and blocked connections to the host, the app network, the LAN gateway, and the internet. |
|
|
|
|
#### The service in the VM
|
|
|
|
systemd runs the Go supervisor with `RootDirectory=/opt/lincodex-runner/root` (the image file system with nsjail, Python, and the Go tools), `Delegate=yes` and `RUNNER_CGROUP_ROOT` set to the unit's own cgroup, and a fresh 256 MiB tmpfs for `RUNNER_WORK_DIR` on every start (`exec`, `nosuid`, `nodev`). It adds `ProtectSystem=strict`, `PrivateTmp`, `NoNewPrivileges`, `MemoryMax=2560M`, `TasksMax=512`, `IPAddressDeny=any` with `IPAddressAllow` for the host side of the bridge and the app subnet, and `RUNNER_MAX_CONCURRENT_RUNS=1`. The secrets directory is bound read-only. systemd reaps a process orphaned by an OOM kill of nsjail, and `KillMode=control-group` stops every process with the service. The VM has no default route; the bridge ACL drops every connection it starts. The backend reaches `https://10.80.0.10:8443` from the app network: Docker masquerades that traffic to the bridge address, and the ACL matches the app subnet before that. The token and `ca.crt` for the backend are in the secrets directory; the stand `.env` does not use them yet.
|
|
|
|
#### Verification on the app host
|
|
|
|
Checked on 2026-10-11 with the runner at commit `dcf03cb861e2` plus two fixes. The amd64 seccomp fix: kafel names `umount2` as `umount`, and the name `umount2` made nsjail reject the whole policy, so every run ended in `infrastructure_failure`. The A16 fix: `go_thread_bomb` now starts a bounded 256 goroutines blocked in system calls, because its unbounded loop raced the memory limit against the process limit (7 of 20 runs failed); the unbounded goroutine loop moved to the memory case `go_goroutine_bomb`; and the weakened-limit check waits up to 2 s for killed sandbox processes to finish exiting.
|
|
|
|
- `runner-vm-check` passes all 49 checks on a VM created from scratch by `runner-vm-up` (about 2 minutes with a cached image).
|
|
- A16 in the VM: 20 of 20 runs pass 32 of 32 cases with exit status 0 and `nothing_left_after_runs: true`.
|
|
- Resources: the guest sees 2 vCPUs and 2885 MiB and uses about 380 MiB at rest. QEMU on the host holds about 1 GiB after 20 A16 runs; it can grow up to the 3 GiB of guest RAM plus QEMU overhead. At rest the VM takes about 0.6% of one host core. Host memory in use went from 1.8 GiB to 2.9 GiB. The guest root uses 1.4 of 10 GiB.
|
|
|
|
#### Removal
|
|
|
|
`lxc delete --force lincodex-runner` removes the VM with its file system and its copy of the secrets. `rm -rf ~/lincodex-runner` removes the CA, the token, the reports, and the exported file system on the host. LXD keeps the downloaded Debian image until its cache expires (`lxc image list`).
|
|
|
|
## Code runner client
|
|
|
|
The backend calls the own code runner (see [the runner](ARCHITECTURE.md#code-runner)) through the `CodeRunner` port. It is off unless `CODE_RUNNER_URL` is set: the backend then selects a disabled runner, logs `code runner selected` with `enabled=false` and a warning, and reports every request as unavailable without running or grading anything. `.env.example` and the Compose file pass every variable below as empty, so a default stack never contacts a runner. Nothing in this build calls the port yet; the settings are validated at startup and the TLS client is built (no network call), so a wrong value fails fast.
|
|
|
|
When `CODE_RUNNER_URL` is empty, no other `CODE_RUNNER_*` variable may be set: the backend refuses to start rather than ignore a token. Errors name the setting and never print its value; the startup log names neither the URL nor a secret.
|
|
|
|
| Variable | Default | Validation |
|
|
| --- | --- | --- |
|
|
| `CODE_RUNNER_URL` | empty, runner off | `https` origin of the runner, for example `https://10.80.0.10:8443`: valid host and port, no credentials, path, query, or fragment. Plain HTTP is refused, including for the local dev runner, which serves HTTP; use a TLS runner and its CA. |
|
|
| `CODE_RUNNER_TOKEN` | none, required with the URL | The runner's service token (`RUNNER_API_TOKEN`): 32 to 256 printable ASCII characters without spaces. Secret. |
|
|
| `CODE_RUNNER_RUN_KEY` | none, required with the URL | Key of the HMAC that derives opaque run IDs, so the runner never sees attempt or submission identifiers: 32 to 256 printable ASCII characters, different from the token. Secret. Generate it with `openssl rand -hex 32`. Changing it makes retries of in-flight submissions start new runs, which the runner forgets after its retention time. |
|
|
| `CODE_RUNNER_CA_FILE` or `CODE_RUNNER_CA_PEM` | none, exactly one required with the URL | The CA that signed the runner certificate: a PEM file path inside the container, or the PEM text (`\n` may stand for line breaks). Only this CA is trusted; the system roots are not. Compose does not mount the file, so a deployment either mounts it or uses the inline form. |
|
|
| `CODE_RUNNER_SERVER_NAME` | the host of the URL | Name the certificate is verified against, for a runner addressed by an IP its certificate does not list. Verification stays on. |
|
|
| `CODE_RUNNER_REQUEST_TIMEOUT` | `10s` | Go duration from `1s` to `1m`; limits one request. A timeout is an infrastructure error, never a verdict. |
|
|
|
|
The connection uses TLS 1.3 only and follows no redirects or environment proxies. The deployment of the runner VM, the certificate, and storing the token for the backend are described in the runner sections above and are not part of this build; the token and the run key belong in the server environment or a secret store and are never committed.
|
|
|
|
Checking a real runner. The unit tests run against a local protocol stand-in. To run fixed harmless programs (Python and Go, an accepted answer, a wrong answer, a syntax error, and a wrong token) on a prepared runner, export the same variables the backend uses and run:
|
|
|
|
export CODE_RUNNER_URL=https://10.80.0.10:8443
|
|
export CODE_RUNNER_TOKEN=... # from the secret store
|
|
export CODE_RUNNER_CA_FILE=/path/to/runner-ca.pem
|
|
make -C backend test-code-runner-live
|
|
|
|
`CODE_RUNNER_SERVER_NAME` is honored too. The target stops with an error when the three variables are unset, and the same tests are skipped by a plain `go test` because they run only when `CODE_RUNNER_LIVE_URL` is set. A pass proves that the client, the TLS settings, the token, and the runner agree on the protocol and that the runner grades the fixed programs as expected; it does not replace the A16 suite.
|
|
|
|
## Services and images
|
|
|
|
Container images use moving `latest` or `alpine` tags where the upstream publishes them. Check the current Compose references when updating the stack. These tags can move; the [release manifest](#release-manifest) records the actual image digests of a release. An SBOM is not produced yet. Application dependency lockfiles remain checked in separately.
|
|
|
|
| Component | Current image source | Principal upstream license |
|
|
| --- | --- | --- |
|
|
| PostgreSQL | Docker Official Image, docker-library/postgres | PostgreSQL License for the server; packaging repository is MIT |
|
|
| SeaweedFS | chrislusf/seaweedfs | [Apache-2.0](https://github.com/seaweedfs/seaweedfs/blob/master/LICENSE) |
|
|
| Apache Kafka | apache/kafka, the Apache Kafka project's image | [Apache-2.0](https://github.com/apache/kafka/blob/trunk/LICENSE) |
|
|
| Prometheus | prom/prometheus | Apache-2.0 |
|
|
| Loki | grafana/loki | AGPL-3.0-only by default; see LICENSING.md exceptions |
|
|
| Grafana Alloy | grafana/alloy | Apache-2.0 by default |
|
|
| Grafana | grafana/grafana | AGPL-3.0-only by default |
|
|
| Node exporter | prometheus/node_exporter | Apache-2.0 |
|
|
| PostgreSQL exporter | prometheus-community/postgres_exporter | Apache-2.0 |
|
|
| Docker socket proxy | Tecnativa/docker-socket-proxy | Apache-2.0 |
|
|
| BusyBox | busybox | GPL-2.0-only |
|
|
| nsjail | Alpine `nsjail` package in the code runner image | [Apache-2.0](https://github.com/google/nsjail/blob/master/LICENSE) |
|
|
|
|
Upstream references: [PostgreSQL image](https://github.com/docker-library/postgres), [Prometheus](https://github.com/prometheus/prometheus/blob/main/LICENSE), [Loki license details](https://github.com/grafana/loki/blob/main/LICENSING.md), [Alloy license details](https://github.com/grafana/alloy/blob/main/LICENSING.md), [Grafana license details](https://github.com/grafana/grafana/blob/main/LICENSING.md), [node_exporter](https://github.com/prometheus/node_exporter/blob/master/LICENSE), [postgres_exporter](https://github.com/prometheus-community/postgres_exporter/blob/master/LICENSE), [socket proxy](https://github.com/Tecnativa/docker-socket-proxy), [BusyBox license](https://busybox.net/license.html).
|
|
|
|
These entries name the principal upstream project's license; they are not a complete inventory of every file in an image. Base OS packages and bundled dependencies may have separate terms. Before redistribution, inspect the exact image tag or digest, its notices, and an SBOM. This repository has no project-wide license.
|
|
|
|
The backend builds with Go 1.26.9; its runtime image is selected in backend/Dockerfile. Frontend and ML base images are selected in their Dockerfiles. Upstream sources include [Docker Official Images](https://github.com/docker-library), [Distroless](https://github.com/GoogleContainerTools/distroless), and [NGINX unprivileged images](https://github.com/nginxinc/docker-nginx-unprivileged); inspect exact tags and layers before distribution.
|
|
|
|
## Release manifest
|
|
|
|
A release manifest records the source, toolchains, lockfile hashes, Compose file hashes, image IDs and digests, and versioned data inputs for one local delivery. Compose may keep moving `latest` and `alpine` tags; restoring a release uses the image IDs or repository digests recorded in its manifest, never a fresh lookup of those tags. The default release ID is the commit-based tag. Use a short `RELEASE_ID` when the same source has more than one delivery or when its data or stage changes:
|
|
|
|
make -C deploy release-build
|
|
make -C deploy release-smoke
|
|
make -C deploy release-e2e
|
|
make -C deploy release-manifest RELEASE_ID=demo-stage-1
|
|
make -C deploy release-manifest-check RELEASE_ID=demo-stage-1
|
|
make -C deploy release-up RELEASE_ID=demo-stage-1
|
|
make -C deploy demo-seed DEMO_MODE=isolated RELEASE_ID=demo-stage-1
|
|
|
|
- `release-build` builds `backend`, `frontend`, the `demo-seed` command, and `ml` from their Dockerfiles and lockfiles through Compose and tags them `lincodex.invalid/<service>:<tag>`. The demo seed image is rendered from the core files, `docker-compose.demo.yml`, and its overlay `docker-compose.demo.release.yml` under the `demo-seed` profile. The `.invalid` domain never resolves, and the release overlays set `pull_policy: never`, so a missing release image is never pulled from a registry. Each Dockerfile takes its base images as `*_IMAGE` build arguments whose defaults are the agreed tags; the target resolves each base to its repository digest in the local image store and builds with `<tag>@<digest>`. A base image used through `COPY --from` or `RUN --mount=from` that is not an earlier stage is refused, because it could not be pinned. Base and core service images are pulled only when missing locally; `RELEASE_PULL=always` refreshes every tag first. The target reads the source state again after the build and writes `build.json` (build arguments, base digests, image IDs) only if the commit and the working tree did not change during the build.
|
|
- `release-smoke` and `release-e2e` run `deploy/scripts/smoke.sh` and `deploy/scripts/e2e.sh` with `LINCODEX_RELEASE_TAG`, which only these targets set: the stack starts from the release images with `--no-build --pull never`, and only after every check passes does the script write `evidence-smoke.json` or `evidence-e2e.json` with the release tag, commit, working tree fingerprint, and the image IDs of the running containers. A failed run writes nothing. Evidence written after the checks passed stays even if the stack cleanup fails afterwards; the script still exits with an error then.
|
|
- `release-manifest` reads local images, the build record, evidence, and optionally a data descriptor. It pulls nothing. It publishes only a `verified` candidate. A dirty tree, a build record that does not match the source, or missing or rejected required evidence makes the command exit before it creates `manifest.json` or retention tags for built images; the error lists the verification reasons. Fix the source or evidence and rerun the required checks. `RELEASE_DATA_MANIFEST=<path>` selects a repository-relative JSON file using schema `lincodex.release-data/v1`; it describes `bank`, `policy`, and `seed` as either available with a version and artifact paths, or unavailable with a reason. Artifact paths must be normalized repository-relative paths without symlinks or environment files. The manifest stores their SHA-256 hashes and sizes; restore checks the files still match. Descriptors, artifact counts, and sizes have explicit limits.
|
|
- Without a data descriptor, the manifest records bundled demo policy source version `1` and hashes `backend/internal/domain/policy_demo.go`. This identifies the shipped definition only; it does not report the policy row currently stored in PostgreSQL, because startup leaves an existing row unchanged. Version `1` is the startup version; the [demo seed](#isolated-demo-stand) publishes `DemoProductPolicyV4` over it, and that choice is part of the seed source. The `seed` entry is the bundled demo seed source: the non-test Go files of `backend/internal/usecase/demoseed` (accounts, organizations, the synthetic bank families, and the prepared attempts) with their hashes, and version `demo-seed.<12 hex digits>` derived from those paths and hashes, so any change of the dataset gives a new version. The demo seed image compiles the same files. The assessment bank has no accepted release snapshot (the synthetic demo bank is versioned within the seed), so `bank` remains unavailable and `product_data_status` is `partial`. This is not a full MVP readiness result.
|
|
- The manifest is published once at `deploy/release/<release-id>/manifest.json`. A release ID is a validated 1-64 character slug. A second run with identical content leaves the original bytes and modification time unchanged; changed data or stage under the same ID fails and requires a new ID. Publication is serialized per ID and creates the file atomically, without replacing an existing manifest. Build and evidence records remain under `deploy/release/<source-tag>/`.
|
|
- `release-manifest-check` checks the manifest location and structure and scans it for secrets and machine data. `RELEASE_MANIFEST=<path>` selects an exact artifact for check, verify, restore, or down; otherwise `RELEASE_ID` selects it, falling back to the current commit-based ID.
|
|
- `release-up` verifies the Compose file hashes, data artifact hashes, local built image IDs, pulled image digests, and recorded image IDs for verified checks before starting Compose. It writes a private temporary Compose override with each built service pinned directly to its image ID, then uses `--no-build --pull never`; the retained image tag is not used to resolve the service. After startup it checks each running container against the manifest. Use the same `APP_PROJECT`, `ENV_FILE`, and manifest for `release-down`. Named volumes remain in the project and are not database backups or snapshots.
|
|
- `make -C deploy release-manifest-verify RELEASE_VERIFY_PROJECT=<project>` compares running container image IDs with the selected manifest and exits with status 1 on a mismatch, missing service, or unknown service. It also works for the demo project (`RELEASE_VERIFY_PROJECT=lincodex-demo`); the one-off seed container is not compared.
|
|
- `restore.demo` tells whether the [isolated demo stand](#isolated-demo-stand) can be restored from the same delivery: it needs an available core restore, the demo seed image built by `release-build` and retained by its image ID, a demo seed binary built with the go.mod Go version, and the hashes of the demo Compose files. Publication retains the demo seed image under `lincodex.invalid/release/demo-seed:<release-id>` like the built core images.
|
|
- `release-clean` removes local release image references that no immutable manifest retains and keeps the files in `deploy/release/`.
|
|
|
|
The source tag is the first 12 characters of the commit, with `-dirty` when the working tree differs from it. The working tree fingerprint is the Git tree ID written from a temporary index (seeded from HEAD, then `git add -A`), with line ending, file mode, symlink, and fsmonitor settings pinned. It covers modified, deleted, and untracked files, does not depend on diff settings, and leaves the real index untouched. Build and evidence records go to `deploy/release/<source-tag>/`; immutable manifests go to `deploy/release/<release-id>/`. Git and the root `.dockerignore` ignore these local artifacts. Manifests are not committed: built image IDs depend on the machine, platform, and build time, and each manifest describes what this machine built and checked. Attach a manifest to the delivery when needed.
|
|
|
|
### Format
|
|
|
|
The manifest is JSON with sorted keys and schema `lincodex.release-manifest/v2`:
|
|
|
|
| Key | Content |
|
|
| --- | --- |
|
|
| `schema`, `generated_at` | Schema version and UTC generation time |
|
|
| `release` | Immutable `id`, source `tag`, core `status` (`verified` or `unverified`), `product_data_status` (`versioned`, `partial`, or `unavailable`), `required_checks` (`smoke`, `e2e`), and reasons |
|
|
| `restore` | Whether the core Compose project can be restored, its command, and any preflight blocking reasons; `demo` holds the same for the isolated demo stand |
|
|
| `source` | `commit`, `dirty`, the working tree `fingerprint` (`git-tree:<id>`, or null for a clean tree), and `build_matches_source` |
|
|
| `toolchains` | Go from go.mod, its `toolchain` directive, the `GO_IMAGE` default, `GOTOOLCHAIN=local`, the base image version, and the version recorded in the backend binary; the same pin of `backend/Dockerfile.demo-seed` and the version in the demo seed binary; Node and pnpm from `.node-version`, `packageManager`, the Dockerfile, and the base image; Python and uv from `.python-version`, `requires-python`, the Dockerfile, and the base image; `matches_version_file` for Node and Python; the Playwright package version |
|
|
| `lockfiles` | SHA-256 of `backend/go.mod`, `backend/go.sum`, `frontend/package.json`, `frontend/pnpm-lock.yaml`, `ml/pyproject.toml`, and `ml/uv.lock` |
|
|
| `configuration`, `data_versions` | SHA-256 hashes of the core and demo stand Compose files; bank, policy, and seed versions with bounded artifact paths, hashes, sizes, or an explicit unavailable reason |
|
|
| `checks`, `rejected_checks` | Accepted evidence with its scope, finish time, commit, fingerprint, tool image, and image IDs; rejected evidence with the reason |
|
|
| `components` | Each Compose service of core, the demo seed, ML, and monitoring and each missing component: `group`, `kind` (`built`, `pulled`, `absent`), image metadata, exact `restore_reference`, optional built-image retention reference, build details, and `verification` |
|
|
|
|
`verification.status` is one of:
|
|
|
|
- `verified`: at least one accepted smoke or E2E run recorded this exact image ID for the service. `verification.checks` lists which. Only core services can be verified.
|
|
- `not_verified`: the image is absent, was not in an accepted passing run, or belongs to a group no release check starts. The demo seed image is built and pinned for the demo stand, but no release check runs it; ML is built but no check starts it and it has no model; monitoring images are recorded only when present locally.
|
|
- `missing`: the component is planned but has no service or image in this repository: GPU inference, Judge0, and Qdrant.
|
|
|
|
The release is `verified` only when all of the following hold; otherwise `release.reasons` names each failed condition:
|
|
|
|
- the working tree is clean and the build record is well formed and matches the current source;
|
|
- every core image was built by `release-build`, and every core pulled image has a registry digest;
|
|
- both smoke and E2E evidence for the current source passed on the current image ID of every core component;
|
|
- every lockfile and every service Dockerfile exists;
|
|
- the Go pin is consistent and the backend binary, and the demo seed binary when its image is present, report the go.mod Go version;
|
|
- Node in the frontend build image equals `frontend/.node-version`.
|
|
|
|
A Python version that differs from `ml/.python-version` is reported in `matches_version_file` but does not block the release, because ML is outside the verified scope. A moving `node:alpine` tag can therefore make a release unverified until `.node-version` is updated. A dirty tree is rejected by `release-manifest`; it reports the verification reasons and leaves no new manifest.
|
|
|
|
Generating the manifest again for the same ID, source, images, evidence, and data leaves the submitted file unchanged. A new data snapshot or stage gets a new ID. Version fields are copied only from an allowlist of image variables and OCI labels. The manifest never contains environment values, `.env` content, container labels, mounts, local paths, user or host names; every file is scanned for those, for values of variables whose names suggest secrets (also as substrings and in base64), and for secret patterns before it is written, and `release-manifest-check` repeats the scan.
|
|
|
|
### Go pin
|
|
|
|
go.mod declares `go 1.26.9` without a separate `toolchain` line, the default `GO_IMAGE` of `backend/Dockerfile` and `backend/Dockerfile.demo-seed` is `golang:1.26.9-alpine`, and both build stages set `GOTOOLCHAIN=local`, so a go.mod that asks for a newer Go fails the build instead of downloading another toolchain. `make -C deploy check` fails when these pins disagree or when a Dockerfile uses a base image that is not a pinnable build argument. The manifest also records the version read from the build information of the backend and demo seed binaries; to read it, the generator creates a container from the image without starting it, copies the binary out, and removes the container.
|
|
|
|
### Not covered
|
|
|
|
- The manifest is not an SBOM, a license inventory, a signature, or a provenance attestation, and it is not pushed to a registry. A restore reinstates images and Compose configuration; it does not restore or validate database contents or persistent volume backups.
|
|
- The files in `deploy/release/` are local and not tamper-proof; evidence is not signed and proves only what this machine recorded.
|
|
- Git-ignored files are not part of the fingerprint. A build context still receives such files unless `.dockerignore` excludes them.
|
|
- Images are built for the local platform only. Versions without an image variable or label, such as Kafka, are identified only by digest.
|
|
- `verified` means the image passed the recorded technical checks. Kafka publication, product workflows, ML, monitoring, backups, and production hosts are not checked.
|
|
- CI runs `check-release` as part of `make -C deploy check`, but not the release build, the release runs, or the manifest targets.
|
|
|
|
## Observability configuration
|
|
|
|
Prometheus scrapes backend /metrics on port 9090, PostgreSQL exporter, Redis exporter on port 9121, SeaweedFS on port 9327, node exporter, itself, and the optional ML target. Loki uses a single-binary filesystem store with 168-hour retention. Grafana provisions Prometheus and Loki datasources from observability/grafana/provisioning/.
|
|
|
|
The six checked-in dashboard JSON files are maintained as project dashboards: Go runtime, PostgreSQL, Redis, SeaweedFS, Linux system, and Lincodex product (`lincodex-product.json`, described in [Separate monitoring Compose project](#separate-monitoring-compose-project)). Prometheus loads `prometheus/rules/*.yml`; `make -C observability check` validates them with `promtool check config` and runs their unit tests in `prometheus/tests/` with `promtool test rules`. The Redis dashboard covers availability, memory, cache hits/misses, evictions/expired keys, and client connections. The exporter collects aggregate metrics without scanning keys. The SeaweedFS dashboard covers availability, S3 request rate and duration, errors, disk, and memory; Prometheus retains only selected aggregate metrics without object paths. They were not copied from Grafana dashboard IDs. No external dashboard provenance or license is claimed for them.
|
|
|
|
The local monitoring stack is a single-node development/demo setup and provides no HA. Compose validation does not establish production retention, off-host backups, public access control, alert delivery, or core application behavior.
|
|
|
|
Workflow files exist in .github/workflows/. Their presence does not mean they have run on GitHub. Branch protection should require two checks: `Required CI result` from ci.yml and `Required documentation result` from docs.yml. See the testing guide for the difference between configuration validation, an infrastructure smoke, and product-flow tests.
|