feat(runner): add the own code runner contract, client and nsjail service

This commit is contained in:
shira committed 2026-10-11 08:23:42 +03:00
1 parent 5e1db37746
commit cdf6bcbb91
109 files changed
+24084 -28

No files matched your search

+26 -2
View File
@@ -26,9 +26,9 @@ The project brief assigns 35% of its score to matching, 25% to assessment and ca
## Contracts and code generation
The contract roots are split by boundary: api/core/ contains browser-to-Go operations, and api/ml/ contains internal Go-to-ML operations. The shared Makefile, package.json, and Redocly configuration stay under api/. Python schema tools live in the repository-level scripts/ directory. Each contract is assembled from small source YAML files.
The contract roots are split by boundary: api/core/ contains browser-to-Go operations, api/ml/ contains internal Go-to-ML operations, and api/runner/ contains internal operations between Go and the code runner. The shared Makefile, package.json, and Redocly configuration stay under api/. Python schema tools live in the repository-level scripts/ directory. Each contract is assembled from small source YAML files.
The public Go handler is generated by ogen from backend/codegen/ogen.yml and mounted in chi. Orval independently generates the TypeScript client, TanStack Query hooks, Zod schemas, and MSW handlers. The ML Go client is configured at backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. datamodel-code-generator produces Pydantic v2 models from the same ML bundle in ml/src/lincodex_ml/api/models.py; the health/readiness handlers use these models. Python generator settings live in ml/codegen/pyproject.toml, while dependencies remain in ml/pyproject.toml. Backend sqlc configuration is backend/codegen/sqlc.yml and its generated SQL adapter is under backend/internal/adapter/secondary/postgres/sqlc/. Frontend configuration is frontend/codegen/orval.config.ts. There are three codegen directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Configuration belongs to the service that uses the generated code.
The public Go handler is generated by ogen from backend/codegen/ogen.yml and mounted in chi. Orval independently generates the TypeScript client, TanStack Query hooks, Zod schemas, and MSW handlers. The ML Go client is configured at backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/, and the code runner Go client is configured at backend/codegen/ogen-code-runner.yml and generated into backend/internal/adapter/secondary/code_runner/api/. datamodel-code-generator produces Pydantic v2 models from the same ML bundle in ml/src/lincodex_ml/api/models.py; the health/readiness handlers use these models. Python generator settings live in ml/codegen/pyproject.toml, while dependencies remain in ml/pyproject.toml. Backend sqlc configuration is backend/codegen/sqlc.yml and its generated SQL adapter is under backend/internal/adapter/secondary/postgres/sqlc/. Frontend configuration is frontend/codegen/orval.config.ts. There are three codegen directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Configuration belongs to the service that uses the generated code.
OpenAPI 3.2.0 is the target version. Verify the subset used here across bundling and lint, ogen, the chi adapter, the API runtime path, Orval, Python Pydantic models, and documentation. A parser version or one fixture does not prove support for every OpenAPI 3.2.0 feature.
@@ -537,6 +537,7 @@ The local release manifest separates core image verification from product data a
```text
api/core/ public browser-to-Go contract and bundle
api/ml/ internal Go-to-ML contract and bundle
api/runner/ internal Go-to-code-runner contract and bundle
backend/cmd/app/main.go calls bootstrap.Run and reports errors
backend/cmd/migrate/ local migration status, up, and down-one
backend/config/ shared runtime configuration
@@ -551,6 +552,7 @@ frontend/src/ app, pages, widgets, features, entities, shared
frontend/codegen/ Orval configuration
ml/src/ FastAPI service and operational checks
ml/codegen/ Python datamodel-code-generator settings
runner/ Go code runner service: nsjail, cgroup v2, judge, and HTTP API
deploy/ Compose, Nginx, and technical smoke checks
observability/ Prometheus, Loki, Alloy, Grafana provisioning
scripts/ shared documentation and schema tooling
@@ -586,6 +588,7 @@ backend/
mail/resend/ mail transport that sends one request to the Resend HTTP API per message
mail/resend/resendfixture/ local stand-in for the Resend API, for tests only; production never imports it
ml/api/ generated client from backend/codegen/ogen-ml.yml
code_runner/api/ generated client from backend/codegen/ogen-code-runner.yml
postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity, consent ledger, organization, membership, and policy repositories, health check
postgres/sqlc/ generated SQL adapter
redis/ cache adapter and Redis check
@@ -720,6 +723,27 @@ A category changes only by a strict grade upgrade (the database trigger and the
`basis` is the same value as the `source` of the category decision. Today it is always `synthetic_demo`: the database accepts only the demonstration source and `calibration_status = uncalibrated`. The candidate card and the organization search therefore show such a category as a demonstration, not as a validated measurement. The basis is required in every category object, so a category without a basis cannot look like a standard confirmation.
### Code runner
Code practice runs in the own `runner/` service; Judge0 is not used (GPL license, owner decision). The service receives the source, the limits, and the test groups through the internal `api/runner/` contract, runs every test in nsjail, and returns the outcome of every group. The backend computes the 0-3 score from the three hidden groups; the runner only reports which groups passed.
The A16 boundary. Untrusted code runs only on a separate runner host. The target production placement is a dedicated LXD VM on the app host (2 vCPU, 3 GB, one concurrent run) attached to a private bridge without internet access; the backend reaches it over TLS with a bearer token. A privileged container on the core host is forbidden, and a Docker network alone is not a boundary. The runner host holds no business secrets: only its TLS key and the API token.
Isolation layers of one run (implemented):
- nsjail in run-once mode: new network (empty, without loopback), PID, mount, IPC, UTS, user, and cgroup namespaces, `no_new_privs`, dropped capabilities, the user uid/gid 99999 inside and outside the user namespace, and no `/proc`.
- File system: the jail root is a read-only tmpfs; only `/usr` and `/lib` (the interpreter) are mounted read-only, the run directory with the source is mounted read-only as `/box`, plus `/dev/null` and `/dev/urandom`, and the working directory `/tmp` is a size-limited tmpfs. The run directory is removed after the run, and its root is emptied at startup.
- cgroup v2: the supervisor creates the cgroup of every run itself (`memory.max` with a small allowance for nsjail, `memory.swap.max=0`, `pids.max`, `cpu.max` for one CPU) and starts nsjail directly inside it with CLONE_INTO_CGROUP. The limits therefore cover the whole process tree, and the OOM, refused fork, and CPU counters are exact.
- rlimits: CPU, file size, open files, core 0, and address space.
- seccomp (kafel): the process is killed on ptrace, mount and namespace calls, keyrings, bpf, perf, userfaultfd, io_uring, kernel modules, and clock and swap administration; clone with namespace flags kills the process, clone3 answers ENOSYS, and sockets other than AF_UNIX answer EAFNOSUPPORT.
- The supervisor checks CPU, wall clock, OOM, and the process limit every 10 ms and, when a limit fires, kills the jailed processes but keeps nsjail so that it reaps its child; if nsjail does not exit within a second, the whole cgroup is killed. After a run the cgroup is removed only once it is empty.
The service bounds concurrent runs (1 by default) and answers 503 `runner_busy` when no slot is free; the backend keeps the queue. The contract and the configuration bound the request body, the source, the inputs, and the output. Logs carry only the method, operation, status, duration, run ID, language, group and test counts, and outcome; the source, test data, program output, and token never reach a log. Runs live only in memory and are forgotten after their TTL; the backend resubmits a run lost in a restart.
Outcomes distinguish `accepted`, `wrong_answer`, `compile_error` (for Python, a syntax check with `compile()` before the tests), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (including the process limit), and `infrastructure_failure`. Test time is the CPU time of every process of the test, including interpreter startup; memory is the cgroup peak of the test, including nsjail and file cache charged to the test.
Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; Go (compile and run); a float tolerance checker and custom checkers; calls from the backend and the run queue; service metrics; the full A16 isolation suite built on `runner/testdata/hostile/`.
## Matching and explanations
Implemented as a deterministic search without ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. There is no new table, migration, or query file: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule.
+39
View File
@@ -735,6 +735,44 @@ Verified on the app host (TASK-592): from a guest on `lxdbr-runner` the internet
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, and Python from `python:alpine`; 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 (planned)
The runner runs only in the `lincodex-runner` VM on the `lxdbr-runner` bridge (see [the isolated runner host](#isolated-runner-and-lab-host-lxd)), never on the core host and never with the dev file. 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. Rolling out the VM, issuing the certificate, storing the token for the backend, and monitoring are not implemented yet.
| 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, tmpfs recommended |
| `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_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 |
## 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.
@@ -752,6 +790,7 @@ Container images use moving `latest` or `alpine` tags where the upstream publish
| 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).
+5 -3
View File
@@ -51,7 +51,7 @@ What exists now:
- Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail.
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and `identity.Credentials` are wired for registration and email confirmation. A generated Go client for the ML contract exists but is not wired into bootstrap.
- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Product notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but notification sending is not implemented. With `resend`, the backend runs a worker for identity service mail: registration and resend queue verification messages bound to their tokens; the worker checks the token and account before sending and uses a quota gate and stable idempotency key. Password reset is not implemented yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries).
- OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA uses the generated API client; MSW handlers provide test data. Implemented forms are listed below, while remaining routes still show placeholders.
- OpenAPI contracts api/core/, api/ml/, and api/runner/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA uses the generated API client; MSW handlers provide test data. Implemented forms are listed below, while remaining routes still show placeholders.
- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`).
- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs two product handlers, the mail delivery consumer and the inbox consumer, and no product flow emits their events yet; see [Event consumers](#event-consumers).
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite.
@@ -100,22 +100,24 @@ Each top-level directory except `.github/` has a short Russian `README.md` and a
| --- | --- |
| api/core/ | Public browser-to-Go OpenAPI contract |
| api/ml/ | Internal Go-to-ML OpenAPI contract |
| api/runner/ | Internal OpenAPI contract between Go and the code runner |
| scripts/ | Shared schema merge, generated drift, and docs-check |
| backend/ | Go HTTP service, adapters, bootstrap, SQL, and consumer codegen |
| backend/config/ | Shared Go configuration outside internal |
| frontend/ | Vite SPA, Orval configuration, generated TypeScript |
| ml/ | Python service, lockfile, and Pydantic model generator |
| runner/ | Go code runner service: nsjail, cgroup v2, judge, ogen server, and isolation tests |
| deploy/ | Compose, Nginx, and smoke script |
| observability/ | Prometheus, Loki, Alloy, provisioning, and dashboard JSON |
| security/ | Scanner configuration, installation, Make targets, and local reports |
| .agents/ | Canonical project instructions and working standards |
| docs/ru/, docs/en/ | User documentation in Russian and English |
Codegen directories belong to the services that use the generated code: backend/codegen/, frontend/codegen/, and ml/codegen/. The Go client for the internal ML API is generated from backend/codegen/ogen-ml.yml and consumed at backend/internal/adapter/secondary/ml/api/. The public Go handler is generated from backend/codegen/ogen.yml and mounted in chi. sqlc configuration is backend/codegen/sqlc.yml, with generated SQL under backend/internal/adapter/secondary/postgres/sqlc/. Orval reads the public bundle from frontend/codegen/orval.config.ts. backend/cmd/app/main.go calls bootstrap.Run() and handles its error; startup, dependency wiring, and lifecycle logic live in backend/internal/bootstrap/app.go.
Codegen directories belong to the services that use the generated code: backend/codegen/, frontend/codegen/, and ml/codegen/. The Go client for the internal ML API is generated from backend/codegen/ogen-ml.yml and consumed at backend/internal/adapter/secondary/ml/api/. The Go client for the code runner is generated from backend/codegen/ogen-code-runner.yml into backend/internal/adapter/secondary/code_runner/api/. The public Go handler is generated from backend/codegen/ogen.yml and mounted in chi. sqlc configuration is backend/codegen/sqlc.yml, with generated SQL under backend/internal/adapter/secondary/postgres/sqlc/. Orval reads the public bundle from frontend/codegen/orval.config.ts. backend/cmd/app/main.go calls bootstrap.Run() and handles its error; startup, dependency wiring, and lifecycle logic live in backend/internal/bootstrap/app.go.
## Contracts and generation
Source YAML stays beside its contract. Run make -C api bundle to merge schemas separately for api/core/ and api/ml/ and then bundle both inputs. The public and internal APIs remain separate contracts.
Source YAML stays beside its contract. Run make -C api bundle to merge schemas separately for api/core/, api/ml/, and api/runner/ and then bundle each input. The public and internal APIs remain separate contracts.
Root make generate prepares both bundles once, then runs Go, TypeScript, and Python consumers. Merged schemas, bundles, and generated clients are tracked derived files; change their sources and regenerate them. After changing a contract, regenerate every consumer and check drift. A service-local Make target can generate one consumer when its inputs are ready and the shared contract owner has agreed.
+14
View File
@@ -581,6 +581,20 @@ What these tests do not show: a real invitation event through Kafka and the rela
The tests do not run the Make targets against a real stack. A manual check on a throwaway project: `make -C deploy demo-seed DEMO_MODE=isolated DEMO_PROJECT=lincodex-demo-check DEMO_HTTP_PORT=18090` twice with identical inventories, a sign-in of the prepared accounts with mail disabled, an express run and the start of the full test, then `demo-reset` refused after a visitor registered. Remove the project afterwards with `docker compose -p lincodex-demo-check down --volumes` and the same variables. The tests do not validate the content of the synthetic bank or any grade, and the browser route of the jury is not covered here. Integration tests need Docker.
## Code runner tests
| Command | What it checks |
| --- | --- |
| make -C runner test | Unit tests with the race detector: checkers, configuration, judge outcomes on a scripted sandbox, idempotency and busy handling of the run manager, the HTTP API (token, 202/200/422/503, 400, 413, 404), and that logs carry no source, input, or token |
| make -C runner lint | golangci-lint for Linux, including the isolation tests |
| make -C runner check-generated | The generated ogen server matches the bundle |
| make -C runner test-sandbox | Isolation tests in a privileged dev container with real nsjail and cgroup v2 |
| make -C deploy check-runner-dev | Dev switches stay out of production files |
`test-sandbox` runs every case of `runner/testdata/hostile/manifest.json` twice: a correct solution is accepted with its time and memory recorded; a syntax error gives `compile_error`; the CPU limit stops an infinite loop, the wall-clock limit a sleep, the cgroup memory limit a memory leak, the output limit endless output, and the process limit a fork bomb (`runtime_error`); network, file system, and privilege probes confirm that there is no network, the root and the source are read-only, runner files are not visible, and the program is not root. After every case and after the series the test checks that the run directory is empty, the run cgroups are gone, and no uid 99999 process is left. It runs without a separate init, so it also confirms that nsjail reaps every stopped process.
What the tests do not prove: isolation in the production VM (they have not run there yet), protection against kernel, nsjail, or cgroup vulnerabilities, the absence of side channels, or behavior under load. The full A16 isolation suite is planned separately and will extend the same fixtures.
## Future software validation
Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter.
+27 -3
View File
@@ -26,15 +26,15 @@ Go владеет авторизацией, подтвержденными ка
## Контракты и генерация
Каталоги контрактов симметричны: api/core/ содержит публичный контракт браузер-Go, api/ml/ - внутренний контракт Go-ML. Общие Makefile, package.json и Redocly config находятся в api/; Python-скрипты сборки лежат в корневом scripts/. Обе спеки состоят из небольших исходных YAML-файлов, которые собираются в bundles.
Каталоги контрактов симметричны: api/core/ содержит публичный контракт браузер-Go, api/ml/ - внутренний контракт Go-ML, api/runner/ - внутренний контракт Go и исполнителя кода. Общие Makefile, package.json и Redocly config находятся в api/; Python-скрипты сборки лежат в корневом scripts/. Все спеки состоят из небольших исходных YAML-файлов, которые собираются в bundles.
Публичный Go handler генерируется ogen из backend/codegen/ogen.yml и монтируется в chi. Orval независимо генерирует TypeScript client, TanStack Query hooks, Zod schemas и MSW handlers. Go-клиент ML API генерируется по backend/codegen/ogen-ml.yml в backend/internal/adapter/secondary/ml/api/. Python-модели Pydantic v2 генерируются datamodel-code-generator из того же ML bundle в ml/src/lincodex_ml/api/models.py; их используют health/readiness handlers. Настройки Python-генератора находятся в ml/codegen/pyproject.toml, зависимости - в ml/pyproject.toml. Backend конфигурация sqlc находится в backend/codegen/sqlc.yml, generated SQL adapter - в backend/internal/adapter/secondary/postgres/sqlc/. Frontend config - в frontend/codegen/orval.config.ts. Всего три каталога codegen: backend/codegen/, frontend/codegen/ и ml/codegen/; конфигурация принадлежит сервису, который использует сгенерированный код.
Публичный Go handler генерируется ogen из backend/codegen/ogen.yml и монтируется в chi. Orval независимо генерирует TypeScript client, TanStack Query hooks, Zod schemas и MSW handlers. Go-клиент ML API генерируется по backend/codegen/ogen-ml.yml в backend/internal/adapter/secondary/ml/api/, Go-клиент исполнителя кода - по backend/codegen/ogen-code-runner.yml в backend/internal/adapter/secondary/code_runner/api/. Python-модели Pydantic v2 генерируются datamodel-code-generator из того же ML bundle в ml/src/lincodex_ml/api/models.py; их используют health/readiness handlers. Настройки Python-генератора находятся в ml/codegen/pyproject.toml, зависимости - в ml/pyproject.toml. Backend конфигурация sqlc находится в backend/codegen/sqlc.yml, generated SQL adapter - в backend/internal/adapter/secondary/postgres/sqlc/. Frontend config - в frontend/codegen/orval.config.ts. Всего три каталога codegen: backend/codegen/, frontend/codegen/ и ml/codegen/; конфигурация принадлежит сервису, который использует сгенерированный код.
Целевая версия OpenAPI - 3.2.0. Проверяется только используемое подмножество: bundling/lint, ogen, chi adapter, runtime путь API, Orval, Python-модели Pydantic и документация. Проверка одной fixture или чтение версии parser не доказывает поддержку всех возможностей OpenAPI 3.2.0.
В публичном API префикс /api/v1 применяется один раз. Служебный /metrics остается отдельным внутренним маршрутом. Health операции именуются с суффиксом z: healthz и readyz. DTO генераторов не заменяют проверку владельца, членства в компании, согласия или допустимости перехода бизнес-состояния.
Генерация идет из исходных контрактов. Core и ML bundles создаются отдельно; затем Go, TypeScript и Python потребители обновляются из своих Make targets. Изменения контракта включают regeneration и проверку generated drift для всех потребителей. Сгенерированные файлы не редактируются вручную.
Генерация идет из исходных контрактов. Core, ML и runner bundles создаются отдельно; затем Go, TypeScript и Python потребители обновляются из своих Make targets. Изменения контракта включают regeneration и проверку generated drift для всех потребителей. Сгенерированные файлы не редактируются вручную.
## Границы сервисов и данных
@@ -537,6 +537,7 @@ Offsets и партиции. Каждый обработчик - один уча
```text
api/core/ публичный контракт браузер-Go и bundle
api/ml/ внутренний контракт Go-ML и bundle
api/runner/ внутренний контракт Go и исполнителя кода и bundle
backend/cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку
backend/cmd/migrate/ локальные status, up и down-one для миграций
backend/config/ общая конфигурация runtime
@@ -551,6 +552,7 @@ frontend/src/ app, pages, widgets, features, entities, shared
frontend/codegen/ конфигурация Orval
ml/src/ FastAPI сервис и operational checks
ml/codegen/ настройки Python datamodel-code-generator
runner/ Go-сервис исполнителя кода: nsjail, cgroup v2, judge и HTTP API
deploy/ Compose, Nginx и технические smoke checks
observability/ Prometheus, Loki, Alloy и Grafana provisioning
scripts/ общие инструменты для документации и схем
@@ -586,6 +588,7 @@ backend/
mail/resend/ почтовый транспорт, который отправляет одно письмо одним запросом к HTTP API Resend
mail/resend/resendfixture/ локальная замена API Resend только для тестов; production ее не импортирует
ml/api/ generated client из backend/codegen/ogen-ml.yml
code_runner/api/ generated client из backend/codegen/ogen-code-runner.yml
postgres/ pool, migrator, transactor, запись outbox и хранилище relay, хранилище обработчиков событий, репозитории identity, журнала согласий, организаций, членств и политики, health check
postgres/sqlc/ generated SQL adapter
redis/ адаптер кеша и проверка Redis
@@ -720,6 +723,27 @@ contact_grant относится к паре кандидат-компания
`basis` - то же значение, что `source` решения о категории. Сейчас оно всегда `synthetic_demo`: база принимает только демонстрационный источник и `calibration_status = uncalibrated`. Поэтому карточки кандидата и подбор организаций показывают такую категорию как демонстрационную, а не как проверенное измерение. Основание обязательно в каждом объекте категории, поэтому категория без основания не может выглядеть стандартным подтверждением.
### Исполнитель кода
Практика с кодом исполняется собственным сервисом `runner/`; Judge0 не используется (лицензия GPL, решение владельца). Сервис принимает исходный код, лимиты и группы тестов по внутреннему контракту `api/runner/`, запускает каждый тест в nsjail и возвращает исход каждой группы. Балл 0-3 по трем скрытым группам считает backend; исполнитель только сообщает, какие группы пройдены.
Граница A16. Недоверенный код запускается только на отдельном хосте исполнителя. Целевое production-размещение - выделенная LXD VM на app-хосте (2 vCPU, 3 GB, один параллельный прогон), подключенная к частному bridge без выхода в интернет; backend обращается к ней по TLS с bearer-токеном. Привилегированный контейнер на core-хосте запрещен, а сеть Docker сама по себе не считается границей. На хосте исполнителя нет бизнес-секретов: только его TLS-ключ и токен API.
Слои изоляции одного прогона (реализовано):
- nsjail в режиме одного запуска: новые пространства имен network (пустое, без loopback), PID, mount, IPC, UTS, user и cgroup, `no_new_privs`, сброс capabilities, пользователь uid/gid 99999 внутри и снаружи user namespace, без `/proc`.
- Файловая система: корень jail - tmpfs, смонтированный только для чтения; внутрь попадают только `/usr` и `/lib` (интерпретатор) только для чтения, каталог прогона с исходником как `/box` только для чтения, `/dev/null` и `/dev/urandom`, а рабочий каталог `/tmp` - tmpfs ограниченного размера. Каталог прогона удаляется после прогона, его корень очищается при старте.
- cgroup v2: супервизор сам создает cgroup каждого прогона (`memory.max` с небольшим запасом на nsjail, `memory.swap.max=0`, `pids.max`, `cpu.max` на один CPU) и запускает nsjail сразу внутри него через CLONE_INTO_CGROUP. Поэтому лимиты покрывают весь процессный tree, а счетчики OOM, отказов fork и CPU точные.
- rlimits: CPU, размер файла, открытые файлы, core 0, адресное пространство.
- seccomp (kafel): завершение процесса при ptrace, mount и namespace-вызовах, keyring, bpf, perf, userfaultfd, io_uring, модулях ядра и администрировании часов и swap; clone с флагами namespace завершает процесс, clone3 отвечает ENOSYS, сокеты кроме AF_UNIX отвечают EAFNOSUPPORT.
- Супервизор отслеживает CPU, стену, OOM и лимит процессов каждые 10 мс и при срабатывании убивает процессы jail, оставляя nsjail, чтобы тот забрал своего потомка; если nsjail не завершился за секунду, убивается вся cgroup. После прогона cgroup удаляется только пустой.
Сервис ограничивает число параллельных прогонов (по умолчанию 1) и отвечает 503 `runner_busy` при занятом слоте; очередь держит backend. Размер тела запроса, исходника, входа и вывода ограничен контрактом и конфигурацией. Логи содержат только метод, операцию, статус, длительность, run ID, язык, число групп и тестов и исход; исходник, тестовые данные, вывод программы и токен в логи не попадают. Прогоны хранятся только в памяти и забываются после TTL; потерянный при рестарте прогон backend отправляет снова.
Исходы различают `accepted`, `wrong_answer`, `compile_error` (для Python - проверка синтаксиса через `compile()` до тестов), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (включая лимит процессов) и `infrastructure_failure`. Время теста - CPU всех процессов теста вместе с запуском интерпретатора; память - пик cgroup теста, включая nsjail и файловый кеш, отнесенный к тесту.
Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; Go (компиляция и запуск); checker с допуском для чисел и собственный checker; вызов исполнителя из backend и очередь прогонов; метрики сервиса; полный набор проверок изоляции A16 на базе `runner/testdata/hostile/`.
## Подбор и объяснение
Реализован как детерминированный поиск без ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.md](../../api/README.md#подбор)). Код: usecase `backend/internal/usecase/matching/` (`search.go` - порядок работы, `filter.go` - фильтры, `score.go` - целочисленный расчет, `explain.go` - объяснение), список карточек `candidateview.Service.ListVisibleCards`, раздел политики `domain.MatchingPolicy` (`policy_matching.go`), связи навыков `domain.RelateEvidenceSkill` (`evidence_relation.go`), обработчик `adapter/primary/http/v1/matches.go` и сборка `bootstrap/matches.go`. Новых таблиц, миграций и файлов запросов нет: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре.
+39
View File
@@ -737,6 +737,44 @@ lxd init --preseed < deploy/labs/lxd-preseed.yaml
Чистка перед раскаткой удалила только кеш сборки Docker (`docker builder prune -af`, около 8 ГБ). `apt-get clean` и `journalctl --vacuum-size=100M` требуют sudo и оставлены оператору. Тома Docker, образы работающего стека, `wg0`, `awg-lincodex` и правила `ufw` не затронуты.
## Исполнитель кода
Образ `runner/Dockerfile` содержит Go-супервизор, nsjail и Python из `python:alpine`; pip и ensurepip удалены. Базовые образы - аргументы `GO_IMAGE` и `RUNTIME_IMAGE`, поэтому сборка выпуска может закрепить их digest. Супервизор работает root внутри своего хоста или VM: ему нужны namespaces, отображение пользователя и запись в делегированную cgroup. Программы кандидата работают как uid 99999 без capabilities.
### Локально (только разработка)
`deploy/docker/docker-compose.runner.dev.yml` - отдельный dev-проект `runner-dev`. Он дает контейнеру `privileged: true`, потому что nsjail внутри VM Docker Desktop нужны namespaces и записываемая cgroup v2, и обслуживает простой HTTP только на 127.0.0.1. Этот файл никогда не используется в выпуске или production; `make -C deploy check-runner-dev` проверяет, что его переключатели не попали в другие Compose-файлы, production-образ и инструменты выпуска.
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` создает локальный случайный токен в `runner/.dev/api-token` (игнорируется Git), если его нет, и запускает сервис на `127.0.0.1:${RUNNER_DEV_HTTP_PORT:-8070}`. Вызов: `Authorization: Bearer $(cat runner/.dev/api-token)` и `PUT /v1/runs/<uuid>` по контракту `api/runner/`.
### Production (запланировано)
Исполнитель работает только в VM `lincodex-runner` на мосту `lxdbr-runner` (см. [изолированный хост раннера](#изолированный-хост-раннера-и-лабораторий-lxd)), никогда на core-хосте и никогда с dev-файлом. Обязательны TLS (`RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE`; без них процесс не стартует) и токен из файла секрета (`RUNNER_API_TOKEN_FILE`). Раскатка VM, выпуск сертификата, хранение токена на стороне backend и мониторинг еще не реализованы.
| Переменная | По умолчанию | Назначение |
| --- | --- | --- |
| `RUNNER_LISTEN_ADDRESS` | `:8443` | Адрес HTTP(S) |
| `RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE` | нет | Сертификат и ключ TLS 1.3; обязательны вне dev |
| `RUNNER_API_TOKEN_FILE` или `RUNNER_API_TOKEN` | нет | Токен не короче 32 символов; предпочтителен файл |
| `RUNNER_DEV_ALLOW_PLAINTEXT_HTTP` | `false` | Только dev Compose: HTTP без TLS |
| `RUNNER_MAX_CONCURRENT_RUNS` | `1` | Параллельные прогоны; сверх них 503 `runner_busy` |
| `RUNNER_MAX_REQUEST_BYTES` | `8388608` | Лимит тела запроса |
| `RUNNER_RESULT_TTL`, `RUNNER_MAX_RETAINED_RUNS` | `15m`, `256` | Хранение результатов в памяти |
| `RUNNER_RETRY_AFTER`, `RUNNER_SHUTDOWN_TIMEOUT` | `2s`, `30s` | Retry-After при занятости и ожидание прогонов при остановке |
| `RUNNER_WORK_DIR` | `/var/lib/lincodex-runner/work` | Каталоги прогонов; очищается при старте, рекомендуется tmpfs |
| `RUNNER_CGROUP_ROOT` | `/sys/fs/cgroup` | Делегированная cgroup v2 сервиса |
| `RUNNER_NSJAIL_PATH`, `RUNNER_PYTHON_PATH` | `/usr/bin/nsjail`, `/usr/local/bin/python3` | Пути в образе |
| `RUNNER_SANDBOX_UID` | `99999` | Пользователь программ, не root |
| `RUNNER_SANDBOX_MAX_PROCESSES` | `16` | Процессы и потоки прогона |
| `RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES` | `4194304` | Запас памяти на nsjail сверх лимита задания |
| `RUNNER_SANDBOX_TMPFS_BYTES`, `RUNNER_SANDBOX_FILE_SIZE_BYTES`, `RUNNER_SANDBOX_OPEN_FILES` | `16777216`, `8388608`, `64` | Размер `/tmp`, размер файла и открытые файлы |
| `RUNNER_LOG_LEVEL` | `info` | Уровень JSON-логов |
## Сервисы и образы
Для контейнерных образов выбраны moving tags `latest` или `alpine`, если upstream публикует такой вариант. При обновлении Compose сверяйте актуальные ссылки на образы. Теги `latest` и `alpine` могут перемещаться; фактические image digests выпуска фиксирует [манифест выпуска](#манифест-выпуска). SBOM пока не формируется. Lockfiles прикладных зависимостей сохраняются отдельно.
@@ -754,6 +792,7 @@ lxd init --preseed < deploy/labs/lxd-preseed.yaml
| 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` в образе исполнителя кода | [Apache-2.0](https://github.com/google/nsjail/blob/master/LICENSE) |
Ссылки на upstream: [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).
+5 -3
View File
@@ -51,7 +51,7 @@ Frontend зависимости выбираются из актуальных s
- Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет.
- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и `identity.Credentials` подключены для регистрации и подтверждения email. Generated Go client для ML контракта есть, но в bootstrap не подключен.
- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы продуктовых уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но отправка уведомлений еще не реализована. При `resend` backend запускает worker служебной почты identity: регистрация и повторная отправка создают письма подтверждения, привязанные к токенам; worker проверяет токен и аккаунт перед отправкой и использует шлюз квот и стабильный ключ идемпотентности. Сброс пароля пока не реализован. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем).
- OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). SPA использует generated API client; MSW handlers служат тестовыми данными. Реализованные формы перечислены ниже, остальные маршруты пока показывают заготовки.
- OpenAPI контракты api/core/, api/ml/ и api/runner/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). SPA использует generated API client; MSW handlers служат тестовыми данными. Реализованные формы перечислены ниже, остальные маршруты пока показывают заготовки.
- Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`).
- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает два продуктовых обработчика - доставки писем и inbox, а продуктовые сценарии пока не создают их события; см. [Обработчики событий](#обработчики-событий).
- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md).
@@ -100,22 +100,24 @@ Cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `Same
| --- | --- |
| api/core/ | Публичный OpenAPI контракт браузер-Go |
| api/ml/ | Внутренний OpenAPI контракт Go-ML |
| api/runner/ | Внутренний OpenAPI контракт Go и исполнителя кода |
| scripts/ | Общее объединение схем, generated drift и docs-check |
| backend/ | Go HTTP service, adapters, bootstrap, SQL и codegen потребителя |
| backend/config/ | Общая конфигурация Go вне internal |
| frontend/ | Vite SPA, Orval config и generated TypeScript |
| ml/ | Python service, lockfile и генератор Pydantic-моделей |
| runner/ | Go-сервис исполнителя кода: nsjail, cgroup v2, judge, ogen-сервер и тесты изоляции |
| deploy/ | Compose, Nginx и smoke |
| observability/ | Prometheus, Loki, Alloy и provisioning/dashboard JSON |
| security/ | Конфигурация сканеров, установка, Make targets и локальные отчеты |
| .agents/ | Канонические проектные инструкции и рабочие стандарты |
| docs/ru/, docs/en/ | Пользовательские документы на русском и английском |
Папки codegen принадлежат сервисам, которые используют сгенерированный код: backend/codegen/, frontend/codegen/ и ml/codegen/. Go client внутреннего ML API создается из backend/codegen/ogen-ml.yml и потребляется в backend/internal/adapter/secondary/ml/api/. Публичный generated Go handler создается из backend/codegen/ogen.yml и монтируется в chi. sqlc config находится в backend/codegen/sqlc.yml, generated SQL - в backend/internal/adapter/secondary/postgres/sqlc/. Orval читает публичный bundle через frontend/codegen/orval.config.ts. В backend/cmd/app/main.go остаются вызов bootstrap.Run() и обработка ошибки; запуск, сборка зависимостей и lifecycle находятся в backend/internal/bootstrap/app.go.
Папки codegen принадлежат сервисам, которые используют сгенерированный код: backend/codegen/, frontend/codegen/ и ml/codegen/. Go client внутреннего ML API создается из backend/codegen/ogen-ml.yml и потребляется в backend/internal/adapter/secondary/ml/api/. Go client исполнителя кода создается из backend/codegen/ogen-code-runner.yml в backend/internal/adapter/secondary/code_runner/api/. Публичный generated Go handler создается из backend/codegen/ogen.yml и монтируется в chi. sqlc config находится в backend/codegen/sqlc.yml, generated SQL - в backend/internal/adapter/secondary/postgres/sqlc/. Orval читает публичный bundle через frontend/codegen/orval.config.ts. В backend/cmd/app/main.go остаются вызов bootstrap.Run() и обработка ошибки; запуск, сборка зависимостей и lifecycle находятся в backend/internal/bootstrap/app.go.
## Контракты и генерация
Исходные YAML находятся рядом с соответствующим контрактом. Для общей сборки используйте make -C api bundle; он собирает схемы для api/core/ и api/ml/, затем bundles для обоих входов. Публичный и внутренний API не объединяются в одну спецификацию.
Исходные YAML находятся рядом с соответствующим контрактом. Для общей сборки используйте make -C api bundle; он собирает схемы для api/core/, api/ml/ и api/runner/, затем bundles для каждого входа. Публичный и внутренние API не объединяются в одну спецификацию.
Корневой make generate подготавливает API bundles один раз, затем запускает потребителей Go, TypeScript и Python. Merged schemas, bundles и generated clients являются отслеживаемыми derived files; меняйте исходники и пересоздавайте их генератором. После контракта перегенерируйте всех потребителей и запустите drift check. Отдельный Make target можно использовать для генерации одной части, если ее вход готов и shared contract owner согласовал его.
+14
View File
@@ -581,6 +581,20 @@ Vitest работает в Node без DOM, поэтому ограничени
Тесты не запускают Make-цели против настоящего стека. Ручная проверка на одноразовом проекте: дважды `make -C deploy demo-seed DEMO_MODE=isolated DEMO_PROJECT=lincodex-demo-check DEMO_HTTP_PORT=18090` с одинаковыми перечнями, вход подготовленными аккаунтами при выключенной почте, экспресс-прохождение и начало полного теста, затем отказ `demo-reset` после регистрации посетителя. После проверки удалите проект командой `docker compose -p lincodex-demo-check down --volumes` с теми же переменными. Тесты не проверяют содержание синтетического банка или какой-либо грейд, а браузерный маршрут жюри здесь не покрыт. Интеграционным тестам нужен Docker.
## Тесты исполнителя кода
| Команда | Что проверяет |
| --- | --- |
| make -C runner test | Unit-тесты с race detector: checker, конфигурация, исходы judge на сценарном sandbox, идемпотентность и занятость менеджера прогонов, HTTP API (токен, 202/200/422/503, 400, 413, 404) и отсутствие исходника, входа и токена в логах |
| make -C runner lint | golangci-lint для Linux, включая тесты изоляции |
| make -C runner check-generated | Сгенерированный ogen-сервер совпадает с bundle |
| make -C runner test-sandbox | Тесты изоляции в привилегированном dev-контейнере с настоящими nsjail и cgroup v2 |
| make -C deploy check-runner-dev | Dev-переключатели не попадают в production-файлы |
`test-sandbox` прогоняет дважды все случаи `runner/testdata/hostile/manifest.json`: верное решение принимается с записанными временем и памятью; синтаксическая ошибка дает `compile_error`; бесконечный цикл останавливает лимит CPU, сон - лимит стены, утечка памяти - лимит памяти cgroup, бесконечный вывод - лимит вывода, fork bomb - лимит процессов (`runtime_error`); пробы сети, файловой системы и привилегий подтверждают, что сети нет, корень и исходник только для чтения, файлы runner не видны, а программа не root. После каждого случая и после серии проверяется, что каталог прогонов пуст, cgroup прогонов удалены и не осталось процессов uid 99999. Тест запускается без отдельного init, поэтому подтверждает, что nsjail забирает каждый остановленный процесс.
Что тесты не доказывают: изоляцию в production VM (там они еще не запускались), защиту от уязвимостей ядра, nsjail или cgroup, отсутствие побочных каналов и устойчивость под нагрузкой. Полный набор проверок A16 запланирован отдельно и расширит те же fixtures.
## Будущая программная валидация
Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером.