277 lines
23 KiB
Markdown
277 lines
23 KiB
Markdown
# Running and deploying
|
|
|
|
Run commands from the repository root. Install Docker with Compose, GNU make, Python 3, and OpenSSL. Go operator commands need the toolchain from `backend/go.mod`; they read exported environment variables rather than loading `.env` automatically. Settings are described in [.env.example](../../.env.example); defaults and container environment bindings are in [deploy/Makefile](../../deploy/Makefile) and [Compose](../../deploy/docker/).
|
|
|
|
## Running the MVP: quick start
|
|
|
|
If `.env` does not exist, copy `.env.example`, replace `replace-this-*`, and set `IDENTITY_KEY_SECRET` to a random secret (`openssl rand -base64 48`). The PostgreSQL password is part of the connection URL, so use URL-safe characters such as hex. This file contains secrets and must stay out of Git.
|
|
|
|
```sh
|
|
make -C deploy config
|
|
make -C deploy up
|
|
curl --fail http://localhost:8080/api/v1/healthz
|
|
```
|
|
|
|
`config` validates example settings; `up` reads the real `.env`. The `app` project starts frontend Nginx, the Go backend, PostgreSQL, Redis, SeaweedFS, and Kafka. The backend applies migrations on startup. An empty database has no question bank or prepared accounts; use the [demo stand](#isolated-demo-stand) to demonstrate the product.
|
|
|
|
| Component | Start | Default address |
|
|
| --- | --- | --- |
|
|
| Core | `make -C deploy up` | `http://localhost:8080` |
|
|
| Synthetic demonstration | `make -C deploy demo-seed DEMO_MODE=isolated` | `http://localhost:8090` |
|
|
| ML, after core | `make -C deploy ml-up` | `127.0.0.1:8000` |
|
|
| Monitoring, after core | `make -C deploy monitoring-up` | Grafana: `127.0.0.1:3000` |
|
|
| Development code runner | `make -C deploy runner-dev-up` | `127.0.0.1:8070` |
|
|
|
|
ML, monitoring, the runner, and labd do not start with core. Pass the same project name to every command, for example `APP_PROJECT=my-app` for `up`, `logs`, and `down`. Make does not read the project name from `.env`.
|
|
|
|
## Core service
|
|
|
|
`make -C deploy logs` follows logs. `make -C deploy down` preserves named volumes; stop monitoring before core. PostgreSQL, SeaweedFS, and Kafka persist data in volumes; Redis is a bounded cache without persistence. Removing volumes destroys their data. A single Compose host provides neither HA nor off-host backups.
|
|
|
|
### Public perimeter and client address
|
|
|
|
Frontend Nginx is the HTTP entry point, serving the SPA and `/api/v1/` on one origin. Open exactly `APP_PUBLIC_URL`; unsafe requests check Origin and, for sessions, a CSRF token. Use `localhost` for local HTTP and HTTPS for a public hostname: the session cookie has the `Secure` flag.
|
|
|
|
Keep `APP_HTTP_BIND=127.0.0.1` locally or use a private tunnel address. Do not publish the backend, `/metrics`, databases, broker, or storage. Docker port publishing can bypass ufw rules. `TRUSTED_PROXY_CIDRS` must trust only frontend Nginx; coordinate proxy addresses and ACLs when changing `APP_SUBNET` or `APP_FRONTEND_IP`.
|
|
|
|
### Outbox relay
|
|
|
|
The backend publishes outbox records to Kafka and runs event consumers and scheduled jobs in the same process. `RELAY_*`, `CONSUMER_*`, and `JOBS_*` settings live in [backend/config](../../backend/config/). Adding a variable to `.env` affects a container only if Compose explicitly passes it. Keep a margin in `stop_grace_period` when increasing shutdown timeouts.
|
|
|
|
### Event consumers
|
|
|
|
Watch outbox age, consumer errors, and due jobs in Grafana. Inspect dead letters in the database and Kafka lag through the broker CLI. Delivery permits retries; handlers deduplicate events. Changing `CONSUMER_GROUP_PREFIX` creates new groups that read retained events from the beginning.
|
|
|
|
#### Dead letters and replay
|
|
|
|
After fixing the cause, inspect the record in `consumer_dead_letters`. For a known `event_id`, republish its retained outbox row by clearing only that row's `published_at`; successful handlers recognize the duplicate. This does not repair an `invalid_record`. Stop all members of the affected group before manually resetting Kafka offsets. `consumer_processed_events` records successful processing; do not copy payloads or personal data into incident logs.
|
|
|
|
### Scheduled jobs
|
|
|
|
`scheduled_jobs` stores state and errors. After fixing the cause, retry only the affected job according to its handler; do not reset the entire queue. Synchronize backend clocks through NTP because deadlines and leases use application time. Practice uses a separate queue described below.
|
|
|
|
## Mail
|
|
|
|
| Mode | Requirements |
|
|
| --- | --- |
|
|
| `EMAIL_PROVIDER=disabled` | Sends nothing; a newly registered account remains unverified |
|
|
| `EMAIL_PROVIDER=resend` | `RESEND_API_KEY`, `EMAIL_FROM` on a verified domain, and the correct `APP_PUBLIC_URL` |
|
|
| `EMAIL_PROVIDER=smtp` | Configuration exists, but the transport is not implemented; backend startup fails |
|
|
|
|
### Mail deliveries
|
|
|
|
Resend sends email confirmation and supported product notifications through the outbox. A transport failure is not a successful delivery. `make -C deploy test-e2e-registration` uses a local Resend-compatible inbox, not a real provider account.
|
|
|
|
### Mail quotas
|
|
|
|
`EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` limit recipients by UTC periods, defaulting to 100 and 3000. `EMAIL_SERVICE_RESERVE_*` reserve part of those limits for service mail. `EMAIL_ACCOUNT` identifies the actual provider account; do not rename it to bypass local accounting. Application defaults do not guarantee a provider plan or quota.
|
|
|
|
### Mail templates
|
|
|
|
Templates and rendering live in `backend/internal/usecase/notification/mailtemplate/`. Send only data the recipient needs; the one-time link and code belong in verification mail. Service keys and data the recipient may no longer access must not be included.
|
|
|
|
## Isolated demo stand
|
|
|
|
```sh
|
|
make -C deploy demo-seed DEMO_MODE=isolated
|
|
make -C deploy monitoring-up DEMO_MODE=isolated
|
|
make -C deploy demo-down DEMO_MODE=isolated
|
|
```
|
|
|
|
The seed creates a separate `lincodex-demo` project, bank, and synthetic accounts; repeated runs are idempotent. The local frontend is available at `http://localhost:8090`; you do not need to pass `APP_HTTP_BIND` on the command line. The target uses the root `.env` and `deploy/demo/demo.env`, falling back to the public example if the latter is absent. The command prints logins; `DEMO_ACCOUNT_PASSWORD` sets their password. For external access, choose your own password and share it separately with participants.
|
|
|
|
The guide is at `/demo`. Main accounts: `candidate@demo.lincodex.test`, `prepared-1@demo.lincodex.test` through `prepared-6@demo.lincodex.test`, `employer-alpha@demo.lincodex.test`, and `employer-beta@demo.lincodex.test`. Follow the candidate from assessment to result, then send an invitation as the employer and accept it as the candidate with selected contacts.
|
|
|
|
`demo-reset DEMO_MODE=isolated` deletes and reseeds only its project; it refuses to run when ordinary accounts exist. Do not use this stand for real people. Demo categories are uncalibrated, and the express run awards no grade. The official FSP integration is not connected.
|
|
|
|
### Demonstration scenario
|
|
|
|
1. Complete the candidate profile and questionnaire, take a test or open a prepared result. The Backend Junior bank with Go is synthetic; `demo_express` assigns neither a grade nor evidence.
|
|
2. Grant C2 and publish the card after previewing it. Anonymous results need a sufficiently large group: one published candidate may not appear in search.
|
|
3. As the company owner, create a hiring need with a salary range, find a candidate, open the explanation and send an invitation.
|
|
4. Accept it as the candidate with C4 and selected contacts. Check that the company can read only those fields, then revoke access or hide the company and verify refusal.
|
|
|
|
The `synthetic_demo` category demonstrates mechanics, not established assessment quality. Built-in consent texts are marked `demo`. Practice requires a separate runner and a suitable bank, so do not present it as part of the ordinary demonstration test. See [ARCHITECTURE.md](ARCHITECTURE.md) for other implementation limits and [TESTING.md](TESTING.md) for acceptance.
|
|
|
|
The presentation slot is 10 minutes; video is allowed instead of a live demonstration. Rehearse with a timer and state limitations. Keep the stand available throughout evaluation where possible; exact dates and whether jury questions count within the ten minutes need confirmation.
|
|
|
|
### Demonstration categories on a stand
|
|
|
|
The seed prepares categories itself. Manual setup requires an open category with a published bank, a demo policy, `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`, and operator attestation:
|
|
|
|
```sh
|
|
make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:maintainer'
|
|
```
|
|
|
|
The command requires `DATABASE_URL`. Attestation binds the category opening, bank, and policy version; reopen and attest after changing them. Synthetic categories remain disabled in environments with real candidates.
|
|
|
|
### Match search policy on a stand
|
|
|
|
The initial policy on an empty stand has no `matching` section. Publish it before demonstrating search:
|
|
|
|
```sh
|
|
make -C backend policy-publish ARGS='matching --actor operator:maintainer'
|
|
```
|
|
|
|
The command requires `DATABASE_URL` and publishes the next demo version. The seed handles this preparation itself. A policy change requires reopening and attesting demo categories; attempts already started keep their previous version.
|
|
|
|
### Assessment review band
|
|
|
|
```sh
|
|
make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operator:maintainer'
|
|
```
|
|
|
|
The command requires `DATABASE_URL` and shows signals for manual review. They do not prove misconduct or automatically lower a score. The `operator:*` label is for auditing; database access remains the operator's access boundary.
|
|
|
|
### Leak trace
|
|
|
|
```sh
|
|
make -C backend assessment-leak-trace ARGS='search --actor operator:maintainer --file leaked.txt'
|
|
```
|
|
|
|
Set `DATABASE_URL` and the same `IDENTITY_KEY_SECRET` used when issuing attempts. Pass text in a file or through `--stdin` to keep it out of shell history. Results and audit records omit the original text; a match supports manual review rather than an automatic decision.
|
|
|
|
## Separate ML Compose project
|
|
|
|
ML serves Giga-Embeddings-instruct-480M and Qwen3-Embedding-0.6B embeddings. Its image downloads pinned weights at build time, verifies SHA-256, and runs offline. Compose uses CPU with a limit of 4 CPUs and 8 GiB. The separate project joins the external core network as `ml`.
|
|
|
|
1. Set the same `ML_SERVICE_TOKEN` for ML and backend in `.env`: at least 32 printable characters without spaces.
|
|
2. Start core, then run `make -C deploy ml-build` and `make -C deploy ml-up`.
|
|
3. Wait for `/readyz` 200. `/healthz` checks the process, not model loading.
|
|
|
|
`ML_EMBEDDER=giga,qwen3` loads both models; `none` keeps the service unready, and `fake` is for fixtures. All routes except health/readiness require the configured bearer token. Without a token, the service permits only loopback clients and refuses to start the container listener on `0.0.0.0`. `ml-logs` and `ml-down` manage this project separately.
|
|
|
|
For development, run `make -C ml install`, `make -C ml model-fetch`, then `make -C ml run` with `ML_EMBEDDER` and model directories in the environment. `model-fetch` downloads about 2.2 GB of weights. `make -C ml test-model` tests real models separately from ordinary tests.
|
|
|
|
### ML service on a GPU host
|
|
|
|
Use the [systemd template](../../deploy/ml-gpu/lincodex-ml.service) and [example settings](../../deploy/ml-gpu/ml.env.example). The service expects code at `~/lincodex-ml/app/ml`, a virtualenv at `~/lincodex-ml/venv`, and settings in `~/.config/lincodex-ml/ml.env` with mode 0600. Use the Python version from `ml/.python-version`; `make -C ml cuda-requirements` prepares pinned dependencies with a CUDA torch build, which must be installed from the matching PyTorch index.
|
|
|
|
Prepare weights from the lock files; select a private address, `ML_DEVICE=cuda`, dtype, and `ML_CUDA_MEMORY_LIMIT_MB` for the host's resources. After installing the unit and configuring lingering, run `systemctl --user daemon-reload`, then `systemctl --user enable --now lincodex-ml.service`. Check `/readyz`, logs, and real model tests on the target device. Memory and latency measurements from another host are not guarantees for yours.
|
|
|
|
Restrict access to the backend address. The service does not terminate TLS; use a protected channel across an untrusted network. CUDA memory exhaustion returns 503 and retries loading; other persistent loading failures exit with `ML_EXIT_ON_LOAD_FAILURE=true` so the supervisor can restart the process.
|
|
|
|
### Semantic matching
|
|
|
|
Search reads precomputed vectors and does not invoke a model within the HTTP request.
|
|
|
|
1. Wait for ML readiness, set `SEMANTIC_MATCHING_ENABLED=true`, the shared token, and `ML_SERVICE_URL` (default `http://ml:8000`), then rerun `make -C deploy up`.
|
|
2. With the stand's `DATABASE_URL`, run `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:maintainer'`. This policy needs both models; `semantic` uses Giga alone.
|
|
3. Queue existing data: `make -C backend semantic-backfill ARGS='all --run initial'`. Repeating the same run label is idempotent; use a new label for another pass.
|
|
|
|
Reopen and attest demo categories after publishing a policy. Missing or incompatible vectors use neutral `Sem=0.5` with `ml_unavailable`. GitHub repository checks are enabled separately through `GITHUB_REPOSITORY_CHECKS_ENABLED`; they are not a requirement for ML startup.
|
|
|
|
## Separate monitoring Compose project
|
|
|
|
```sh
|
|
make -C observability check
|
|
make -C deploy monitoring-up
|
|
make -C deploy monitoring-logs
|
|
make -C deploy monitoring-down
|
|
```
|
|
|
|
By default, the project joins the core network. After starting the demo, run `make -C deploy monitoring-up DEMO_MODE=isolated` to connect it to the `lincodex-demo` network. Grafana is bound to loopback; Prometheus, Loki, Alloy, and exporters remain internal. Dashboards cover Go, PostgreSQL, Redis, SeaweedFS, the host, and product metrics. Kafka has no dedicated scrape yet. The React telemetry SDK is not connected. Alert rules exist; notification delivery needs separate configuration.
|
|
|
|
Prometheus retains metrics for 14 days with a 4 GB cap; Loki retains logs for 7 days. Keep contacts, resumes, raw URLs, and user identifiers out of labels. Alloy accesses the Docker API through a restricted socket proxy; even read-only Docker API access can expose sensitive container configuration. Treat this component as privileged.
|
|
|
|
The PostgreSQL exporter role is created only on first initialization of an empty volume: set `POSTGRES_EXPORTER_USER` and `POSTGRES_EXPORTER_PASSWORD` beforehand. Provision the role separately for an existing database. `ML_METRICS_TARGET` adds a private target, but the current scrape template sends no bearer token; protected ML also requires Prometheus authorization configuration.
|
|
|
|
`make -C observability verify-product-metrics` starts disposable core and monitoring stacks, checks metrics and the absence of fixture personal data in telemetry, then removes them. This integration check is separate from `check`.
|
|
|
|
## Edge proxy, HTTPS and tunnel
|
|
|
|
Public requests follow browser -> edge HTTPS Nginx -> private AmneziaWG tunnel -> frontend Nginx -> Go. Templates and scripts live in [deploy/edge](../../deploy/edge/); core Compose does not terminate TLS.
|
|
|
|
1. Prepare `deploy/edge/edge.env` from the example: domain, dedicated `EDGE_LISTEN_IP`, tunnel addresses, and port. Check DNS, free listeners, and subnet overlap. Preserve existing sites and routes on a shared edge host.
|
|
2. `make -C deploy edge-config` checks templates and runs containerized `nginx -t`; `edge-render` writes Nginx configuration into `deploy/edge/rendered/`. These targets install nothing on the host.
|
|
3. On edge, install the HTTP configuration for ACME, obtain a certificate with certbot, then install the HTTPS configuration and [reload-nginx.sh](../../deploy/edge/certbot/reload-nginx.sh) hook. Run `nginx -t` before reload and test renewal with `certbot renew --dry-run`.
|
|
4. Create tunnel keys through `deploy/edge/scripts/awg-keys.sh` and render each side through `render.sh --params`. Keep key files outside the repository, accessible only to root. Prepare AmneziaWG and the required systemd drop-ins on both hosts.
|
|
5. On app, set `APP_HTTP_BIND` to its tunnel address and `APP_PUBLIC_URL=https://<domain>`. The firewall permits the core port only from edge; frontend trusts forwarded headers only from the edge address. Check both sides; Docker publishing does not replace a firewall.
|
|
|
|
Before opening access, check HTTPS and the certificate chain, HTTP redirects, SPA deep links, sign-in and CSRF, and denial of `/metrics` and administrative paths. Edge replaces forwarded headers instead of trusting client values. Run `make -C deploy check-perimeter` and `make -C deploy perimeter-test`; the latter starts disposable Nginx containers.
|
|
|
|
Keep previous configuration and certificates for rollback and validate them before reload. Do not remove unrelated interfaces, firewall rules, or sites. A successful template check does not prove public domain availability.
|
|
|
|
## Isolated runner and lab host (LXD)
|
|
|
|
LXD needs Linux with KVM, space for the btrfs pool, and operator privileges. Review [acls.sh](../../deploy/labs/acls.sh) and [lxd-preseed.yaml](../../deploy/labs/lxd-preseed.yaml) against the host's network, then apply ACLs before the preseed. The scripts create separate runner and lab-management bridges; guests use static addresses without NAT, DHCP, or DNS. Do not apply the layout over unrelated objects with the same names.
|
|
|
|
The backend never receives the LXD socket. The `lxd` group grants root-equivalent access; only the operator and labd receive it. Test guest isolation from core, the host, LAN, and the internet on the actual host; configuration alone does not prove it.
|
|
|
|
## Code runner
|
|
|
|
The `runner/` service executes Python and Go in nsjail with cgroup v2, seccomp, and limits. The supervisor needs isolation privileges; candidate code runs as an unprivileged user. Run history is in runner memory and is lost on restart.
|
|
|
|
### Local development only
|
|
|
|
`make -C deploy runner-dev-up` creates a token at `runner/.dev/api-token` and starts a separate privileged container with loopback HTTP. Stop it with `runner-dev-down`. This mode is forbidden on the core host and is excluded from release. The backend requires TLS and cannot connect directly to this HTTP mode.
|
|
|
|
### Production: the runner VM
|
|
|
|
Use a dedicated LXD VM with its own kernel and no core directory, Docker socket, application secrets, or default route. The network permits API connections only from the app network and host side, while denying guest-initiated connections. TLS 1.3 and a bearer token are required. nsjail needs delegated cgroup v2 and a work tmpfs with `exec,nosuid,nodev`.
|
|
|
|
### Steps of the VM script
|
|
|
|
On a prepared app host, as a member of the `docker` and `lxd` groups:
|
|
|
|
```sh
|
|
make -C deploy runner-vm-up
|
|
make -C runner a16-bundle
|
|
make -C deploy runner-vm-a16 A16_BUNDLE=/path/to/a16-bundle.tar.gz
|
|
make -C deploy runner-vm-check
|
|
```
|
|
|
|
The A16 bundle can be built on a machine with Go and transferred to app. `runner-vm-up` prepares secrets, rootfs, VM, and service in sequence. Separate targets are `runner-vm-secrets`, `runner-vm-rootfs`, `runner-vm-create`, and `runner-vm-install`. Secrets and reports stay in `RUNNER_VM_STATE_DIR`, defaulting to `~/lincodex-runner`, outside the repository.
|
|
|
|
### Verification on the app host
|
|
|
|
Before enabling practice, pass A16 on the target VM and `runner-vm-check`: TLS, token, harmless programs, limits, cleanup, and network denial. A failure blocks practice activation. Repeat checks after changes to the kernel, runtime, or isolation settings. A passing run on an older release does not replace them.
|
|
|
|
### Code runner client
|
|
|
|
Set backend `CODE_RUNNER_URL` to HTTPS, `CODE_RUNNER_TOKEN`, a distinct `CODE_RUNNER_RUN_KEY`, and exactly one of `CODE_RUNNER_CA_FILE`/`CODE_RUNNER_CA_PEM`. Mount the CA file into the container yourself. Set `CODE_RUNNER_SERVER_NAME` if required; certificate verification stays enabled. `CODE_RUNNER_REQUEST_TIMEOUT` bounds each request.
|
|
|
|
Without a URL, all other `CODE_RUNNER_*` settings must be empty; practice reports unavailable. Invalid configuration prevents startup. `make -C backend test-code-runner-live` tests the client against a prepared TLS runner with `CODE_RUNNER_URL`, `CODE_RUNNER_TOKEN`, and `CODE_RUNNER_CA_FILE` from the environment; it does not replace A16.
|
|
|
|
### Practice queue and debug run limits
|
|
|
|
The backend already connects the practice handler and PostgreSQL queue when `DATABASE_URL` and a runner are configured. The queue allows one running and ten waiting jobs; Redis limits candidate debug requests. `PRACTICE_*` settings live in `backend/config/` but are not passed by ordinary Compose. Infrastructure failure ends without grading, not as a wrong answer; inspect the queue through `assessment_practice_jobs`.
|
|
|
|
## Labs and labd
|
|
|
|
labd runs as a systemd service on the app host and exclusively manages LXD. Use its [unit](../../deploy/labs/lincodex-labd.service) and [settings](../../deploy/labs/labd.env.example): TLS, token, allowed networks, state file, and memory budget. Preserve its state file with the LXD objects; it is needed to recover and delete labs.
|
|
|
|
The built-in template registry is currently empty, backend does not connect the labd adapter, and the WebSocket console returns 501. A usable workflow requires prepared images, templates, and integration. Before enabling it, verify L2 isolation, MAC/port filtering, cloud-init, and node authentication during checks. `make -C labd test-live` creates and deletes a lab on a separate test LXD with `LABD_LIVE_SOCKET` and `LABD_LIVE_SOURCE`; never run it against production.
|
|
|
|
## Release manifest
|
|
|
|
A reproducible release needs a clean working tree and passing checks of those exact images:
|
|
|
|
```sh
|
|
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 release-manifest-verify RELEASE_ID=demo-stage-1
|
|
```
|
|
|
|
The manifest in `deploy/release/<id>/` records source, dependencies, Compose, image IDs/digests, and inputs. Each ID is immutable; a new delivery needs a new ID. These are local artifacts and stay out of Git. `RELEASE_DATA_MANIFEST` adds bank, policy, and seed versions; the absence of an accepted bank remains an explicit limitation rather than proof of product readiness.
|
|
|
|
`release-up` requires local images and matching files; it neither builds nor pulls them. For another project, use matching `APP_PROJECT` and `RELEASE_VERIFY_PROJECT`. Restore the demo with `demo-seed DEMO_MODE=isolated RELEASE_ID=<id>`; stop core with `release-down` using the same ID. `release-clean` removes only image references not retained by manifests.
|
|
|
|
The manifest does not back up data or deploy edge, the GPU host, runner, or labd. Back up data and configuration before upgrades; rolling back an image does not undo migrations. Test recovery of PostgreSQL and SeaweedFS objects separately.
|
|
|
|
## Checks
|
|
|
|
| Command | Coverage |
|
|
| --- | --- |
|
|
| `make -C deploy check` | Compose and tooling checks without starting the stack |
|
|
| `make -C deploy smoke` | Dependency health and network boundaries of a disposable stack |
|
|
| `make -C frontend install`, then `make -C deploy test-e2e` | Browser scenarios on a disposable stack |
|
|
| `make -C deploy test-e2e-registration` | Scenarios with a local mail fixture |
|
|
| `make -C observability check` | Monitoring configuration and alert rules |
|
|
|
|
Test coverage and environment requirements are in [TESTING.md](TESTING.md). A passing health check does not confirm the complete business flow.
|