feat(deploy): pin the demo seed in release manifests and restore the demo stand from them

This commit is contained in:
shira committed 2026-10-09 14:59:06 +03:00
1 parent e1df4ff77c
commit b768f7e53f
14 files changed
+789 -147

No files matched your search

+1 -1
View File
@@ -502,7 +502,7 @@ Test fixtures use their own values. Since `product` is the only family, the inte
## Release artifacts and restoration
The local release manifest separates core image verification from product data availability. It records immutable release IDs, source and Compose file hashes, exact built image IDs, registry digests for pulled images, and bounded hashes for versioned data artifacts. Restoration checks these references and hashes before Compose starts and never resolves a moving tag again. The bundled demo policy source is version 1, but that does not establish which policy row is active in PostgreSQL. The assessment bank and demo seed remain unavailable until accepted snapshots exist, so `product_data_status` is partial. Named Compose volumes persist across a release restart, but the manifest is not a database backup or data snapshot. See [DEPLOY.md](DEPLOY.md#release-manifest) for the commands and manifest schema.
The local release manifest separates core image verification from product data availability. It records immutable release IDs, source and Compose file hashes, exact built image IDs, registry digests for pulled images, and bounded hashes for versioned data artifacts. Restoration checks these references and hashes before Compose starts and never resolves a moving tag again. The bundled demo policy source is version 1, but that does not establish which policy row is active in PostgreSQL. The demo seed is versioned by the hashes of its bundled source, which also holds the synthetic demo bank, and its image is pinned so the isolated demo stand can be restored from the same delivery. The assessment bank remains unavailable until an accepted snapshot exists, so `product_data_status` is partial. Named Compose volumes persist across a release restart, but the manifest is not a database backup or data snapshot. See [DEPLOY.md](DEPLOY.md#release-manifest) for the commands and manifest schema.
## Repository map and package purpose
+16 -12
View File
@@ -369,8 +369,9 @@ 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. 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.
- 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.
- `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.
@@ -387,7 +388,7 @@ What the seed creates (all names carry a synthetic marker; addresses are on `@de
- 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 and release images do not contain it.
- 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
@@ -626,15 +627,18 @@ A release manifest records the source, toolchains, lockfile hashes, Compose file
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`, and `ml` from their Dockerfiles and lockfiles through Compose and tags them `lincodex.invalid/<service>:<tag>`. 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-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. The assessment bank has no accepted release snapshot and the demo seed is not yet versioned, so both remain unavailable and `product_data_status` is `partial`. This is not a full MVP readiness result.
- 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.
- `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.
@@ -647,18 +651,18 @@ The manifest is JSON with sorted keys and schema `lincodex.release-manifest/v2`:
| --- | --- |
| `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 |
| `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; 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 |
| `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 Compose files; bank, policy, and seed versions with bounded artifact paths, hashes, sizes, or an explicit unavailable reason |
| `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, 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` |
| `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. ML is built but no check starts it and it has no model; monitoring images are recorded only when present locally.
- `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:
@@ -667,7 +671,7 @@ The release is `verified` only when all of the following hold; otherwise `releas
- 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 reports the go.mod Go version;
- 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.
@@ -676,7 +680,7 @@ Generating the manifest again for the same ID, source, images, evidence, and dat
### Go pin
go.mod declares `go 1.26.8` without a separate `toolchain` line, the default `GO_IMAGE` is `golang:1.26.8-alpine`, and the build stage sets `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 binary; to read it, the generator creates a container from the image without starting it, copies the binary out, and removes the container.
go.mod declares `go 1.26.8` without a separate `toolchain` line, the default `GO_IMAGE` of `backend/Dockerfile` and `backend/Dockerfile.demo-seed` is `golang:1.26.8-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
+5 -3
View File
@@ -85,7 +85,7 @@ The same command also seeds a second synthetic candidate for `frontend/e2e/priva
## Release manifest tests
`make -C deploy check-release` runs `deploy/scripts/test_release_manifest.py` with the Python standard library and without Docker. It fails when go.mod, the `GO_IMAGE` default, and `GOTOOLCHAIN=local` in backend/Dockerfile stop pinning Go 1.26.8, or when a service Dockerfile uses a base image that is not a pinnable `*_IMAGE` build argument, including an external image in `COPY --from` or `RUN --mount=from`. On fake image, Compose, and container data it checks that:
`make -C deploy check-release` runs `deploy/scripts/test_release_manifest.py` with the Python standard library and without Docker. It fails when go.mod, the `GO_IMAGE` default, and `GOTOOLCHAIN=local` in backend/Dockerfile or backend/Dockerfile.demo-seed stop pinning Go 1.26.8, or when a service Dockerfile uses a base image that is not a pinnable `*_IMAGE` build argument, including an external image in `COPY --from` or `RUN --mount=from`. On fake image, Compose, and container data it checks that:
- the manifest copies no environment values, labels, or local paths, and two generations differ only in `generated_at`;
- evidence counts only for the same tag, commit, and working tree fingerprint, and malformed evidence or build records are not used;
@@ -93,7 +93,9 @@ The same command also seeds a second synthetic candidate for `frontend/e2e/priva
- `release-build` refuses to write the build record when the commit or the working tree changes during the build;
- the working tree fingerprint of a temporary Git repository ignores diff and line ending settings, covers untracked files, skips ignored ones, and leaves the real index unchanged;
- the secret scan finds key blocks, tokens, credentials in URLs, local paths, user and host names, and values of secret-like variables, also as substrings and in base64, without echoing them;
- the running-container comparison reports a different digest, a missing service, and an unknown service.
- the running-container comparison reports a different digest, a missing service, and an unknown service;
- the demo seed image is built with pinned base images under its profile, recorded but never verified, and retained by its image ID; its absence blocks only the demo stand restore, a Go drift in its binary keeps the release unverified, and the demo override pins the core services and the seed to exact image IDs and digests and refuses a missing image, a changed demo overlay, or a manifest without a demo restore entry;
- the `seed` entry hashes the non-test demo seed sources, and its version changes with them but not with a test file.
The test does not build images or start containers. The end-to-end path is `release-build`, `release-smoke` and `release-e2e`, `release-manifest`, `release-up`, `release-manifest-verify`, and `release-manifest-check`; see [DEPLOY.md](DEPLOY.md#release-manifest).
@@ -493,7 +495,7 @@ What these tests do not show: a real invitation (none produces an event yet), th
- A perfect express run of the self-service candidate through the attempt operations draws three items from the training category, ends as `demonstration`, and adds no category and no evidence; the same candidate can then start the full test.
- After an ordinary account registers on the seeded database, the reset check refuses and counts it, a repeated seed still creates nothing, and the account is unchanged.
`make -C deploy check-demo` (part of `make -C deploy check`) runs `deploy/scripts/demo.sh` against a recording stub of the docker CLI: every action refuses without `DEMO_MODE=isolated`, with a project name that equals `APP_PROJECT` or lacks `demo`, with an invalid actor, or without the env file, before any Docker command; a project volume without the demo label is refused before any Compose command; a refused reset check stops the reset before `down`; a reset addresses only the demo project and seeds again; `down` keeps the volumes. With the docker CLI it also renders the overlay: only the frontend is published, on loopback; the seed container has only the default network, a read-only root, and the explicit profile; every volume carries the demo label; the demo backend enables synthetic categories; and the backend images do not contain the command.
`make -C deploy check-demo` (part of `make -C deploy check`) runs `deploy/scripts/demo.sh` against a recording stub of the docker CLI: every action refuses without `DEMO_MODE=isolated`, with a project name that equals `APP_PROJECT` or lacks `demo`, with an invalid actor, or without the env file, before any Docker command; a project volume without the demo label is refused before any Compose command; a refused reset check stops the reset before `down`; a reset addresses only the demo project and seeds again; `down` keeps the volumes; a release manifest that cannot be restored stops `seed` and `reset` before any Compose command, and `down` ignores it. With the docker CLI it also renders the overlay: only the frontend is published, on loopback; the seed container has only the default network, a read-only root, and the explicit profile; every volume carries the demo label; the demo backend enables synthetic categories; the release overlay names the seed image `lincodex.invalid/demo-seed:<tag>` with `pull_policy: never`; and the backend images do not contain the command.
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.
+1 -1
View File
@@ -502,7 +502,7 @@ Offsets и партиции. Каждый обработчик - один уча
## Артефакты выпуска и восстановление
Локальный манифест разделяет проверку core-образов и наличие продуктовых данных. Он записывает неизменяемый ID выпуска, хеши исходников и Compose-файлов, точные image ID собранных образов, registry digest скачанных образов и ограниченные хеши версионированных артефактов данных. До старта Compose восстановление сверяет эти ссылки и хеши и не разрешает плавающие теги заново. Исходник демонстрационной политики в составе проекта имеет версию 1, но это не показывает, какая строка политики активна в PostgreSQL. Банк оценивания и демонстрационный seed пока недоступны до появления принятых снимков, поэтому `product_data_status` равен `partial`. Именованные Compose volumes сохраняются при перезапуске выпуска, но манифест не является резервной копией базы или снимком данных. Команды и схема описаны в [DEPLOY.md](DEPLOY.md#манифест-выпуска).
Локальный манифест разделяет проверку core-образов и наличие продуктовых данных. Он записывает неизменяемый ID выпуска, хеши исходников и Compose-файлов, точные image ID собранных образов, registry digest скачанных образов и ограниченные хеши версионированных артефактов данных. До старта Compose восстановление сверяет эти ссылки и хеши и не разрешает плавающие теги заново. Исходник демонстрационной политики в составе проекта имеет версию 1, но это не показывает, какая строка политики активна в PostgreSQL. Демонстрационный seed версионируется по хешам своего исходника в составе проекта, где лежит и синтетический демонстрационный банк, а его образ закреплен, поэтому изолированный демонстрационный стенд восстанавливается из той же поставки. Банк оценивания недоступен до появления принятого снимка, поэтому `product_data_status` равен `partial`. Именованные Compose volumes сохраняются при перезапуске выпуска, но манифест не является резервной копией базы или снимком данных. Команды и схема описаны в [DEPLOY.md](DEPLOY.md#манифест-выпуска).
## Структура репозитория и назначение пакетов
+17 -13
View File
@@ -371,8 +371,9 @@ make -C deploy demo-reset DEMO_MODE=isolated
make -C deploy demo-down DEMO_MODE=isolated
```
- Каждая цель требует `DEMO_MODE=isolated` и без него отказывает до любой команды Docker. Она работает только с проектом `DEMO_PROJECT` (по умолчанию `lincodex-demo`), имя которого должно содержать `demo` и отличаться от `APP_PROJECT`; к обычному проекту и его томам цели не обращаются. Проект собирается из `docker-compose.yml` и `docker-compose.demo.yml` по текущим исходникам. Overlay включает `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` в демонстрационном backend, поэтому полный тест на нем присваивает неоткалиброванную синтетическую категорию, как и подготовленные попытки (см. [Демонстрационные категории на стенде](#демонстрационные-категории-на-стенде)). Секреты берутся из корневого `.env` (`ENV_FILE`), а имя проекта, сети, `APP_HTTP_PORT` (`DEMO_HTTP_PORT`, по умолчанию 8090), `APP_PUBLIC_URL` (`DEMO_PUBLIC_URL`, по умолчанию `http://localhost:8090`) и закрепленная подсеть (`DEMO_SUBNET` 172.29.84.0/24, `DEMO_FRONTEND_IP`) переопределяются, поэтому стенд может работать рядом с обычным. Адрес привязки остается `APP_HTTP_BIND`. За edge укажите в `DEMO_PUBLIC_URL` публичный origin. Почтовый транспорт берется из `.env`; подготовленным аккаунтам почта не нужна.
- Каждая цель требует `DEMO_MODE=isolated` и без него отказывает до любой команды Docker. Она работает только с проектом `DEMO_PROJECT` (по умолчанию `lincodex-demo`), имя которого должно содержать `demo` и отличаться от `APP_PROJECT`; к обычному проекту и его томам цели не обращаются. Проект собирается из `docker-compose.yml` и `docker-compose.demo.yml` по текущим исходникам, если не выбран манифест выпуска (см. ниже). Overlay включает `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` в демонстрационном backend, поэтому полный тест на нем присваивает неоткалиброванную синтетическую категорию, как и подготовленные попытки (см. [Демонстрационные категории на стенде](#демонстрационные-категории-на-стенде)). Секреты берутся из корневого `.env` (`ENV_FILE`), а имя проекта, сети, `APP_HTTP_PORT` (`DEMO_HTTP_PORT`, по умолчанию 8090), `APP_PUBLIC_URL` (`DEMO_PUBLIC_URL`, по умолчанию `http://localhost:8090`) и закрепленная подсеть (`DEMO_SUBNET` 172.29.84.0/24, `DEMO_FRONTEND_IP`) переопределяются, поэтому стенд может работать рядом с обычным. Адрес привязки остается `APP_HTTP_BIND`. За edge укажите в `DEMO_PUBLIC_URL` публичный origin. Почтовый транспорт берется из `.env`; подготовленным аккаунтам почта не нужна.
- `demo-seed` при необходимости запускает проект, ждет готовности backend (к этому моменту миграции и стартовая политика уже применены), выполняет команду `demo-seed seed` в отдельном контейнере и печатает перечень созданных записей. Повторный запуск ничего не создает и печатает тот же перечень. `demo-down` останавливает проект и сохраняет тома.
- `RELEASE_MANIFEST=<path>` или `RELEASE_ID=<id>` у `demo-seed` или `demo-reset` восстанавливает стенд из этого неизменяемого [манифеста выпуска](#манифест-выпуска) вместо текущих исходников; точную команду дает `restore.demo.command` в манифесте. Сначала `release_manifest.py demo-override` проверяет структуру манифеста и статус восстановления core и демонстрационного стенда, хеши core и демонстрационных Compose-файлов и артефактов данных, а также точные локальные образы, затем пишет закрытый временный Compose override, который закрепляет каждый сервис и команду `demo-seed` за записанными image ID и digest. Compose запускается с `--no-build --pull never`, seed выполняется без `--build`, а после проверки готовности запущенные контейнеры сверяются с манифестом. Манифест, который нельзя восстановить, останавливает цель до любой команды Compose. Для `demo-down` манифест не нужен.
- `demo-reset` сначала выполняет `demo-seed check-reset` против демонстрационной базы. Цель отказывает и ничего не удаляет, если в базе есть хотя бы один аккаунт вне зарезервированного домена `@demo.lincodex.test`, например собственная регистрация посетителя: такой аккаунт - обычные данные. Иначе она удаляет демонстрационный проект вместе с томами (`down --volumes` только для `DEMO_PROJECT`), запускает его снова и заполняет. Overlay при создании помечает тома PostgreSQL, SeaweedFS и Kafka меткой `org.lincodex.demo-mode=isolated`; каждая цель отказывает при томе проекта без этой метки, поэтому том обычного стенда никогда не будет использован или удален. Стенд, сброс которого отклонен, очищается только сознательным ручным решением оператора.
- Пароль всех синтетических аккаунтов - `DEMO_ACCOUNT_PASSWORD` из `deploy/demo/demo.env`, а без этого файла - из закоммиченного `deploy/demo/demo.env.example`. Значение из примера - опубликованные демонстрационные учетные данные, а не секрет; для стенда, доступного извне, скопируйте пример в `demo.env` (Git его игнорирует) и передайте новый пароль жюри отдельно. Пароль применяется при создании аккаунта; меняется он через сброс. Команды печатают логины и никогда не печатают пароль.
@@ -389,7 +390,7 @@ make -C deploy demo-down DEMO_MODE=isolated
- Политика и банк: поверх неизмененной стартовой версии 1 seed публикует демонстрационную политику `DemoProductPolicyV4` (явные настройки `demo_basic`, отдельный раздел учебного экспресс-режима, полоса ручной проверки и раздел подбора); стенд с любой другой последней версией политики отклоняется. Seed импортирует и публикует 25 синтетических семейств категории `demo-backend-junior` (автор `ai:demo-seed-synthetic-bank`, метка проверяющего `operator:demo-seed-bank-reviewer`; предметной проверки семейства не проходили), открывает категорию для Backend Junior с Go и аттестует ее как синтетический демонстрационный источник. У экспресс-режима свои три семейства в категории `demo-express` и своя учебная привязка; экспресс-прохождение никогда не создает категорию, перцентиль или доказательство.
- Подготовленные попытки проходят через обычные операции попытки: создание, ответ на каждое закрепленное задание (все, кроме последнего, верно) и завершение, поэтому результат, категория, история и проекция доказательств получаются тем же кодом и теми же триггерами, что и у попытки кандидата. Это не три демонстрационных вопроса. Они помечены в профиле каждого подготовленного кандидата («Полная попытка теста подготовлена командой demo-seed»), в выводе seed (идентификаторы попыток) и как неоткалиброванные категории `synthetic_demo`. Отдельного признака происхождения у результата в базе пока нет. Ответы даются за секунды, поэтому полоса ручной проверки этих попыток может показать сигналы скорости.
- Подготовленных карточек шесть одинаковых, потому что карточка показывается только в когорте не меньше пяти; шестая сохраняет непустой поиск, если один подготовленный кандидат скроет организацию или снимет публикацию. Поиск владельца «Альфы» возвращает шесть записей; поиск рекрутера в «Бете» отвечает 403. Потребность seed не создает: работодатель создает ее во время демонстрации.
- Seed отклоняет стенд, где есть обычные аккаунты, но нет ни одного его собственного, никогда не меняет записи, которые не создавал, и при повторе не трогает свои записи (например, профиль, измененный посетителем); для восстановления используйте сброс. Seed отклоняет адрес зарезервированного домена, принадлежащий неподтвержденному аккаунту или аккаунту другой роли. Команде `demo-seed` нужны `DATABASE_URL` и `DEMO_MODE=isolated`, а для `seed` еще `DEMO_ACCOUNT_PASSWORD`; dotenv-файл она не читает и проверяет все значения до подключения. Исполнитель `operator:<handle>` (`DEMO_ACTOR`, по умолчанию `operator:demo-seed`) записывается как автор версии политики, публикатор семейств, открывший категорию и аттестующий; это метка аудита, а не аутентификация. `make -C backend demo-seed ARGS='inventory'` запускает ту же команду с хоста, у которого есть доступ к базе; `make -C backend demo-seed-build` собирает `backend/bin/demo-seed`. Команду собирает `backend/Dockerfile.demo-seed`; backend- и release-образы ее не содержат.
- Seed отклоняет стенд, где есть обычные аккаунты, но нет ни одного его собственного, никогда не меняет записи, которые не создавал, и при повторе не трогает свои записи (например, профиль, измененный посетителем); для восстановления используйте сброс. Seed отклоняет адрес зарезервированного домена, принадлежащий неподтвержденному аккаунту или аккаунту другой роли. Команде `demo-seed` нужны `DATABASE_URL` и `DEMO_MODE=isolated`, а для `seed` еще `DEMO_ACCOUNT_PASSWORD`; dotenv-файл она не читает и проверяет все значения до подключения. Исполнитель `operator:<handle>` (`DEMO_ACTOR`, по умолчанию `operator:demo-seed`) записывается как автор версии политики, публикатор семейств, открывший категорию и аттестующий; это метка аудита, а не аутентификация. `make -C backend demo-seed ARGS='inventory'` запускает ту же команду с хоста, у которого есть доступ к базе; `make -C backend demo-seed-build` собирает `backend/bin/demo-seed`. Команду собирает `backend/Dockerfile.demo-seed`; backend-образ ее не содержит, а `release-build` собирает ее отдельным образом выпуска `lincodex.invalid/demo-seed:<tag>`.
## Отдельный ML Compose
@@ -628,15 +629,18 @@ Backend строится с Go 1.26.8; образ runtime выбран в backen
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` собирает `backend`, `frontend` и `ml` через Compose из их Dockerfile и lockfiles и помечает образы `lincodex.invalid/<service>:<tag>`. Домен `.invalid` никогда не разрешается, а release-overlay задает `pull_policy: never`, поэтому отсутствующий образ выпуска не скачивается из registry. Каждый Dockerfile принимает базовые образы как build-аргументы `*_IMAGE`, по умолчанию равные согласованным тегам; цель разрешает каждый базовый образ в его repository digest из локального хранилища образов и собирает с `<tag>@<digest>`. Образ в `COPY --from` или `RUN --mount=from`, который не является предыдущим этапом, отклоняется, потому что его нельзя закрепить. Базовые образы и образы core-сервисов скачиваются, только если их нет локально; `RELEASE_PULL=always` сначала обновляет все теги. После сборки цель снова читает состояние исходников и пишет `build.json` (build-аргументы, digest базовых образов, image ID), только если коммит и рабочее дерево за время сборки не изменились.
- `release-build` собирает `backend`, `frontend`, команду `demo-seed` и `ml` через Compose из их Dockerfile и lockfiles и помечает образы `lincodex.invalid/<service>:<tag>`. Образ demo seed рендерится из core-файлов, `docker-compose.demo.yml` и его overlay `docker-compose.demo.release.yml` с профилем `demo-seed`. Домен `.invalid` никогда не разрешается, а release-overlay задает `pull_policy: never`, поэтому отсутствующий образ выпуска не скачивается из registry. Каждый Dockerfile принимает базовые образы как build-аргументы `*_IMAGE`, по умолчанию равные согласованным тегам; цель разрешает каждый базовый образ в его repository digest из локального хранилища образов и собирает с `<tag>@<digest>`. Образ в `COPY --from` или `RUN --mount=from`, который не является предыдущим этапом, отклоняется, потому что его нельзя закрепить. Базовые образы и образы core-сервисов скачиваются, только если их нет локально; `RELEASE_PULL=always` сначала обновляет все теги. После сборки цель снова читает состояние исходников и пишет `build.json` (build-аргументы, digest базовых образов, image ID), только если коммит и рабочее дерево за время сборки не изменились.
- `release-smoke` и `release-e2e` запускают `deploy/scripts/smoke.sh` и `deploy/scripts/e2e.sh` с `LINCODEX_RELEASE_TAG`, который задают только эти цели: стек поднимается из образов выпуска с `--no-build --pull never`, и только после прохождения всех проверок скрипт пишет `evidence-smoke.json` или `evidence-e2e.json` с тегом выпуска, коммитом, отпечатком рабочего дерева и image ID запущенных контейнеров. Неуспешный прогон ничего не пишет. Evidence, записанный после успешных проверок, остается, даже если затем не удалась очистка стека; скрипт при этом все равно завершается ошибкой.
- `release-manifest` читает локальные образы, запись сборки, evidence и необязательное описание данных; ничего не скачивает. Он публикует только проверенный кандидат со статусом `verified`. Грязное дерево, несоответствие записи сборки исходникам или отсутствие либо отказ обязательных проверок завершают команду до создания `manifest.json` и ссылок удержания собранных образов; ошибка перечисляет причины. Исправьте исходники или evidence и повторите обязательные проверки. `RELEASE_DATA_MANIFEST=<path>` выбирает JSON внутри репозитория со схемой `lincodex.release-data/v1`. Он описывает `bank`, `policy` и `seed` как доступные с версией и путями к артефактам либо недоступные с причиной. Пути нормализованы, относительны к репозиторию, не проходят через symlink и env-файлы. Манифест записывает SHA-256 и размер каждого файла, а восстановление проверяет их; для данных заданы пределы количества и размера.
- Без описания данных манифест записывает версию `1` встроенного исходника демонстрационной политики и хеш `backend/internal/domain/policy_demo.go`. Это только определение из исходников; оно не сообщает версию строки политики в PostgreSQL, потому что старт не заменяет существующую строку. У банка оценивания нет принятого снимка, а демонстрационный seed пока не версионирован, поэтому оба недоступны и `product_data_status` равен `partial`. Это не означает готовность всего MVP.
- Без описания данных манифест записывает версию `1` встроенного исходника демонстрационной политики и хеш `backend/internal/domain/policy_demo.go`. Это только определение из исходников; оно не сообщает версию строки политики в PostgreSQL, потому что старт не заменяет существующую строку. Версия `1` - стартовая; [демонстрационный seed](#изолированный-демонстрационный-стенд) публикует поверх нее `DemoProductPolicyV4`, и этот выбор входит в исходник seed. Запись `seed` - исходник демонстрационного seed в составе проекта: Go-файлы `backend/internal/usecase/demoseed` без тестов (аккаунты, организации, синтетические семейства банка и подготовленные попытки) с их хешами и версией `demo-seed.<12 hex-цифр>`, вычисленной из этих путей и хешей, поэтому любое изменение набора данных дает новую версию. Образ demo seed компилирует те же файлы. У банка оценивания нет принятого снимка (синтетический демонстрационный банк версионируется в составе seed), поэтому `bank` недоступен и `product_data_status` равен `partial`. Это не означает готовность всего MVP.
- Публикация выполняется один раз в `deploy/release/<release-id>/manifest.json`. ID - проверяемый slug длиной от 1 до 64 символов. Повтор с тем же содержимым сохраняет исходные байты и mtime. Изменение данных или этапа под тем же ID завершается ошибкой; используйте новый ID. Публикация сериализована для каждого ID и атомарно создает файл без замены существующего. Записи сборки и evidence остаются в `deploy/release/<source-tag>/`.
- `release-manifest-check` проверяет расположение и структуру манифеста, а также ищет секреты и данные машины. `RELEASE_MANIFEST=<path>` выбирает точный артефакт для check, verify, restore или down; иначе его выбирает `RELEASE_ID`, по умолчанию равный текущему ID на основе коммита.
- `release-up` до запуска Compose сверяет хеши Compose-файлов и входных данных, локальные image ID собранных образов, digest скачанных образов и image ID из принятых проверок. Для собранных сервисов создается закрытый временный Compose override с точными image ID, затем Compose запускается с `--no-build --pull never`; тег удержания образа не выбирает сервис. После старта сверяются image ID контейнеров. Для `release-down` выберите те же `APP_PROJECT`, `ENV_FILE` и манифест. Именованные volumes сохраняются, но не являются снимком или резервной копией базы.
- `make -C deploy release-manifest-verify RELEASE_VERIFY_PROJECT=<project>` сравнивает image ID запущенных контейнеров с выбранным манифестом и завершается со статусом 1 при несовпадении, отсутствии сервиса или неизвестном сервисе.
- `make -C deploy release-manifest-verify RELEASE_VERIFY_PROJECT=<project>` сравнивает image ID запущенных контейнеров с выбранным манифестом и завершается со статусом 1 при несовпадении, отсутствии сервиса или неизвестном сервисе. Это работает и для демонстрационного проекта (`RELEASE_VERIFY_PROJECT=lincodex-demo`); одноразовый контейнер seed не сравнивается.
- `restore.demo` сообщает, можно ли восстановить [изолированный демонстрационный стенд](#изолированный-демонстрационный-стенд) из той же поставки: для этого нужны доступное восстановление core, образ demo seed, собранный `release-build` и удержанный по image ID, бинарник demo seed, собранный версией Go из go.mod, и хеши демонстрационных Compose-файлов. При публикации образ demo seed удерживается ссылкой `lincodex.invalid/release/demo-seed:<release-id>`, как собранные core-образы.
- `release-clean` удаляет ссылки на образы выпуска, которые не удерживает ни один неизменяемый манифест; файлы в `deploy/release/` остаются.
Тег исходников - первые 12 символов коммита с суффиксом `-dirty`, если рабочее дерево отличается от коммита. Отпечаток рабочего дерева - Git tree ID из временного индекса (заполняется из HEAD, затем `git add -A`) с закрепленными настройками переводов строк, режима файлов, symlink и fsmonitor. Он учитывает измененные, удаленные и неотслеживаемые файлы, не зависит от настроек diff и не меняет настоящий индекс. Записи сборки и evidence хранятся в `deploy/release/<source-tag>/`, неизменяемые манифесты - в `deploy/release/<release-id>/`. Git и корневой `.dockerignore` игнорируют эти локальные файлы. Манифест не коммитится: image ID собранных образов зависят от машины, платформы и времени сборки, а файл описывает конкретную локальную поставку.
@@ -650,17 +654,17 @@ Backend строится с Go 1.26.8; образ runtime выбран в backen
| `schema`, `generated_at` | Версия схемы и время генерации в UTC |
| `release` | Неизменяемый `id`, source `tag`, статус core (`verified` или `unverified`), `product_data_status` (`versioned`, `partial` или `unavailable`), обязательные проверки (`smoke`, `e2e`) и причины |
| `source` | `commit`, `dirty`, отпечаток рабочего дерева `fingerprint` (`git-tree:<id>` или null для чистого дерева) и `build_matches_source` |
| `toolchains` | Go из go.mod, его директива `toolchain`, значение `GO_IMAGE` по умолчанию, `GOTOOLCHAIN=local`, версия базового образа и версия, записанная в бинарнике backend; Node и pnpm из `.node-version`, `packageManager`, Dockerfile и базового образа; Python и uv из `.python-version`, `requires-python`, Dockerfile и базового образа; `matches_version_file` для Node и Python; версия пакета Playwright |
| `toolchains` | Go из go.mod, его директива `toolchain`, значение `GO_IMAGE` по умолчанию, `GOTOOLCHAIN=local`, версия базового образа и версия, записанная в бинарнике backend; тот же pin в `backend/Dockerfile.demo-seed` и версия в бинарнике demo seed; Node и pnpm из `.node-version`, `packageManager`, Dockerfile и базового образа; Python и uv из `.python-version`, `requires-python`, Dockerfile и базового образа; `matches_version_file` для Node и Python; версия пакета Playwright |
| `lockfiles` | SHA-256 `backend/go.mod`, `backend/go.sum`, `frontend/package.json`, `frontend/pnpm-lock.yaml`, `ml/pyproject.toml` и `ml/uv.lock` |
| `restore` | Можно ли восстановить core Compose-проект, точная команда и причины блокировки preflight |
| `configuration`, `data_versions` | SHA-256 core Compose-файлов; версии bank, policy и seed с ограниченными относительными путями артефактов, SHA-256, размерами, `source_kind` либо с явной причиной недоступности |
| `restore` | Можно ли восстановить core Compose-проект, точная команда и причины блокировки preflight; `demo` содержит то же для изолированного демонстрационного стенда |
| `configuration`, `data_versions` | SHA-256 core и демонстрационных Compose-файлов; версии bank, policy и seed с ограниченными относительными путями артефактов, SHA-256, размерами, `source_kind` либо с явной причиной недоступности |
| `checks`, `rejected_checks` | Принятые проверки с охватом, временем, коммитом, отпечатком, образом инструмента и image ID; отклоненные проверки с причиной |
| `components` | Сервисы Compose core, ML и monitoring и отсутствующие компоненты: `group`, `kind` (`built`, `pulled`, `absent`), метаданные образа, точный `restore_reference`, необязательная ссылка удержания собранного образа, данные сборки и `verification` |
| `components` | Сервисы Compose core, demo seed, ML и monitoring и отсутствующие компоненты: `group`, `kind` (`built`, `pulled`, `absent`), метаданные образа, точный `restore_reference`, необязательная ссылка удержания собранного образа, данные сборки и `verification` |
`verification.status` принимает значения:
- `verified`: хотя бы один принятый smoke или E2E записал именно этот image ID сервиса. Какие именно, перечисляет `verification.checks`. Проверенными могут быть только core-сервисы.
- `not_verified`: образа нет локально, он не участвовал в принятом успешном прогоне или относится к группе, которую не запускает ни одна проверка выпуска. ML собирается, но проверки его не запускают, и модели у него нет; образы monitoring записываются, только если есть локально.
- `not_verified`: образа нет локально, он не участвовал в принятом успешном прогоне или относится к группе, которую не запускает ни одна проверка выпуска. Образ demo seed собирается и закрепляется для демонстрационного стенда, но ни одна проверка выпуска его не запускает; ML собирается, но проверки его не запускают, и модели у него нет; образы monitoring записываются, только если есть локально.
- `missing`: компонент запланирован, но в репозитории нет его сервиса или образа: GPU inference, Judge0 и Qdrant.
Выпуск получает `verified`, только если выполнены все условия ниже; иначе `release.reasons` называет каждое невыполненное:
@@ -669,16 +673,16 @@ Backend строится с Go 1.26.8; образ runtime выбран в backen
- каждый core-образ собран `release-build`, у каждого скачанного core-образа есть registry digest;
- evidence и smoke, и E2E для текущих исходников прошел на текущем image ID каждого core-компонента;
- все lockfiles и Dockerfile сервисов существуют;
- Go pin согласован, и бинарник backend сообщает версию Go из go.mod;
- Go pin согласован, и бинарник backend, а при наличии образа и бинарник demo seed, сообщают версию Go из go.mod;
- Node в образе сборки frontend совпадает с `frontend/.node-version`.
Версия Python, отличная от `ml/.python-version`, отражается в `matches_version_file`, но не блокирует выпуск: ML вне проверяемого охвата. Поэтому плавающий тег `node:alpine` может сделать выпуск непроверенным, пока не обновлен `.node-version`. `release-manifest` отклоняет грязное дерево, сообщает причины и не создает новый манифест.
`source_kind` равен `bundled_source` для исходника демонстрационной политики и `snapshot` для входного снимка данных. `bundled_source` не доказывает, какая версия политики находится в runtime-базе. Bank и seed остаются недоступны, пока для них нет принятых снимков. Поля версий образа копируются только из разрешенных переменных и OCI labels. Манифест не содержит значения окружения, содержимое `.env`, labels контейнеров, mounts, локальные пути, имя пользователя или хоста. До публикации он проверяется на эти данные и секреты; `release-manifest-check` повторяет сканирование.
`source_kind` равен `bundled_source` для исходников демонстрационной политики и seed и `snapshot` для входного снимка данных. `bundled_source` не доказывает, какая версия политики находится в runtime-базе. Bank остается недоступен, пока для него нет принятого снимка. Поля версий образа копируются только из разрешенных переменных и OCI labels. Манифест не содержит значения окружения, содержимое `.env`, labels контейнеров, mounts, локальные пути, имя пользователя или хоста. До публикации он проверяется на эти данные и секреты; `release-manifest-check` повторяет сканирование.
### Go pin
go.mod объявляет `go 1.26.8` без отдельной строки `toolchain`, `GO_IMAGE` по умолчанию - `golang:1.26.8-alpine`, а этап сборки задает `GOTOOLCHAIN=local`, поэтому go.mod с требованием более новой Go роняет сборку вместо скачивания другого toolchain. `make -C deploy check` падает, если эти значения расходятся или Dockerfile использует базовый образ не через закрепляемый build-аргумент. Манифест также записывает версию из build information бинарника backend; для этого генератор создает контейнер из образа без запуска, копирует бинарник и удаляет контейнер.
go.mod объявляет `go 1.26.8` без отдельной строки `toolchain`, `GO_IMAGE` по умолчанию в `backend/Dockerfile` и `backend/Dockerfile.demo-seed` - `golang:1.26.8-alpine`, а оба этапа сборки задают `GOTOOLCHAIN=local`, поэтому go.mod с требованием более новой Go роняет сборку вместо скачивания другого toolchain. `make -C deploy check` падает, если эти значения расходятся или Dockerfile использует базовый образ не через закрепляемый build-аргумент. Манифест также записывает версию из build information бинарников backend и demo seed; для этого генератор создает контейнер из образа без запуска, копирует бинарник и удаляет контейнер.
### Что не покрыто
+5 -3
View File
@@ -85,7 +85,7 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f
## Тесты манифеста выпуска
`make -C deploy check-release` запускает `deploy/scripts/test_release_manifest.py` на стандартной библиотеке Python и без Docker. Тест падает, если go.mod, значение `GO_IMAGE` по умолчанию и `GOTOOLCHAIN=local` в backend/Dockerfile перестают закреплять Go 1.26.8 или если Dockerfile сервиса использует базовый образ не через закрепляемый build-аргумент `*_IMAGE`, в том числе внешний образ в `COPY --from` или `RUN --mount=from`. На подставных данных образов, Compose и контейнеров он проверяет, что:
`make -C deploy check-release` запускает `deploy/scripts/test_release_manifest.py` на стандартной библиотеке Python и без Docker. Тест падает, если go.mod, значение `GO_IMAGE` по умолчанию и `GOTOOLCHAIN=local` в backend/Dockerfile или backend/Dockerfile.demo-seed перестают закреплять Go 1.26.8 или если Dockerfile сервиса использует базовый образ не через закрепляемый build-аргумент `*_IMAGE`, в том числе внешний образ в `COPY --from` или `RUN --mount=from`. На подставных данных образов, Compose и контейнеров он проверяет, что:
- манифест не копирует значения окружения, labels и локальные пути, а две генерации различаются только `generated_at`;
- evidence засчитывается только для того же тега, коммита и отпечатка рабочего дерева, а evidence и записи сборки с неверной структурой не используются;
@@ -93,7 +93,9 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f
- `release-build` не пишет запись сборки, если коммит или рабочее дерево изменились во время сборки;
- отпечаток рабочего дерева временного Git-репозитория не зависит от настроек diff и переводов строк, учитывает неотслеживаемые файлы, пропускает игнорируемые и не меняет настоящий индекс;
- поиск секретов находит блоки ключей, токены, учетные данные в URL, локальные пути, имена пользователя и хоста и значения переменных, похожих на секреты, в том числе как подстроки и в base64, не печатая их;
- сравнение с запущенными контейнерами сообщает о другом digest, незапущенном и неизвестном сервисе.
- сравнение с запущенными контейнерами сообщает о другом digest, незапущенном и неизвестном сервисе;
- образ demo seed собирается с закрепленными базовыми образами под своим профилем, записывается, но никогда не считается проверенным, и удерживается по image ID; его отсутствие блокирует только восстановление демонстрационного стенда, другая версия Go в его бинарнике оставляет выпуск непроверенным, а demo override закрепляет core-сервисы и seed за точными image ID и digest и отказывает при отсутствующем образе, измененном демонстрационном overlay или манифесте без записи восстановления стенда;
- запись `seed` хеширует исходники demo seed без тестов, и ее версия меняется вместе с ними, но не с тестовым файлом.
Тест не собирает образы и не запускает контейнеры. Полный путь: `release-build`, `release-smoke` и `release-e2e`, `release-manifest`, `release-up`, `release-manifest-verify` и `release-manifest-check`; см. [DEPLOY.md](DEPLOY.md#манифест-выпуска).
@@ -493,7 +495,7 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
- Безошибочное экспресс-прохождение этого кандидата через операции попытки берет три задания из учебной категории, завершается результатом `demonstration` и не добавляет ни категории, ни доказательства; после этого тот же кандидат может начать полный тест.
- После регистрации обычного аккаунта в заполненной базе проверка сброса отказывает и учитывает его, повторный seed по-прежнему ничего не создает, а аккаунт не меняется.
`make -C deploy check-demo` (часть `make -C deploy check`) запускает `deploy/scripts/demo.sh` с записывающей заглушкой docker CLI: каждое действие отказывает без `DEMO_MODE=isolated`, с именем проекта, равным `APP_PROJECT` или без `demo`, с неверным исполнителем или без env-файла, до любой команды Docker; том проекта без демонстрационной метки отклоняется до любой команды Compose; отказ проверки сброса останавливает сброс до `down`; сброс обращается только к демонстрационному проекту и заново заполняет его; `down` сохраняет тома. При наличии docker CLI тест также рендерит overlay: опубликован только frontend и только на loopback; у контейнера seed только сеть default, корень только для чтения и явный профиль; у каждого тома есть демонстрационная метка; демонстрационный backend включает синтетические категории; backend-образы команду не содержат.
`make -C deploy check-demo` (часть `make -C deploy check`) запускает `deploy/scripts/demo.sh` с записывающей заглушкой docker CLI: каждое действие отказывает без `DEMO_MODE=isolated`, с именем проекта, равным `APP_PROJECT` или без `demo`, с неверным исполнителем или без env-файла, до любой команды Docker; том проекта без демонстрационной метки отклоняется до любой команды Compose; отказ проверки сброса останавливает сброс до `down`; сброс обращается только к демонстрационному проекту и заново заполняет его; `down` сохраняет тома; манифест выпуска, который нельзя восстановить, останавливает `seed` и `reset` до любой команды Compose, а `down` его не использует. При наличии docker CLI тест также рендерит overlay: опубликован только frontend и только на loopback; у контейнера seed только сеть default, корень только для чтения и явный профиль; у каждого тома есть демонстрационная метка; демонстрационный backend включает синтетические категории; release-overlay называет образ seed `lincodex.invalid/demo-seed:<tag>` с `pull_policy: never`; backend-образы команду не содержат.
Тесты не запускают 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.