feat(deploy): pin the demo seed in release manifests and restore the demo stand from them
This commit is contained in:
1 parent
e1df4ff77c
commit
b768f7e53f
14 files changed
+789
-147
No files matched your search
+9
-3
@@ -18,6 +18,7 @@ MONITORING_FILE := $(ROOT)/deploy/docker/docker-compose.monitoring.yml
|
||||
E2E_FILE := $(ROOT)/deploy/docker/docker-compose.e2e.yml
|
||||
E2E_MAIL_FILE := $(ROOT)/deploy/docker/docker-compose.e2e-mail.yml
|
||||
DEMO_FILE := $(ROOT)/deploy/docker/docker-compose.demo.yml
|
||||
DEMO_RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.demo.release.yml
|
||||
RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.release.yml
|
||||
ML_RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.ml.release.yml
|
||||
RELEASE_SCRIPT := $(ROOT)/deploy/scripts/release_manifest.py
|
||||
@@ -48,9 +49,13 @@ DEMO_FRONTEND_IP ?= 172.29.84.10
|
||||
DEMO_ACTOR ?= operator:demo-seed
|
||||
# demo.env is local; the checked-in example is used when it does not exist.
|
||||
DEMO_ENV ?= $(if $(wildcard $(ROOT)/deploy/demo/demo.env),$(ROOT)/deploy/demo/demo.env,$(ROOT)/deploy/demo/demo.env.example)
|
||||
# An explicit RELEASE_MANIFEST or RELEASE_ID restores the demo stand from that
|
||||
# immutable manifest; without them the stand builds from the current sources.
|
||||
DEMO_RELEASE_MANIFEST = $(if $(strip $(RELEASE_MANIFEST)),$(RELEASE_MANIFEST),$(if $(strip $(RELEASE_ID)),deploy/release/$(RELEASE_ID)/manifest.json,))
|
||||
DEMO_SCRIPT_ENV = DOCKER="$(DOCKER)" DEMO_MODE="$(DEMO_MODE)" DEMO_PROJECT="$(DEMO_PROJECT)" APP_PROJECT="$(APP_PROJECT)" \
|
||||
ENV_FILE="$(ENV_FILE)" DEMO_ENV_FILE="$(DEMO_ENV)" DEMO_HTTP_PORT="$(DEMO_HTTP_PORT)" DEMO_PUBLIC_URL="$(DEMO_PUBLIC_URL)" \
|
||||
DEMO_SUBNET="$(DEMO_SUBNET)" DEMO_FRONTEND_IP="$(DEMO_FRONTEND_IP)" DEMO_ACTOR="$(DEMO_ACTOR)"
|
||||
DEMO_SUBNET="$(DEMO_SUBNET)" DEMO_FRONTEND_IP="$(DEMO_FRONTEND_IP)" DEMO_ACTOR="$(DEMO_ACTOR)" \
|
||||
DEMO_RELEASE_MANIFEST="$(DEMO_RELEASE_MANIFEST)"
|
||||
PLAYWRIGHT_VERSION := $(shell sed -n 's/^ *"@playwright\/test": "\([^"]*\)",\{0,1\}$$/\1/p' "$(ROOT)/frontend/package.json")
|
||||
|
||||
.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows check-release check-perimeter check-e2e-mail check-demo perimeter-test smoke test-e2e test-e2e-registration release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean demo-seed demo-reset demo-down
|
||||
@@ -69,6 +74,7 @@ config: ## Render all Compose files with safe example values
|
||||
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" -f "$(ML_RELEASE_FILE)" config --quiet
|
||||
APP_PROJECT=lincodex-e2e-config APP_NETWORK=lincodex-e2e-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" --profile e2e config --quiet
|
||||
APP_PROJECT=lincodex-demo-config APP_NETWORK=lincodex-demo-config_default DEMO_ACCOUNT_PASSWORD=render-only-demo-account-password IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-demo-config -f "$(CORE_FILE)" -f "$(DEMO_FILE)" --profile demo-seed config --quiet
|
||||
APP_PROJECT=lincodex-demo-config APP_NETWORK=lincodex-demo-config_default LINCODEX_RELEASE_TAG=000000000000 DEMO_ACCOUNT_PASSWORD=render-only-demo-account-password IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-demo-config -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" -f "$(DEMO_FILE)" -f "$(DEMO_RELEASE_FILE)" --profile demo-seed config --quiet
|
||||
E2E_COMPANY_FIXTURE_TOKEN=render-only-company-fixture-token-00000000000000000000000000000000 APP_PROJECT=lincodex-e2e-mail-config APP_NETWORK=lincodex-e2e-mail-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-mail-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" -f "$(E2E_MAIL_FILE)" --profile e2e config --quiet
|
||||
|
||||
build: ## Build local frontend and backend images
|
||||
@@ -161,7 +167,7 @@ test-e2e: ## Run the Playwright suite against an isolated throwaway stack
|
||||
test-e2e-registration: ## Run browser registration tests with the local authenticated mail fixture
|
||||
@bash scripts/e2e.sh --mail-fixture
|
||||
|
||||
release-build: ## Build release images with every base image pinned to its resolved digest
|
||||
release-build: ## Build release images (core, demo seed, ML) with every base image pinned to its resolved digest
|
||||
@$(RELEASE) build --pull "$(RELEASE_PULL)"
|
||||
|
||||
release-smoke: ## Run the smoke against the release images and record passing evidence
|
||||
@@ -190,7 +196,7 @@ release-down: ## Stop the release project selected by the immutable manifest and
|
||||
release-clean: ## Remove local release image references not retained by an immutable manifest
|
||||
@$(RELEASE) clean-images
|
||||
|
||||
demo-seed: ## Start the isolated demo stand when needed and seed its synthetic data (needs DEMO_MODE=isolated)
|
||||
demo-seed: ## Start the isolated demo stand when needed and seed its synthetic data (needs DEMO_MODE=isolated; RELEASE_MANIFEST or RELEASE_ID pins it to a release)
|
||||
@$(DEMO_SCRIPT_ENV) bash scripts/demo.sh seed
|
||||
|
||||
demo-reset: ## Discard only the isolated demo project when it holds no ordinary account, then seed it again (needs DEMO_MODE=isolated)
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ Configuration for running the application with Docker Compose and Nginx.
|
||||
- `docker/docker-compose.ml.yml` and `docker/docker-compose.monitoring.yml` run ML and monitoring as separate projects.
|
||||
- `nginx/` configures frontend serving and API proxying.
|
||||
- `docker/docker-compose.e2e.yml` is an overlay used only by the browser suite: it removes the frontend host port and adds the Playwright runner.
|
||||
- `docker/docker-compose.release.yml` and `docker/docker-compose.ml.release.yml` are overlays that name the release images `lincodex.invalid/<service>:<tag>` and never pull them from a registry.
|
||||
- `docker/docker-compose.release.yml`, `docker/docker-compose.demo.release.yml`, and `docker/docker-compose.ml.release.yml` are overlays that name the release images `lincodex.invalid/<service>:<tag>` (the demo seed image included) and never pull them from a registry.
|
||||
- `docker/docker-compose.demo.yml` and `demo/` belong to the isolated demo stand with synthetic data: `make -C deploy demo-seed DEMO_MODE=isolated` starts and seeds it, `demo-reset` rebuilds it only when it holds no ordinary account, and `demo-down` stops it; see the [isolated demo stand](../docs/en/DEPLOY.md#isolated-demo-stand).
|
||||
- `scripts/` contains the isolated stack smoke check, the browser E2E runner, and `release_manifest.py`, which builds, describes, and checks release images.
|
||||
- `edge/` holds the public edge proxy: nginx and tunnel templates, certbot renewal hook, systemd drop-ins, and the scripts that render and check them. `make -C deploy edge-config` renders the nginx configuration and runs `nginx -t` in a container; see the [edge proxy runbook](../docs/en/DEPLOY.md#edge-proxy-https-and-tunnel).
|
||||
@@ -16,6 +16,6 @@ Configuration for running the application with Docker Compose and Nginx.
|
||||
|
||||
Dockerfiles live in service directories and `.env.example` at the repository root. From the root, `make -C deploy config` checks Compose and `make -C deploy up` starts the core stack after `.env` is prepared. Start monitoring separately with `make -C deploy monitoring-up`. `make -C deploy test-e2e` runs the Playwright suite against a throwaway stack under a unique project name and removes it afterwards; `make -C deploy test-e2e-registration` enables a local Resend-compatible inbox only for registration browser tests. See [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite) for details.
|
||||
|
||||
`make -C deploy release-build`, `release-smoke`, and `release-manifest` build the release images with pinned base image digests, check them, and write the manifest to `deploy/release/<tag>/`, which Git ignores; `make -C deploy release-manifest-verify` compares running containers with the manifest, and `make -C deploy release-clean` removes the release images. See the [release manifest](../docs/en/DEPLOY.md#release-manifest).
|
||||
`make -C deploy release-build`, `release-smoke`, `release-e2e`, and `release-manifest` build the release images with pinned base image digests, check them, and publish an immutable manifest to `deploy/release/<release-id>/`, which Git ignores; a new `RELEASE_ID` gives the next stage its own manifest. `make -C deploy release-manifest-check` scans the manifest for secrets and machine data, `release-manifest-verify` compares running containers with it, `release-up` restores the core stack and `demo-seed DEMO_MODE=isolated RELEASE_ID=<id>` the demo stand from its exact images, and `release-clean` removes release images that no manifest retains. See the [release manifest](../docs/en/DEPLOY.md#release-manifest).
|
||||
|
||||
See the [deployment guide](../docs/en/DEPLOY.md).
|
||||
+2
-2
@@ -8,7 +8,7 @@
|
||||
- `docker/docker-compose.ml.yml` и `docker/docker-compose.monitoring.yml` запускают ML и мониторинг отдельными проектами.
|
||||
- `nginx/` содержит конфигурацию раздачи frontend и проксирования API.
|
||||
- `docker/docker-compose.e2e.yml` - overlay только для браузерного набора: убирает host-порт frontend и добавляет запуск Playwright.
|
||||
- `docker/docker-compose.release.yml` и `docker/docker-compose.ml.release.yml` - overlay с именами образов выпуска `lincodex.invalid/<service>:<tag>` без скачивания из registry.
|
||||
- `docker/docker-compose.release.yml`, `docker/docker-compose.demo.release.yml` и `docker/docker-compose.ml.release.yml` - overlay с именами образов выпуска `lincodex.invalid/<service>:<tag>` (включая образ demo seed) без скачивания из registry.
|
||||
- `docker/docker-compose.demo.yml` и `demo/` относятся к изолированному демонстрационному стенду с синтетическими данными: `make -C deploy demo-seed DEMO_MODE=isolated` запускает и заполняет его, `demo-reset` пересоздает его, только если в нем нет обычных аккаунтов, а `demo-down` останавливает; см. [изолированный демонстрационный стенд](../docs/ru/DEPLOY.md#изолированный-демонстрационный-стенд).
|
||||
- `scripts/` содержит smoke-проверку изолированного стека, запуск браузерных E2E и `release_manifest.py` для сборки, описания и сверки образов выпуска.
|
||||
- `edge/` содержит публичный edge proxy: шаблоны nginx и туннеля, hook продления certbot, drop-in systemd и скрипты, которые их отрисовывают и проверяют. `make -C deploy edge-config` отрисовывает конфигурацию nginx и выполняет `nginx -t` в контейнере; см. [runbook edge proxy](../docs/ru/DEPLOY.md#edge-proxy-https-и-туннель).
|
||||
@@ -16,6 +16,6 @@
|
||||
|
||||
Dockerfile лежат в каталогах сервисов, `.env.example` - в корне репозитория. Из корня: `make -C deploy config` проверяет Compose, `make -C deploy up` запускает основной стек после подготовки `.env`. Мониторинг включается отдельно через `make -C deploy monitoring-up`. `make -C deploy test-e2e` запускает набор Playwright на одноразовом стеке с уникальным именем проекта и удаляет его после прогона; `make -C deploy test-e2e-registration` включает локальный Resend-compatible inbox только для браузерных тестов регистрации. Подробности см. в [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор).
|
||||
|
||||
`make -C deploy release-build`, `release-smoke` и `release-manifest` собирают образы выпуска с закрепленными digest базовых образов, проверяют их и пишут манифест в `deploy/release/<tag>/` (игнорируется Git); `make -C deploy release-manifest-verify` сверяет запущенные контейнеры с манифестом, а `make -C deploy release-clean` удаляет образы выпуска. См. [манифест выпуска](../docs/ru/DEPLOY.md#манифест-выпуска).
|
||||
`make -C deploy release-build`, `release-smoke`, `release-e2e` и `release-manifest` собирают образы выпуска с закрепленными digest базовых образов, проверяют их и публикуют неизменяемый манифест в `deploy/release/<release-id>/` (игнорируется Git); новый `RELEASE_ID` дает следующему этапу собственный манифест. `make -C deploy release-manifest-check` ищет в манифесте секреты и данные машины, `release-manifest-verify` сверяет с ним запущенные контейнеры, `release-up` восстанавливает основной стек, а `demo-seed DEMO_MODE=isolated RELEASE_ID=<id>` - демонстрационный стенд из точных образов, и `release-clean` удаляет образы выпуска, которые не удерживает ни один манифест. См. [манифест выпуска](../docs/ru/DEPLOY.md#манифест-выпуска).
|
||||
|
||||
Подробнее: [развертывание](../docs/ru/DEPLOY.md).
|
||||
@@ -0,0 +1,11 @@
|
||||
# Overlay that names the demo seed image built by make -C deploy release-build.
|
||||
# release_manifest.py renders it after docker-compose.yml,
|
||||
# docker-compose.release.yml, and docker-compose.demo.yml with the demo-seed
|
||||
# profile, so the demo seed image of a delivery is built with pinned base
|
||||
# images and recorded in its manifest. See docker-compose.release.yml for the
|
||||
# naming and pull rules. A demo stand restored from a manifest uses the exact
|
||||
# image ID instead of this tag.
|
||||
services:
|
||||
demo-seed:
|
||||
image: lincodex.invalid/demo-seed:${LINCODEX_RELEASE_TAG:?Set LINCODEX_RELEASE_TAG}
|
||||
pull_policy: never
|
||||
+36
-3
@@ -25,12 +25,17 @@
|
||||
# DEMO_PUBLIC_URL public origin of the demo stand
|
||||
# DEMO_SUBNET, DEMO_FRONTEND_IP pinned network of the demo project
|
||||
# DEMO_ACTOR operator:<handle> that the seed records
|
||||
# DEMO_RELEASE_MANIFEST optional repository-relative release manifest; seed
|
||||
# and reset then start and seed the stand from the exact
|
||||
# image IDs and digests it records, without building or
|
||||
# pulling, and check the running images against it
|
||||
# DOCKER docker CLI
|
||||
set -euo pipefail
|
||||
|
||||
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
compose_file="$root/deploy/docker/docker-compose.yml"
|
||||
demo_file="$root/deploy/docker/docker-compose.demo.yml"
|
||||
release_script="$root/deploy/scripts/release_manifest.py"
|
||||
docker_cli="${DOCKER:-docker}"
|
||||
demo_label='org.lincodex.demo-mode'
|
||||
ready_attempts=120
|
||||
@@ -72,6 +77,11 @@ port="${DEMO_HTTP_PORT:-8090}"
|
||||
public_url="${DEMO_PUBLIC_URL:-http://localhost:$port}"
|
||||
subnet="${DEMO_SUBNET:-172.29.84.0/24}"
|
||||
frontend_ip="${DEMO_FRONTEND_IP:-172.29.84.10}"
|
||||
release_manifest="${DEMO_RELEASE_MANIFEST:-}"
|
||||
compose_files=(-f "$compose_file" -f "$demo_file")
|
||||
# From the current sources by default; pinned by the release override below.
|
||||
up_args=(--build)
|
||||
run_args=(--build)
|
||||
|
||||
# The shell values override the env files, so the root .env cannot point the
|
||||
# demo project at the ordinary project's names, network, or port.
|
||||
@@ -80,7 +90,7 @@ compose() {
|
||||
APP_HTTP_PORT="$port" APP_SUBNET="$subnet" APP_FRONTEND_IP="$frontend_ip" APP_PUBLIC_URL="$public_url" \
|
||||
DEMO_MODE=isolated "$docker_cli" compose \
|
||||
--env-file "$env_file" --env-file "$demo_env_file" \
|
||||
-p "$project" -f "$compose_file" -f "$demo_file" "$@"
|
||||
-p "$project" "${compose_files[@]}" "$@"
|
||||
}
|
||||
|
||||
volume_exists() {
|
||||
@@ -101,12 +111,32 @@ check_volumes() {
|
||||
done
|
||||
}
|
||||
|
||||
# The release script pins every service of the stand, the seed included, to
|
||||
# the image IDs and digests of the manifest after checking that the Compose
|
||||
# files and data artifacts still match it. The override lives in a private
|
||||
# temporary directory for this run only.
|
||||
pin_release_images() {
|
||||
override_dir=$(mktemp -d)
|
||||
trap 'rm -rf "$override_dir"' EXIT
|
||||
DOCKER="$docker_cli" PYTHONDONTWRITEBYTECODE=1 python3 "$release_script" demo-override \
|
||||
--manifest "$release_manifest" --output-dir "$override_dir" ||
|
||||
fail "refusing to $action: the release manifest $release_manifest cannot be restored on the demo stand"
|
||||
compose_files+=(-f "$override_dir/release-restore.yml")
|
||||
up_args=(--no-build --pull never)
|
||||
run_args=()
|
||||
}
|
||||
|
||||
start_stand() {
|
||||
compose up -d --build --wait --wait-timeout 300
|
||||
compose up -d "${up_args[@]}" --wait --wait-timeout 300
|
||||
local attempt response
|
||||
for ((attempt = 1; attempt <= ready_attempts; attempt++)); do
|
||||
response=$(compose exec -T frontend wget -q -O - http://backend:8080/readyz 2>/dev/null || true)
|
||||
if [[ "$response" == '{"status":"ready"}' ]]; then
|
||||
if [[ -n "$release_manifest" ]]; then
|
||||
DOCKER="$docker_cli" PYTHONDONTWRITEBYTECODE=1 python3 "$release_script" verify \
|
||||
--project "$project" --manifest "$release_manifest" ||
|
||||
fail "the running images of $project differ from $release_manifest"
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
sleep 1
|
||||
@@ -115,7 +145,7 @@ start_stand() {
|
||||
}
|
||||
|
||||
run_command() {
|
||||
compose --profile demo-seed run --rm --build demo-seed "$@"
|
||||
compose --profile demo-seed run --rm ${run_args[@]+"${run_args[@]}"} demo-seed "$@"
|
||||
}
|
||||
|
||||
# The inventory after the seed lets two runs be compared line by line.
|
||||
@@ -128,6 +158,9 @@ seed() {
|
||||
}
|
||||
|
||||
check_volumes
|
||||
if [[ -n "$release_manifest" && "$action" != down ]]; then
|
||||
pin_release_images
|
||||
fi
|
||||
case "$action" in
|
||||
seed)
|
||||
seed
|
||||
|
||||
@@ -12,6 +12,8 @@ Subcommands (deploy/Makefile is the supported interface):
|
||||
restore preflight and restore exact images for a selected manifest
|
||||
verify compare running containers of a project with a manifest
|
||||
check check a manifest's structure and scan it for machine secrets
|
||||
demo-override preflight a manifest for the isolated demo stand and write
|
||||
the Compose override that pins its exact images
|
||||
clean-images remove unretained local lincodex.invalid/* release images
|
||||
|
||||
Only the standard library is used. Docker is called through the CLI; no
|
||||
@@ -59,6 +61,9 @@ RENDER_PROJECT = "lincodex-release"
|
||||
# Compose requires IDENTITY_KEY_SECRET and .env.example has none; this value only
|
||||
# lets a render or build go through and is never deployed.
|
||||
RENDER_ONLY_IDENTITY_KEY = "render-only-identity-key-secret-not-for-deployment"
|
||||
# The demo overlay requires DEMO_ACCOUNT_PASSWORD; this value only lets a
|
||||
# render or build of the demo seed image go through and is never deployed.
|
||||
RENDER_ONLY_DEMO_PASSWORD = "render-only-demo-account-password"
|
||||
CHECKS = ("smoke", "e2e")
|
||||
DATA_COMPONENTS = ("bank", "policy", "seed")
|
||||
RELEASE_ID_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
|
||||
@@ -70,6 +75,20 @@ CORE_COMPOSE_FILES = (
|
||||
"deploy/docker/docker-compose.yml",
|
||||
"deploy/docker/docker-compose.release.yml",
|
||||
)
|
||||
# The isolated demo stand adds these to the core files; deploy/scripts/demo.sh
|
||||
# restores it from a manifest through command_demo_override.
|
||||
DEMO_COMPOSE_FILES = (
|
||||
"deploy/docker/docker-compose.demo.yml",
|
||||
"deploy/docker/docker-compose.demo.release.yml",
|
||||
)
|
||||
RELEASE_COMPOSE_FILES = CORE_COMPOSE_FILES + DEMO_COMPOSE_FILES
|
||||
DEMO_PROFILE = "demo-seed"
|
||||
DEMO_SEED_SERVICE = "demo-seed"
|
||||
# The demo seed dataset, including its synthetic bank, is Go source compiled
|
||||
# into the demo seed image; the manifest versions it by the hash of this
|
||||
# package's non-test files.
|
||||
SEED_SOURCE_DIR = "backend/internal/usecase/demoseed"
|
||||
SEED_DOCKERFILE = "backend/Dockerfile.demo-seed"
|
||||
CHECK_SCOPE = {
|
||||
"smoke": (
|
||||
"deploy/scripts/smoke.sh: Compose startup and health, API routing, PostgreSQL, Redis, and "
|
||||
@@ -91,10 +110,23 @@ class Group:
|
||||
# Groups whose images a passing smoke or E2E run can verify.
|
||||
verifiable: bool
|
||||
unverified_reason: str
|
||||
# Files rendered before compose_file, for a group that is an overlay.
|
||||
base_files: tuple[str, ...] = ()
|
||||
# A group with a profile takes only the services of that profile.
|
||||
profile: str | None = None
|
||||
|
||||
|
||||
GROUPS = (
|
||||
Group("core", "deploy/docker/docker-compose.yml", "deploy/docker/docker-compose.release.yml", True, ""),
|
||||
Group(
|
||||
"demo",
|
||||
DEMO_COMPOSE_FILES[0],
|
||||
DEMO_COMPOSE_FILES[1],
|
||||
False,
|
||||
"Built by release-build and pinned for the isolated demo stand, but no release check runs the demo seed.",
|
||||
base_files=CORE_COMPOSE_FILES,
|
||||
profile=DEMO_PROFILE,
|
||||
),
|
||||
Group(
|
||||
"ml",
|
||||
"deploy/docker/docker-compose.ml.yml",
|
||||
@@ -374,11 +406,48 @@ def default_data_versions(root: Path = ROOT) -> dict[str, Any]:
|
||||
}
|
||||
else:
|
||||
result["policy"]["reason"] = "No versioned demo policy source is present."
|
||||
result["bank"]["reason"] = "No accepted assessment bank release snapshot is present."
|
||||
result["seed"]["reason"] = "No versioned demo seed release snapshot is present."
|
||||
result["bank"]["reason"] = (
|
||||
"No accepted assessment bank release snapshot is present; the synthetic demo bank is versioned with the seed."
|
||||
)
|
||||
seed_paths = seed_source_paths(root)
|
||||
if seed_paths:
|
||||
result["seed"] = bundled_source_entry(seed_paths, "demo-seed", "Demo seed source", root)
|
||||
else:
|
||||
result["seed"]["reason"] = "No versioned demo seed source is present."
|
||||
return result
|
||||
|
||||
|
||||
def seed_source_paths(root: Path = ROOT) -> list[str]:
|
||||
"""Return the non-test Go files of the demo seed package, sorted."""
|
||||
directory = root / SEED_SOURCE_DIR
|
||||
if directory.is_symlink():
|
||||
raise ReleaseError("Demo seed source directory cannot be a symlink.")
|
||||
if not directory.is_dir():
|
||||
return []
|
||||
return sorted(
|
||||
f"{SEED_SOURCE_DIR}/{path.name}"
|
||||
for path in directory.iterdir()
|
||||
if path.name.endswith(".go") and not path.name.endswith("_test.go")
|
||||
)
|
||||
|
||||
|
||||
def bundled_source_entry(paths: list[str], prefix: str, label: str, root: Path = ROOT) -> dict[str, Any]:
|
||||
"""Version checked-in source files by a hash over their paths and digests."""
|
||||
artifacts: list[dict[str, Any]] = []
|
||||
combined = hashlib.sha256()
|
||||
for path_text in paths:
|
||||
path = project_file(path_text, root, maximum_size=DATA_ARTIFACT_SIZE_LIMIT, label=label)
|
||||
digest, size = bounded_digest(path, maximum_size=DATA_ARTIFACT_SIZE_LIMIT)
|
||||
artifacts.append({"path": path_text, "sha256": digest, "size_bytes": size})
|
||||
combined.update(f"{path_text}\0{digest}\n".encode("utf-8"))
|
||||
return {
|
||||
"status": "available",
|
||||
"version": f"{prefix}.{combined.hexdigest()[:12]}",
|
||||
"source_kind": "bundled_source",
|
||||
"artifacts": artifacts,
|
||||
}
|
||||
|
||||
|
||||
def read_data_versions(path_text: str | None, root: Path = ROOT) -> dict[str, Any]:
|
||||
if not path_text:
|
||||
return default_data_versions(root)
|
||||
@@ -641,6 +710,11 @@ def manifest_restore_command(release_id: str) -> str:
|
||||
return f"make -C deploy release-up RELEASE_MANIFEST=deploy/release/{release_id}/manifest.json"
|
||||
|
||||
|
||||
def demo_restore_command(release_id: str) -> str:
|
||||
validate_release_id(release_id)
|
||||
return f"make -C deploy demo-seed DEMO_MODE=isolated RELEASE_MANIFEST=deploy/release/{release_id}/manifest.json"
|
||||
|
||||
|
||||
def relative(path: Path, root: Path = ROOT) -> str:
|
||||
try:
|
||||
return path.resolve().relative_to(root.resolve()).as_posix()
|
||||
@@ -751,23 +825,37 @@ def dockerfile_bases(text: str, source: str = "Dockerfile") -> list[BaseImage]:
|
||||
return [bases[name] for name in sorted(bases)]
|
||||
|
||||
|
||||
def go_build_pin(dockerfile: str, source: str) -> tuple[str, bool]:
|
||||
"""Return the GO_IMAGE default and whether its build stage sets GOTOOLCHAIN=local."""
|
||||
bases = {base.arg: base.default for base in dockerfile_bases(dockerfile, source)}
|
||||
build_stage = dockerfile.split("FROM ${GO_IMAGE}", 1)[-1].split("\nFROM ", 1)[0]
|
||||
return bases.get("GO_IMAGE", ""), bool(re.search(r"^ENV\s+GOTOOLCHAIN=local\s*$", build_stage, re.MULTILINE))
|
||||
|
||||
|
||||
def go_policy(root: Path = ROOT) -> dict[str, Any]:
|
||||
"""Describe the Go pin and whether go.mod and the build image agree."""
|
||||
"""Describe the Go pin and whether go.mod and every Go build image agree."""
|
||||
go_mod = (root / "backend/go.mod").read_text(encoding="utf-8")
|
||||
directive = re.search(r"^go\s+(\S+)\s*$", go_mod, re.MULTILINE)
|
||||
toolchain = re.search(r"^toolchain\s+(\S+)\s*$", go_mod, re.MULTILINE)
|
||||
dockerfile = (root / "backend/Dockerfile").read_text(encoding="utf-8")
|
||||
bases = {base.arg: base.default for base in dockerfile_bases(dockerfile, "backend/Dockerfile")}
|
||||
image = bases.get("GO_IMAGE", "")
|
||||
image, gotoolchain_local = go_build_pin((root / "backend/Dockerfile").read_text(encoding="utf-8"), "backend/Dockerfile")
|
||||
image_version = re.match(r"^golang:([0-9]+\.[0-9]+\.[0-9]+)-", image)
|
||||
build_stage = dockerfile.split("FROM ${GO_IMAGE}", 1)[-1].split("\nFROM ", 1)[0]
|
||||
version = directive.group(1) if directive else None
|
||||
policy = {
|
||||
"go_mod": version,
|
||||
"toolchain_directive": toolchain.group(1) if toolchain else None,
|
||||
"dockerfile_image": image or None,
|
||||
"gotoolchain_local": bool(re.search(r"^ENV\s+GOTOOLCHAIN=local\s*$", build_stage, re.MULTILINE)),
|
||||
"gotoolchain_local": gotoolchain_local,
|
||||
"demo_seed_dockerfile_image": None,
|
||||
"demo_seed_gotoolchain_local": None,
|
||||
}
|
||||
# The demo seed image builds the same module, so it must use the same pin.
|
||||
seed_matches = True
|
||||
seed_dockerfile = root / SEED_DOCKERFILE
|
||||
if seed_dockerfile.is_file():
|
||||
seed_image, seed_local = go_build_pin(seed_dockerfile.read_text(encoding="utf-8"), SEED_DOCKERFILE)
|
||||
policy["demo_seed_dockerfile_image"] = seed_image or None
|
||||
policy["demo_seed_gotoolchain_local"] = seed_local
|
||||
seed_matches = bool(seed_image and seed_image == image and seed_local)
|
||||
policy["consistent"] = bool(
|
||||
version
|
||||
and re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version)
|
||||
@@ -775,6 +863,7 @@ def go_policy(root: Path = ROOT) -> dict[str, Any]:
|
||||
and image_version.group(1) == version
|
||||
and policy["toolchain_directive"] in (None, f"go{version}")
|
||||
and policy["gotoolchain_local"]
|
||||
and seed_matches
|
||||
)
|
||||
return policy
|
||||
|
||||
@@ -835,6 +924,19 @@ def docker_env(extra: dict[str, str] | None = None) -> dict[str, str]:
|
||||
return env
|
||||
|
||||
|
||||
def render_env(tag: str) -> dict[str, str]:
|
||||
"""Environment of a render or build from .env.example under RENDER_PROJECT."""
|
||||
return docker_env(
|
||||
{
|
||||
"APP_PROJECT": RENDER_PROJECT,
|
||||
"APP_NETWORK": f"{RENDER_PROJECT}_default",
|
||||
"LINCODEX_RELEASE_TAG": tag,
|
||||
"IDENTITY_KEY_SECRET": RENDER_ONLY_IDENTITY_KEY,
|
||||
"DEMO_ACCOUNT_PASSWORD": RENDER_ONLY_DEMO_PASSWORD,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class Docker:
|
||||
"""Thin CLI wrapper; tests replace it with a fake."""
|
||||
|
||||
@@ -850,20 +952,16 @@ class Docker:
|
||||
data = json.loads(result.stdout)
|
||||
return data[0] if data else None
|
||||
|
||||
def compose_config(self, files: list[str], tag: str, root: Path = ROOT) -> dict[str, Any]:
|
||||
def compose_config(
|
||||
self, files: list[str], tag: str, root: Path = ROOT, profile: str | None = None
|
||||
) -> dict[str, Any]:
|
||||
args = [self.binary, "compose", "--env-file", str(root / ".env.example"), "-p", RENDER_PROJECT]
|
||||
for name in files:
|
||||
args += ["-f", str(root / name)]
|
||||
if profile:
|
||||
args += ["--profile", profile]
|
||||
args += ["config", "--format", "json"]
|
||||
env = docker_env(
|
||||
{
|
||||
"APP_PROJECT": RENDER_PROJECT,
|
||||
"APP_NETWORK": f"{RENDER_PROJECT}_default",
|
||||
"LINCODEX_RELEASE_TAG": tag,
|
||||
"IDENTITY_KEY_SECRET": RENDER_ONLY_IDENTITY_KEY,
|
||||
}
|
||||
)
|
||||
return json.loads(run(args, cwd=root, env=env))
|
||||
return json.loads(run(args, cwd=root, env=render_env(tag)))
|
||||
|
||||
def project_containers(self, project: str) -> list[dict[str, Any]]:
|
||||
ids = run(
|
||||
@@ -904,24 +1002,26 @@ class Docker:
|
||||
if subprocess.run([self.binary, "pull", reference], check=False, env=docker_env()).returncode != 0:
|
||||
raise ReleaseError(f"Could not pull {reference}.")
|
||||
|
||||
def compose_build(self, files: list[str], tag: str, service: str, build_args: dict[str, str], root: Path = ROOT) -> None:
|
||||
def compose_build(
|
||||
self,
|
||||
files: list[str],
|
||||
tag: str,
|
||||
service: str,
|
||||
build_args: dict[str, str],
|
||||
root: Path = ROOT,
|
||||
profile: str | None = None,
|
||||
) -> None:
|
||||
args = [self.binary, "compose", "--env-file", str(root / ".env.example"), "-p", RENDER_PROJECT]
|
||||
for name in files:
|
||||
args += ["-f", str(root / name)]
|
||||
if profile:
|
||||
args += ["--profile", profile]
|
||||
args += ["build"]
|
||||
for name, value in sorted(build_args.items()):
|
||||
args += ["--build-arg", f"{name}={value}"]
|
||||
args.append(service)
|
||||
env = docker_env(
|
||||
{
|
||||
"APP_PROJECT": RENDER_PROJECT,
|
||||
"APP_NETWORK": f"{RENDER_PROJECT}_default",
|
||||
"LINCODEX_RELEASE_TAG": tag,
|
||||
"IDENTITY_KEY_SECRET": RENDER_ONLY_IDENTITY_KEY,
|
||||
}
|
||||
)
|
||||
print(f"Building {service} for release {tag}", flush=True)
|
||||
if subprocess.run(args, cwd=root, env=env, check=False).returncode != 0:
|
||||
if subprocess.run(args, cwd=root, env=render_env(tag), check=False).returncode != 0:
|
||||
raise ReleaseError(f"Building {service} failed.")
|
||||
|
||||
def tag_image(self, image_id: str, reference: str) -> None:
|
||||
@@ -1057,14 +1157,26 @@ class Service:
|
||||
context: str | None = None
|
||||
compose_file: str = ""
|
||||
overlay: str | None = None
|
||||
# Every file and the profile Compose needs to render or build the service.
|
||||
render_files: tuple[str, ...] = ()
|
||||
profile: str | None = None
|
||||
|
||||
|
||||
def group_files(group: Group) -> list[str]:
|
||||
return [*group.base_files, group.compose_file] + ([group.release_overlay] if group.release_overlay else [])
|
||||
|
||||
|
||||
def group_services(docker: Docker, group: Group, tag: str, root: Path = ROOT) -> list[Service]:
|
||||
files = [group.compose_file] + ([group.release_overlay] if group.release_overlay else [])
|
||||
config = docker.compose_config(files, tag, root)
|
||||
files = group_files(group)
|
||||
config = docker.compose_config(files, tag, root, profile=group.profile)
|
||||
services: list[Service] = []
|
||||
for name, spec in sorted((config.get("services") or {}).items()):
|
||||
if spec.get("profiles"):
|
||||
profiles = spec.get("profiles") or []
|
||||
if group.profile:
|
||||
# An overlay group renders the core services too; keep only its own.
|
||||
if group.profile not in profiles:
|
||||
continue
|
||||
elif profiles:
|
||||
continue
|
||||
build = spec.get("build")
|
||||
reference = spec.get("image")
|
||||
@@ -1074,10 +1186,22 @@ def group_services(docker: Docker, group: Group, tag: str, root: Path = ROOT) ->
|
||||
context = Path(build["context"])
|
||||
dockerfile = context / build.get("dockerfile", "Dockerfile")
|
||||
services.append(
|
||||
Service(group.name, name, reference, relative(dockerfile, root), relative(context, root) or ".", group.compose_file, group.release_overlay)
|
||||
Service(
|
||||
group.name,
|
||||
name,
|
||||
reference,
|
||||
relative(dockerfile, root),
|
||||
relative(context, root) or ".",
|
||||
group.compose_file,
|
||||
group.release_overlay,
|
||||
tuple(files),
|
||||
group.profile,
|
||||
)
|
||||
)
|
||||
elif reference:
|
||||
services.append(Service(group.name, name, reference, compose_file=group.compose_file))
|
||||
services.append(
|
||||
Service(group.name, name, reference, compose_file=group.compose_file, render_files=tuple(files), profile=group.profile)
|
||||
)
|
||||
return services
|
||||
|
||||
|
||||
@@ -1105,8 +1229,8 @@ def command_build(args: argparse.Namespace, docker: Docker | None = None, root:
|
||||
policy = go_policy(root)
|
||||
if not policy["consistent"]:
|
||||
raise ReleaseError(
|
||||
"The Go pin is inconsistent: backend/go.mod, the toolchain directive, the GO_IMAGE default, "
|
||||
"and ENV GOTOOLCHAIN=local in backend/Dockerfile must agree."
|
||||
"The Go pin is inconsistent: backend/go.mod, the toolchain directive, the GO_IMAGE defaults, "
|
||||
"and ENV GOTOOLCHAIN=local in backend/Dockerfile and backend/Dockerfile.demo-seed must agree."
|
||||
)
|
||||
record: dict[str, Any] = {
|
||||
"schema": BUILD_SCHEMA,
|
||||
@@ -1137,8 +1261,8 @@ def command_build(args: argparse.Namespace, docker: Docker | None = None, root:
|
||||
bases.append(
|
||||
{"arg": base.arg, "reference": base.default, "digest": digest, "versions": image_versions(info)}
|
||||
)
|
||||
files = [service.compose_file] + ([service.overlay] if service.overlay else [])
|
||||
docker.compose_build(files, source.tag, service.name, build_args, root)
|
||||
files = list(service.render_files) or [service.compose_file] + ([service.overlay] if service.overlay else [])
|
||||
docker.compose_build(files, source.tag, service.name, build_args, root, profile=service.profile)
|
||||
info = docker.inspect_image(service.reference)
|
||||
if info is None:
|
||||
raise ReleaseError(f"{service.reference} is missing after the build.")
|
||||
@@ -1358,6 +1482,18 @@ class Inputs:
|
||||
files: dict[str, str | None] = field(default_factory=dict)
|
||||
rejected_checks: dict[str, str] = field(default_factory=dict)
|
||||
build_problem: str | None = None
|
||||
seed_go_binary: str | None = None
|
||||
|
||||
|
||||
def image_go_version(docker: Docker, info: dict[str, Any] | None) -> str | None:
|
||||
"""Return the Go version recorded in the entrypoint binary of a local image."""
|
||||
if not info:
|
||||
return None
|
||||
entrypoint = (info.get("Config") or {}).get("Entrypoint") or []
|
||||
if not entrypoint:
|
||||
return None
|
||||
content = docker.read_file(info["Id"], entrypoint[0])
|
||||
return go_build_version(content) if content else None
|
||||
|
||||
|
||||
def collect_inputs(docker: Docker, root: Path = ROOT) -> Inputs:
|
||||
@@ -1374,13 +1510,8 @@ def collect_inputs(docker: Docker, root: Path = ROOT) -> Inputs:
|
||||
build_problem = build_record_problem(build) if build is not None else None
|
||||
if build_problem:
|
||||
build = None
|
||||
go_binary = None
|
||||
backend = images.get(release_reference("backend", source.tag))
|
||||
if backend:
|
||||
entrypoint = (backend.get("Config") or {}).get("Entrypoint") or []
|
||||
if entrypoint:
|
||||
content = docker.read_file(backend["Id"], entrypoint[0])
|
||||
go_binary = go_build_version(content) if content else None
|
||||
go_binary = image_go_version(docker, images.get(release_reference("backend", source.tag)))
|
||||
seed_go_binary = image_go_version(docker, images.get(release_reference(DEMO_SEED_SERVICE, source.tag)))
|
||||
files = {name: file_digest(root / name) for name in LOCKFILES}
|
||||
files[".node-version"] = text_match(root / "frontend/.node-version", r"^\s*(\S+)\s*$")
|
||||
files["packageManager"] = text_match(root / "frontend/package.json", r'"packageManager":\s*"([^"]+)"')
|
||||
@@ -1393,7 +1524,7 @@ def collect_inputs(docker: Docker, root: Path = ROOT) -> Inputs:
|
||||
if service.dockerfile:
|
||||
files[service.dockerfile] = file_digest(root / service.dockerfile)
|
||||
return Inputs(
|
||||
source, services, images, build, evidence, go_binary, go_policy(root), files, rejected, build_problem
|
||||
source, services, images, build, evidence, go_binary, go_policy(root), files, rejected, build_problem, seed_go_binary
|
||||
)
|
||||
|
||||
|
||||
@@ -1417,7 +1548,7 @@ def build_manifest(
|
||||
release_id = validate_release_id(release_id or inputs.source.tag)
|
||||
data_versions = data_versions if data_versions is not None else default_data_versions(root)
|
||||
compose_files = compose_files if compose_files is not None else {
|
||||
name: file_digest(root / name) for name in CORE_COMPOSE_FILES
|
||||
name: file_digest(root / name) for name in RELEASE_COMPOSE_FILES
|
||||
}
|
||||
source = inputs.source
|
||||
build = inputs.build_record
|
||||
@@ -1428,11 +1559,17 @@ def build_manifest(
|
||||
components: list[dict[str, Any]] = []
|
||||
reasons: list[str] = []
|
||||
restore_reasons: list[str] = []
|
||||
demo_reasons: list[str] = []
|
||||
demo_present = False
|
||||
for service in inputs.services:
|
||||
image = image_record(inputs.images.get(service.reference), service.reference, built=bool(service.dockerfile))
|
||||
image["restore_reference"], image["retention_reference"] = immutable_image_references(service, image, release_id)
|
||||
if service.group == "core" and image["restore_reference"] is None:
|
||||
restore_reasons.append(f"Core component {service.name} has no immutable local image reference.")
|
||||
if service.group == "demo":
|
||||
demo_present = demo_present or bool(image.get("present"))
|
||||
if image["restore_reference"] is None:
|
||||
demo_reasons.append(f"Demo component {service.name} has no immutable local image reference.")
|
||||
component: dict[str, Any] = {
|
||||
"name": service.name,
|
||||
"group": service.group,
|
||||
@@ -1485,6 +1622,10 @@ def build_manifest(
|
||||
reasons.append(f"Core image {service.name} was not built by release-build.")
|
||||
if not service.dockerfile and image.get("present") and not image.get("repo_digest"):
|
||||
reasons.append(f"Core image {service.name} has no registry digest.")
|
||||
if service.group == "demo" and service.dockerfile and not component["build"]["recorded_by_release_build"]:
|
||||
demo_reasons.append(f"Demo image {service.name} was not built by release-build for this tag.")
|
||||
if not any(service.group == "demo" for service in inputs.services):
|
||||
demo_reasons.append("No demo seed service was found in the demo stand Compose files.")
|
||||
for name, reason in sorted(MISSING_COMPONENTS.items()):
|
||||
components.append(
|
||||
{
|
||||
@@ -1495,7 +1636,7 @@ def build_manifest(
|
||||
"verification": {"status": "missing", "reason": reason, "checks": []},
|
||||
}
|
||||
)
|
||||
components.sort(key=lambda item: (["core", "ml", "monitoring", "missing"].index(item["group"]), item["name"]))
|
||||
components.sort(key=lambda item: (COMPONENT_GROUP_ORDER.index(item["group"]), item["name"]))
|
||||
|
||||
go = dict(inputs.go)
|
||||
go["build_image_version"] = base_version(build, "backend", "GOLANG_VERSION")
|
||||
@@ -1505,6 +1646,13 @@ def build_manifest(
|
||||
reasons.append("The Go pin in go.mod and backend/Dockerfile is inconsistent.")
|
||||
if not go["binary_matches"]:
|
||||
reasons.append("The backend binary was not confirmed to be built with the go.mod Go version.")
|
||||
go["demo_seed_binary"] = inputs.seed_go_binary
|
||||
go["demo_seed_binary_matches"] = bool(go["go_mod"] and inputs.seed_go_binary == f"go{go['go_mod']}")
|
||||
if demo_present and not go["demo_seed_binary_matches"]:
|
||||
# The demo seed image is delivered with the release, so a Go drift in
|
||||
# it is a silent toolchain change too.
|
||||
reasons.append("The demo seed binary was not confirmed to be built with the go.mod Go version.")
|
||||
demo_reasons.append("The demo seed binary was not confirmed to be built with the go.mod Go version.")
|
||||
|
||||
node_image = base_version(build, "frontend", "NODE_VERSION")
|
||||
node_matches = bool(node_image and node_image == files.get(".node-version"))
|
||||
@@ -1529,7 +1677,11 @@ def build_manifest(
|
||||
|
||||
for name, digest in sorted(compose_files.items()):
|
||||
if digest is None:
|
||||
restore_reasons.append(f"Compose file {name} is missing.")
|
||||
(demo_reasons if name in DEMO_COMPOSE_FILES else restore_reasons).append(f"Compose file {name} is missing.")
|
||||
if any(name not in compose_files for name in DEMO_COMPOSE_FILES):
|
||||
demo_reasons.append("The demo stand Compose files are not recorded.")
|
||||
if restore_reasons:
|
||||
demo_reasons.append("The core restore is blocked.")
|
||||
data_states = [data_versions[name]["status"] for name in DATA_COMPONENTS]
|
||||
product_data_status = "versioned" if all(state == "available" for state in data_states) else (
|
||||
"partial" if any(state == "available" for state in data_states) else "unavailable"
|
||||
@@ -1567,6 +1719,11 @@ def build_manifest(
|
||||
"scope": "core",
|
||||
"command": restore_command,
|
||||
"reasons": sorted(set(restore_reasons)),
|
||||
"demo": {
|
||||
"status": "blocked" if demo_reasons else "available",
|
||||
"command": demo_restore_command(release_id),
|
||||
"reasons": sorted(set(demo_reasons)),
|
||||
},
|
||||
},
|
||||
"source": {
|
||||
"commit": source.commit,
|
||||
@@ -1607,33 +1764,46 @@ def comparable(document: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
return {key: value for key, value in document.items() if key != "generated_at"}
|
||||
|
||||
|
||||
def add_restore_problem(manifest: dict[str, Any], problem: str) -> None:
|
||||
def block_restore(section: dict[str, Any], problem: str) -> None:
|
||||
section["status"] = "blocked"
|
||||
section["reasons"] = sorted(set(section["reasons"] + [problem]))
|
||||
|
||||
|
||||
def add_restore_problem(manifest: dict[str, Any], problem: str, group: str = "core") -> None:
|
||||
"""Block the restore of a group; the demo stand also needs the core images."""
|
||||
restore = manifest["restore"]
|
||||
restore["status"] = "blocked"
|
||||
restore["reasons"] = sorted(set(restore["reasons"] + [problem]))
|
||||
if group == "core":
|
||||
block_restore(restore, problem)
|
||||
problem = "The core restore is blocked."
|
||||
if isinstance(restore.get("demo"), dict):
|
||||
block_restore(restore["demo"], problem)
|
||||
|
||||
|
||||
def prepare_manifest_images(manifest: dict[str, Any], docker: Docker) -> None:
|
||||
"""Retain built core image IDs and confirm pulled digests before publication."""
|
||||
"""Retain built core and demo image IDs and confirm pulled digests before publication."""
|
||||
for component in manifest["components"]:
|
||||
if component.get("group") != "core":
|
||||
group = component.get("group")
|
||||
if group not in ("core", "demo"):
|
||||
continue
|
||||
label = "Core" if group == "core" else "Demo"
|
||||
image = component.get("image") or {}
|
||||
reference = image.get("restore_reference")
|
||||
retention_reference = image.get("retention_reference")
|
||||
image_id = image.get("image_id")
|
||||
if not image.get("present") or not isinstance(image_id, str) or not reference:
|
||||
add_restore_problem(manifest, f"Core component {component.get('name')} has no immutable local image reference.")
|
||||
add_restore_problem(
|
||||
manifest, f"{label} component {component.get('name')} has no immutable local image reference.", group
|
||||
)
|
||||
continue
|
||||
if component.get("kind") == "built":
|
||||
if reference != image_id or not retention_reference:
|
||||
add_restore_problem(manifest, f"Built image {component.get('name')} is not pinned to its image ID.")
|
||||
add_restore_problem(manifest, f"Built image {component.get('name')} is not pinned to its image ID.", group)
|
||||
continue
|
||||
existing = docker.inspect_image(retention_reference)
|
||||
if existing is None:
|
||||
source = docker.inspect_image(image_id)
|
||||
if source is None or source.get("Id") != image_id:
|
||||
add_restore_problem(manifest, f"Exact local image {image_id} for {component.get('name')} is missing.")
|
||||
add_restore_problem(manifest, f"Exact local image {image_id} for {component.get('name')} is missing.", group)
|
||||
continue
|
||||
docker.tag_image(image_id, retention_reference)
|
||||
existing = docker.inspect_image(retention_reference)
|
||||
@@ -1642,7 +1812,9 @@ def prepare_manifest_images(manifest: dict[str, Any], docker: Docker) -> None:
|
||||
else:
|
||||
existing = docker.inspect_image(reference)
|
||||
if existing is None or existing.get("Id") != image_id:
|
||||
add_restore_problem(manifest, f"Pulled digest for {component.get('name')} does not resolve to the recorded image ID.")
|
||||
add_restore_problem(
|
||||
manifest, f"Pulled digest for {component.get('name')} does not resolve to the recorded image ID.", group
|
||||
)
|
||||
if manifest["restore"]["reasons"]:
|
||||
manifest["restore"]["status"] = "blocked"
|
||||
|
||||
@@ -1714,7 +1886,7 @@ def command_manifest(args: argparse.Namespace, docker: Docker | None = None, roo
|
||||
inputs = collect_inputs(docker, root)
|
||||
release_id = validate_release_id(args.release_id or inputs.source.tag)
|
||||
data_versions = read_data_versions(args.data_manifest, root)
|
||||
compose_files = {name: file_digest(root / name) for name in CORE_COMPOSE_FILES}
|
||||
compose_files = {name: file_digest(root / name) for name in RELEASE_COMPOSE_FILES}
|
||||
manifest = build_manifest(inputs, utc_now(), release_id, data_versions, compose_files, root)
|
||||
require_verified_release(manifest)
|
||||
path = release_artifact_dir(release_id, root) / "manifest.json"
|
||||
@@ -1743,6 +1915,10 @@ def command_manifest(args: argparse.Namespace, docker: Docker | None = None, roo
|
||||
print(f" - {reason}")
|
||||
for reason in manifest["restore"]["reasons"]:
|
||||
print(f" - restore blocked: {reason}")
|
||||
demo = manifest["restore"]["demo"]
|
||||
print(f"Demo stand restore {demo['status']}: {demo['command']}")
|
||||
for reason in demo["reasons"]:
|
||||
print(f" - demo restore blocked: {reason}")
|
||||
for component in manifest["components"]:
|
||||
image = component["image"] or {}
|
||||
status = component["verification"]["status"]
|
||||
@@ -1840,6 +2016,7 @@ REQUIRED_KEYS = (
|
||||
"components",
|
||||
)
|
||||
STATUSES = frozenset({"verified", "not_verified", "missing"})
|
||||
COMPONENT_GROUP_ORDER = ("core", "demo", "ml", "monitoring", "missing")
|
||||
SHA256_PATTERN = re.compile(r"sha256:[0-9a-f]{64}")
|
||||
IMAGE_ID_PATTERN = SHA256_PATTERN
|
||||
|
||||
@@ -1933,17 +2110,18 @@ def structure_errors(manifest: dict[str, Any], root: Path = ROOT) -> list[str]:
|
||||
ids = evidence.get("image_ids") if isinstance(evidence, dict) else None
|
||||
if not isinstance(ids, dict) or ids.get(name) != image_id:
|
||||
errors.append(f"verified component {name} does not match the recorded {check} image ID")
|
||||
if component.get("group") == "core":
|
||||
if component.get("kind") == "built":
|
||||
if image.get("restore_reference") != image_id:
|
||||
errors.append(f"built core component {name} is not pinned to its exact image ID")
|
||||
try:
|
||||
expected_retention = release_image_reference(name, release.get("id"))
|
||||
except (ReleaseError, TypeError):
|
||||
expected_retention = None
|
||||
if image.get("retention_reference") != expected_retention:
|
||||
errors.append(f"built core component {name} has an invalid retention reference")
|
||||
elif component.get("kind") == "pulled":
|
||||
group = component.get("group")
|
||||
if group in ("core", "demo") and component.get("kind") == "built":
|
||||
if image.get("restore_reference") != image_id:
|
||||
errors.append(f"built {group} component {name} is not pinned to its exact image ID")
|
||||
try:
|
||||
expected_retention = release_image_reference(name, release.get("id"))
|
||||
except (ReleaseError, TypeError):
|
||||
expected_retention = None
|
||||
if image.get("retention_reference") != expected_retention:
|
||||
errors.append(f"built {group} component {name} has an invalid retention reference")
|
||||
elif group == "core":
|
||||
if component.get("kind") == "pulled":
|
||||
digest = image.get("repo_digest")
|
||||
if not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest):
|
||||
errors.append(f"pulled core component {name} has no repository digest")
|
||||
@@ -1987,15 +2165,18 @@ def structure_errors(manifest: dict[str, Any], root: Path = ROOT) -> list[str]:
|
||||
errors.append("blocked restore has no reason")
|
||||
|
||||
config = manifest.get("configuration")
|
||||
compose_inventory: dict[str, Any] = {}
|
||||
if not isinstance(config, dict) or not isinstance(config.get("compose_files"), dict):
|
||||
errors.append("Compose file digests are malformed")
|
||||
else:
|
||||
files = config["compose_files"]
|
||||
if set(files) != set(CORE_COMPOSE_FILES):
|
||||
compose_inventory = config["compose_files"]
|
||||
# Manifests written before the demo stand was pinned list the core files only.
|
||||
if set(compose_inventory) not in (set(CORE_COMPOSE_FILES), set(RELEASE_COMPOSE_FILES)):
|
||||
errors.append("Compose file digest inventory is incomplete")
|
||||
for name, digest in files.items():
|
||||
for name, digest in compose_inventory.items():
|
||||
if digest is not None and (not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest)):
|
||||
errors.append(f"Compose file digest for {name} is invalid")
|
||||
errors += demo_restore_errors(manifest, restore, components, compose_inventory)
|
||||
|
||||
data = manifest.get("data_versions")
|
||||
if not isinstance(data, dict) or set(data) != set(DATA_COMPONENTS):
|
||||
@@ -2073,6 +2254,49 @@ def structure_errors(manifest: dict[str, Any], root: Path = ROOT) -> list[str]:
|
||||
return errors
|
||||
|
||||
|
||||
def demo_restore_errors(
|
||||
manifest: dict[str, Any], restore: dict[str, Any], components: list[Any], compose_inventory: dict[str, Any]
|
||||
) -> list[str]:
|
||||
"""Check the optional demo stand restore entry; older manifests have none."""
|
||||
if "demo" not in restore:
|
||||
return []
|
||||
demo = restore["demo"]
|
||||
if not isinstance(demo, dict) or set(demo) != {"status", "command", "reasons"}:
|
||||
return ["demo restore entry is malformed"]
|
||||
errors: list[str] = []
|
||||
release_info = manifest.get("release") if isinstance(manifest.get("release"), dict) else {}
|
||||
try:
|
||||
expected_command = demo_restore_command(release_info.get("id"))
|
||||
except (ReleaseError, TypeError):
|
||||
expected_command = None
|
||||
reasons = demo.get("reasons")
|
||||
if (
|
||||
demo.get("status") not in {"available", "blocked"}
|
||||
or demo.get("command") != expected_command
|
||||
or not isinstance(reasons, list)
|
||||
or not all(isinstance(reason, str) for reason in reasons)
|
||||
):
|
||||
return ["demo restore status, command, or reasons are malformed"]
|
||||
if demo["status"] == "blocked":
|
||||
if not reasons:
|
||||
errors.append("blocked demo restore has no reason")
|
||||
return errors
|
||||
if reasons:
|
||||
errors.append("available demo restore has blocking reasons")
|
||||
if restore.get("status") != "available":
|
||||
errors.append("available demo restore needs an available core restore")
|
||||
if any(not compose_inventory.get(name) for name in DEMO_COMPOSE_FILES):
|
||||
errors.append("available demo restore has no demo stand Compose file digests")
|
||||
demo_components = [item for item in components if isinstance(item, dict) and item.get("group") == "demo"]
|
||||
if not demo_components:
|
||||
errors.append("available demo restore has no demo component")
|
||||
for component in demo_components:
|
||||
image = component.get("image") if isinstance(component.get("image"), dict) else {}
|
||||
if not image.get("present") or not image.get("restore_reference"):
|
||||
errors.append(f"available demo restore has no exact image for {component.get('name')}")
|
||||
return errors
|
||||
|
||||
|
||||
def command_check(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int:
|
||||
path = manifest_file(args.manifest, root)
|
||||
try:
|
||||
@@ -2101,9 +2325,11 @@ def command_check(args: argparse.Namespace, docker: Docker | None = None, root:
|
||||
return 0
|
||||
|
||||
|
||||
def check_compose_files(manifest: dict[str, Any], root: Path = ROOT) -> None:
|
||||
def check_compose_files(
|
||||
manifest: dict[str, Any], root: Path = ROOT, names: tuple[str, ...] = CORE_COMPOSE_FILES
|
||||
) -> None:
|
||||
expected = (manifest.get("configuration") or {}).get("compose_files") or {}
|
||||
for name in CORE_COMPOSE_FILES:
|
||||
for name in names:
|
||||
want = expected.get(name)
|
||||
actual = file_digest(root / name)
|
||||
if not want or actual != want:
|
||||
@@ -2165,6 +2391,40 @@ def restore_images(manifest: dict[str, Any], docker: Docker, root: Path = ROOT)
|
||||
return result
|
||||
|
||||
|
||||
def restore_demo_images(manifest: dict[str, Any], docker: Docker, root: Path = ROOT) -> dict[str, str]:
|
||||
"""Return the exact image IDs of the demo services, retaining them like core images."""
|
||||
release_id = manifest["release"]["id"]
|
||||
demo_group = next(group for group in GROUPS if group.name == "demo")
|
||||
expected_services = {item.name for item in group_services(docker, demo_group, manifest["release"]["tag"], root)}
|
||||
components = {item["name"]: item for item in manifest["components"] if item.get("group") == "demo"}
|
||||
if not components or set(components) != expected_services:
|
||||
raise ReleaseError("Demo stand Compose services differ from the immutable release manifest.")
|
||||
result: dict[str, str] = {}
|
||||
for name, component in sorted(components.items()):
|
||||
image = component.get("image") or {}
|
||||
image_id = image.get("image_id")
|
||||
retention_reference = release_image_reference(name, release_id)
|
||||
if (
|
||||
component.get("kind") != "built"
|
||||
or not image.get("present")
|
||||
or not isinstance(image_id, str)
|
||||
or image.get("restore_reference") != image_id
|
||||
or image.get("retention_reference") != retention_reference
|
||||
):
|
||||
raise ReleaseError(f"Demo image {name} is not pinned to its exact image ID in the manifest.")
|
||||
local = docker.inspect_image(image_id)
|
||||
if local is None or local.get("Id") != image_id:
|
||||
raise ReleaseError(f"Exact local image {image_id} for {name} is missing; restore will not rebuild it.")
|
||||
retained = docker.inspect_image(retention_reference)
|
||||
if retained is None:
|
||||
docker.tag_image(image_id, retention_reference)
|
||||
retained = docker.inspect_image(retention_reference)
|
||||
if retained is None or retained.get("Id") != image_id:
|
||||
raise ReleaseError(f"Retained release reference for {name} points to a different image ID.")
|
||||
result[name] = image_id
|
||||
return result
|
||||
|
||||
|
||||
def write_compose_override(directory: Path, images: dict[str, str]) -> Path:
|
||||
if any(not re.fullmatch(r"[a-z0-9][a-z0-9_.-]*", name) for name in images):
|
||||
raise ReleaseError("Compose override contains an invalid service name.")
|
||||
@@ -2235,6 +2495,38 @@ def command_restore(args: argparse.Namespace, docker: Docker | None = None, root
|
||||
return 0
|
||||
|
||||
|
||||
def command_demo_override(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int:
|
||||
"""Preflight a manifest for the isolated demo stand and write its pinned override.
|
||||
|
||||
deploy/scripts/demo.sh combines the override with docker-compose.yml and
|
||||
docker-compose.demo.yml, so the demo stand starts and seeds from the exact
|
||||
image IDs and digests of the delivery instead of building or resolving tags.
|
||||
"""
|
||||
docker = docker or Docker()
|
||||
directory = Path(args.output_dir)
|
||||
if not directory.is_absolute() or directory.is_symlink() or not directory.is_dir():
|
||||
raise ReleaseError("The override directory must be an existing absolute directory.")
|
||||
path = manifest_file(args.manifest, root)
|
||||
manifest = load_manifest(path, root)
|
||||
validate_manifest_location(path, manifest, root)
|
||||
problems = structure_errors(manifest, root) + forbidden_findings(manifest)
|
||||
if problems:
|
||||
raise ReleaseError(f"Release manifest at {display(path, root)} is invalid: " + "; ".join(sorted(set(problems))))
|
||||
demo = manifest["restore"].get("demo")
|
||||
if not isinstance(demo, dict):
|
||||
raise ReleaseError("The manifest has no demo stand restore entry; publish a new manifest for the demo stand.")
|
||||
if manifest["restore"]["status"] != "available" or demo["status"] != "available":
|
||||
reasons = "; ".join(manifest["restore"]["reasons"] + demo["reasons"])
|
||||
raise ReleaseError("Demo stand restore is blocked" + (f": {reasons}" if reasons else "."))
|
||||
check_compose_files(manifest, root, RELEASE_COMPOSE_FILES)
|
||||
verify_data_artifacts(manifest["data_versions"], root)
|
||||
images = restore_images(manifest, docker, root)
|
||||
images.update(restore_demo_images(manifest, docker, root))
|
||||
override = write_compose_override(directory, images)
|
||||
print(f"Pinned the demo stand to {display(path, root)} (release {manifest['release']['id']}) in {override.name}.")
|
||||
return 0
|
||||
|
||||
|
||||
def retained_image_references(root: Path = ROOT) -> set[str]:
|
||||
release_root = root / RELEASE_DIR_NAME
|
||||
if release_root.is_symlink():
|
||||
@@ -2322,6 +2614,10 @@ def parser() -> argparse.ArgumentParser:
|
||||
check = commands.add_parser("check")
|
||||
check.add_argument("--manifest")
|
||||
check.set_defaults(handler=command_check)
|
||||
demo_override = commands.add_parser("demo-override")
|
||||
demo_override.add_argument("--manifest", required=True)
|
||||
demo_override.add_argument("--output-dir", required=True)
|
||||
demo_override.set_defaults(handler=command_demo_override)
|
||||
return result
|
||||
|
||||
|
||||
|
||||
@@ -140,6 +140,24 @@ class DemoScriptGuardTest(unittest.TestCase):
|
||||
self.assertIn(" seed --actor operator:demo-seed", compose_calls[-2])
|
||||
self.assertTrue(compose_calls[-1].endswith(" inventory"))
|
||||
|
||||
def test_an_unrestorable_release_manifest_stops_before_compose(self):
|
||||
manifest = "deploy/release/demo-guard-absent/manifest.json"
|
||||
self.assertFalse((ROOT / manifest).exists())
|
||||
for action in ("seed", "reset"):
|
||||
with self.subTest(action=action):
|
||||
result = self.run_script(action, DEMO_RELEASE_MANIFEST=manifest)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertIn("cannot be restored on the demo stand", result.stderr)
|
||||
self.assertFalse([call for call in self.calls() if call.startswith("compose")])
|
||||
|
||||
def test_down_ignores_the_release_manifest(self):
|
||||
result = self.run_script("down", DEMO_RELEASE_MANIFEST="deploy/release/demo-guard-absent/manifest.json")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
compose_calls = [call for call in self.calls() if call.startswith("compose")]
|
||||
self.assertEqual(len(compose_calls), 1)
|
||||
self.assertNotIn("release-restore.yml", compose_calls[0])
|
||||
self.assertTrue(compose_calls[0].endswith(" down"))
|
||||
|
||||
def test_down_keeps_the_volumes(self):
|
||||
result = self.run_script("down")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
@@ -148,7 +166,7 @@ class DemoScriptGuardTest(unittest.TestCase):
|
||||
self.assertTrue(compose_calls[0].endswith(" down"))
|
||||
|
||||
|
||||
def render_demo(project="lincodex-demo-render"):
|
||||
def render_demo(project="lincodex-demo-render", release_tag=None):
|
||||
environment = dict(
|
||||
os.environ,
|
||||
APP_PROJECT=project,
|
||||
@@ -162,11 +180,14 @@ def render_demo(project="lincodex-demo-render"):
|
||||
DEMO_MODE="isolated",
|
||||
)
|
||||
environment.pop("APP_HTTP_BIND", None)
|
||||
command = [
|
||||
DOCKER, "compose", "--env-file", str(ROOT / ".env.example"), "-p", project,
|
||||
"-f", str(DEPLOY / "docker" / "docker-compose.yml"), "-f", str(DEPLOY / "docker" / "docker-compose.demo.yml"),
|
||||
"--profile", "demo-seed", "config", "--format", "json",
|
||||
]
|
||||
files = ["docker-compose.yml", "docker-compose.demo.yml"]
|
||||
if release_tag:
|
||||
environment["LINCODEX_RELEASE_TAG"] = release_tag
|
||||
files = ["docker-compose.yml", "docker-compose.release.yml", "docker-compose.demo.yml", "docker-compose.demo.release.yml"]
|
||||
command = [DOCKER, "compose", "--env-file", str(ROOT / ".env.example"), "-p", project]
|
||||
for name in files:
|
||||
command += ["-f", str(DEPLOY / "docker" / name)]
|
||||
command += ["--profile", "demo-seed", "config", "--format", "json"]
|
||||
result = subprocess.run(command, capture_output=True, text=True, env=environment, check=False)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(f"docker compose config failed: {result.stderr}")
|
||||
@@ -206,6 +227,13 @@ class DemoOverlayTest(unittest.TestCase):
|
||||
self.assertEqual(backend["environment"]["ASSESSMENT_DEMO_CATEGORIES_ENABLED"], "true")
|
||||
self.assertEqual(backend["labels"]["org.lincodex.demo-mode"], "isolated")
|
||||
|
||||
def test_the_release_overlay_names_the_seed_image_without_pulling(self):
|
||||
rendered = render_demo(release_tag="0123456789ab")
|
||||
seed = rendered["services"]["demo-seed"]
|
||||
self.assertEqual(seed["image"], "lincodex.invalid/demo-seed:0123456789ab")
|
||||
self.assertEqual(seed["pull_policy"], "never")
|
||||
self.assertEqual(rendered["services"]["backend"]["image"], "lincodex.invalid/backend:0123456789ab")
|
||||
|
||||
def test_release_and_ordinary_images_never_contain_the_seed(self):
|
||||
for dockerfile in ("Dockerfile", "Dockerfile.e2e"):
|
||||
self.assertNotIn("demo-seed", (ROOT / "backend" / dockerfile).read_text())
|
||||
|
||||
@@ -36,6 +36,7 @@ BACKEND_ID = fake_id("b")
|
||||
FRONTEND_ID = fake_id("f")
|
||||
POSTGRES_ID = fake_id("e")
|
||||
ML_ID = fake_id("c")
|
||||
SEED_ID = fake_id("5")
|
||||
|
||||
|
||||
def image(image_id: str, *, env: list[str] | None = None, digests: list[str] | None = None) -> dict:
|
||||
@@ -59,6 +60,14 @@ def services(tag: str) -> list:
|
||||
service("core", "backend", f"lincodex.invalid/backend:{tag}", "backend/Dockerfile", "backend", "deploy/docker/docker-compose.yml"),
|
||||
service("core", "frontend", f"lincodex.invalid/frontend:{tag}", "frontend/Dockerfile", ".", "deploy/docker/docker-compose.yml"),
|
||||
service("core", "postgres", "postgres:alpine", compose_file="deploy/docker/docker-compose.yml"),
|
||||
service(
|
||||
"demo",
|
||||
"demo-seed",
|
||||
f"lincodex.invalid/demo-seed:{tag}",
|
||||
"backend/Dockerfile.demo-seed",
|
||||
"backend",
|
||||
"deploy/docker/docker-compose.demo.yml",
|
||||
),
|
||||
service("ml", "ml", f"lincodex.invalid/ml:{tag}", "ml/Dockerfile", ".", "deploy/docker/docker-compose.ml.yml"),
|
||||
service("monitoring", "prometheus", "prom/prometheus:latest", compose_file="deploy/docker/docker-compose.monitoring.yml"),
|
||||
]
|
||||
@@ -84,6 +93,7 @@ CURRENT_IDS = {"backend": BACKEND_ID, "frontend": FRONTEND_ID, "postgres": POSTG
|
||||
def all_files() -> dict:
|
||||
files = {name: fake_id("0") for name in release.LOCKFILES}
|
||||
files.update({"backend/Dockerfile": fake_id("1"), "frontend/Dockerfile": fake_id("2"), "ml/Dockerfile": fake_id("3")})
|
||||
files["backend/Dockerfile.demo-seed"] = fake_id("4")
|
||||
files.update({".node-version": "26.10.0", ".python-version": "3.14.8"})
|
||||
return files
|
||||
|
||||
@@ -94,6 +104,8 @@ def inputs(
|
||||
evidence_ids: dict | None = None,
|
||||
checks: tuple = ("smoke", "e2e"),
|
||||
go_binary: str | None = "go1.26.8",
|
||||
seed_go_binary: str | None = "go1.26.8",
|
||||
seed_present: bool = True,
|
||||
files: dict | None = None,
|
||||
postgres_digests: list | None = None,
|
||||
node_version: str = "26.10.0",
|
||||
@@ -107,6 +119,7 @@ def inputs(
|
||||
"postgres:alpine": image(
|
||||
POSTGRES_ID, env=["PG_VERSION=18.6"], digests=[f"postgres@{POSTGRES_ID}"] if postgres_digests is None else postgres_digests
|
||||
),
|
||||
f"lincodex.invalid/demo-seed:{tag}": image(SEED_ID) if seed_present else None,
|
||||
f"lincodex.invalid/ml:{tag}": image(ML_ID, env=["PYTHON_VERSION=3.14.8"]),
|
||||
"prom/prometheus:latest": None,
|
||||
}
|
||||
@@ -127,6 +140,13 @@ def inputs(
|
||||
"build_args": {},
|
||||
"base_images": [{"arg": "NODE_IMAGE", "reference": "node:alpine", "digest": fake_id("d"), "versions": {"NODE_VERSION": node_version}}],
|
||||
},
|
||||
"demo-seed": {
|
||||
"image_id": SEED_ID,
|
||||
"build_args": {"GO_IMAGE": f"golang:1.26.8-alpine@{fake_id('a')}"},
|
||||
"base_images": [
|
||||
{"arg": "GO_IMAGE", "reference": "golang:1.26.8-alpine", "digest": fake_id("a"), "versions": {"GOLANG_VERSION": "1.26.8"}}
|
||||
],
|
||||
},
|
||||
"ml": {
|
||||
"image_id": ML_ID,
|
||||
"build_args": {},
|
||||
@@ -136,8 +156,26 @@ def inputs(
|
||||
}
|
||||
ids = CURRENT_IDS if evidence_ids is None else evidence_ids
|
||||
evidence = {check: evidence_doc(check, source, ids) for check in checks}
|
||||
go = {"go_mod": "1.26.8", "toolchain_directive": None, "dockerfile_image": "golang:1.26.8-alpine", "gotoolchain_local": True, "consistent": True}
|
||||
return release.Inputs(source, services(tag), images, build, evidence, go_binary, go, all_files() if files is None else files)
|
||||
go = {
|
||||
"go_mod": "1.26.8",
|
||||
"toolchain_directive": None,
|
||||
"dockerfile_image": "golang:1.26.8-alpine",
|
||||
"gotoolchain_local": True,
|
||||
"demo_seed_dockerfile_image": "golang:1.26.8-alpine",
|
||||
"demo_seed_gotoolchain_local": True,
|
||||
"consistent": True,
|
||||
}
|
||||
return release.Inputs(
|
||||
source,
|
||||
services(tag),
|
||||
images,
|
||||
build,
|
||||
evidence,
|
||||
go_binary,
|
||||
go,
|
||||
all_files() if files is None else files,
|
||||
seed_go_binary=seed_go_binary,
|
||||
)
|
||||
|
||||
|
||||
def component(manifest: dict, name: str) -> dict:
|
||||
@@ -151,10 +189,12 @@ class PinTest(unittest.TestCase):
|
||||
self.assertIn(policy["toolchain_directive"], (None, f"go{AGREED_GO}"))
|
||||
self.assertEqual(policy["dockerfile_image"], f"golang:{AGREED_GO}-alpine")
|
||||
self.assertTrue(policy["gotoolchain_local"], "backend/Dockerfile must set ENV GOTOOLCHAIN=local in the build stage")
|
||||
self.assertEqual(policy["demo_seed_dockerfile_image"], f"golang:{AGREED_GO}-alpine")
|
||||
self.assertTrue(policy["demo_seed_gotoolchain_local"], "backend/Dockerfile.demo-seed must set ENV GOTOOLCHAIN=local")
|
||||
self.assertTrue(policy["consistent"])
|
||||
|
||||
def test_every_service_base_image_is_a_pinnable_argument(self) -> None:
|
||||
for name in ("backend/Dockerfile", "frontend/Dockerfile", "ml/Dockerfile"):
|
||||
for name in ("backend/Dockerfile", "backend/Dockerfile.demo-seed", "frontend/Dockerfile", "ml/Dockerfile"):
|
||||
with self.subTest(dockerfile=name):
|
||||
bases = release.dockerfile_bases((ROOT / name).read_text(encoding="utf-8"), name)
|
||||
self.assertTrue(bases)
|
||||
@@ -194,6 +234,24 @@ class PinTest(unittest.TestCase):
|
||||
(root / "backend/Dockerfile").write_text("ARG GO_IMAGE=golang:1.26.8-alpine\nFROM ${GO_IMAGE} AS build\n", encoding="utf-8")
|
||||
self.assertFalse(release.go_policy(root)["consistent"])
|
||||
|
||||
def test_demo_seed_dockerfile_must_share_the_go_pin(self) -> None:
|
||||
import tempfile
|
||||
|
||||
pinned = "ARG GO_IMAGE=golang:1.26.8-alpine\nFROM ${GO_IMAGE} AS build\nENV GOTOOLCHAIN=local\n"
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / "backend").mkdir()
|
||||
(root / "backend/go.mod").write_text("module x\n\ngo 1.26.8\n", encoding="utf-8")
|
||||
(root / "backend/Dockerfile").write_text(pinned, encoding="utf-8")
|
||||
self.assertTrue(release.go_policy(root)["consistent"])
|
||||
seed = root / "backend/Dockerfile.demo-seed"
|
||||
seed.write_text(pinned, encoding="utf-8")
|
||||
self.assertTrue(release.go_policy(root)["consistent"])
|
||||
seed.write_text(pinned.replace("1.26.8", "1.27.0"), encoding="utf-8")
|
||||
self.assertFalse(release.go_policy(root)["consistent"])
|
||||
seed.write_text(pinned.replace("ENV GOTOOLCHAIN=local\n", ""), encoding="utf-8")
|
||||
self.assertFalse(release.go_policy(root)["consistent"])
|
||||
|
||||
|
||||
class BuildInfoTest(unittest.TestCase):
|
||||
def blob(self, version: bytes, offset: int = 64) -> bytes:
|
||||
@@ -240,6 +298,51 @@ class ManifestTest(unittest.TestCase):
|
||||
self.assertEqual(component(manifest, name)["verification"]["status"], "missing")
|
||||
self.assertIsNone(component(manifest, name)["image"])
|
||||
|
||||
def test_demo_seed_is_pinned_for_the_demo_stand_but_not_verified(self) -> None:
|
||||
manifest = release.build_manifest(inputs(), "t", release_id="stage-demo")
|
||||
seed = component(manifest, "demo-seed")
|
||||
self.assertEqual(seed["group"], "demo")
|
||||
self.assertEqual(seed["kind"], "built")
|
||||
self.assertEqual(seed["verification"]["status"], "not_verified")
|
||||
self.assertIn("no release check runs the demo seed", seed["verification"]["reason"])
|
||||
self.assertEqual(seed["image"]["restore_reference"], SEED_ID)
|
||||
self.assertEqual(seed["image"]["retention_reference"], "lincodex.invalid/release/demo-seed:stage-demo")
|
||||
self.assertEqual(seed["build"]["base_images"][0]["digest"], fake_id("a"))
|
||||
self.assertEqual(manifest["toolchains"]["go"]["demo_seed_binary"], "go1.26.8")
|
||||
self.assertEqual(
|
||||
manifest["restore"]["demo"],
|
||||
{
|
||||
"status": "available",
|
||||
"command": "make -C deploy demo-seed DEMO_MODE=isolated RELEASE_MANIFEST=deploy/release/stage-demo/manifest.json",
|
||||
"reasons": [],
|
||||
},
|
||||
)
|
||||
self.assertEqual(manifest["release"]["status"], "verified", manifest["release"]["reasons"])
|
||||
self.assertEqual(release.structure_errors(manifest), [])
|
||||
|
||||
def test_missing_demo_seed_image_blocks_only_the_demo_restore(self) -> None:
|
||||
manifest = release.build_manifest(inputs(seed_present=False, seed_go_binary=None), "t")
|
||||
self.assertEqual(manifest["release"]["status"], "verified", manifest["release"]["reasons"])
|
||||
self.assertEqual(manifest["restore"]["status"], "available")
|
||||
self.assertEqual(manifest["restore"]["demo"]["status"], "blocked")
|
||||
self.assertIn("Demo component demo-seed has no immutable local image reference.", manifest["restore"]["demo"]["reasons"])
|
||||
self.assertEqual(release.structure_errors(manifest), [])
|
||||
|
||||
def test_demo_seed_go_drift_keeps_the_release_unverified(self) -> None:
|
||||
manifest = release.build_manifest(inputs(seed_go_binary="go1.27.0"), "t")
|
||||
self.assertEqual(manifest["release"]["status"], "unverified")
|
||||
reason = "The demo seed binary was not confirmed to be built with the go.mod Go version."
|
||||
self.assertIn(reason, manifest["release"]["reasons"])
|
||||
self.assertIn(reason, manifest["restore"]["demo"]["reasons"])
|
||||
self.assertFalse(manifest["toolchains"]["go"]["demo_seed_binary_matches"])
|
||||
|
||||
def test_blocked_core_restore_blocks_the_demo_restore(self) -> None:
|
||||
manifest = release.build_manifest(inputs(), "t")
|
||||
release.add_restore_problem(manifest, "Pulled digest for postgres does not resolve to the recorded image ID.")
|
||||
self.assertEqual(manifest["restore"]["status"], "blocked")
|
||||
self.assertEqual(manifest["restore"]["demo"]["reasons"], ["The core restore is blocked."])
|
||||
self.assertEqual(release.structure_errors(manifest), [])
|
||||
|
||||
def test_evidence_for_other_images_does_not_verify(self) -> None:
|
||||
manifest = release.build_manifest(inputs(evidence_ids={"backend": fake_id("4")}), "t")
|
||||
self.assertEqual(component(manifest, "backend")["verification"]["status"], "not_verified")
|
||||
@@ -458,16 +561,22 @@ class FakeDocker:
|
||||
def __init__(self, tag_holder: list) -> None:
|
||||
self.tag_holder = tag_holder
|
||||
self.built: list = []
|
||||
self.profiles: dict = {}
|
||||
|
||||
def compose_config(self, files, tag, root):
|
||||
def compose_config(self, files, tag, root, profile=None):
|
||||
if files[0].endswith("docker-compose.ml.yml"):
|
||||
return {"services": {"ml": {"image": f"lincodex.invalid/ml:{tag}", "build": {"context": str(ROOT), "dockerfile": "ml/Dockerfile"}}}}
|
||||
return {
|
||||
"services": {
|
||||
"backend": {"image": f"lincodex.invalid/backend:{tag}", "build": {"context": str(ROOT / "backend"), "dockerfile": "Dockerfile"}},
|
||||
"postgres": {"image": "postgres:alpine"},
|
||||
}
|
||||
services = {
|
||||
"backend": {"image": f"lincodex.invalid/backend:{tag}", "build": {"context": str(ROOT / "backend"), "dockerfile": "Dockerfile"}},
|
||||
"postgres": {"image": "postgres:alpine"},
|
||||
}
|
||||
if any(name.endswith("docker-compose.demo.yml") for name in files):
|
||||
services["demo-seed"] = {
|
||||
"image": f"lincodex.invalid/demo-seed:{tag}",
|
||||
"build": {"context": str(ROOT / "backend"), "dockerfile": "Dockerfile.demo-seed"},
|
||||
"profiles": ["demo-seed"],
|
||||
}
|
||||
return {"services": services}
|
||||
|
||||
def inspect_image(self, reference):
|
||||
base = reference.split(":")[0]
|
||||
@@ -476,8 +585,9 @@ class FakeDocker:
|
||||
def pull(self, reference):
|
||||
raise AssertionError("no pull expected")
|
||||
|
||||
def compose_build(self, files, tag, service, build_args, root):
|
||||
def compose_build(self, files, tag, service, build_args, root, profile=None):
|
||||
self.built.append((service, dict(build_args)))
|
||||
self.profiles[service] = (tuple(files), profile)
|
||||
|
||||
|
||||
class BuildStabilityTest(unittest.TestCase):
|
||||
@@ -507,7 +617,7 @@ class BuildStabilityTest(unittest.TestCase):
|
||||
self.assertIsNotNone(error)
|
||||
self.assertIn("changed during the build", str(error))
|
||||
self.assertFalse(written)
|
||||
self.assertEqual([service for service, _ in docker.built], ["backend", "ml"])
|
||||
self.assertEqual([service for service, _ in docker.built], ["backend", "demo-seed", "ml"])
|
||||
|
||||
def test_changed_commit_fails_without_writing(self) -> None:
|
||||
before = release.Source(COMMIT, False, None)
|
||||
@@ -523,6 +633,13 @@ class BuildStabilityTest(unittest.TestCase):
|
||||
self.assertTrue(written)
|
||||
backend_args = dict(docker.built)["backend"]
|
||||
self.assertEqual(backend_args["GO_IMAGE"], f"golang:1.26.8-alpine@{fake_id('2')}")
|
||||
seed_args = dict(docker.built)["demo-seed"]
|
||||
self.assertEqual(seed_args["GO_IMAGE"], f"golang:1.26.8-alpine@{fake_id('2')}")
|
||||
self.assertEqual(seed_args["RUNTIME_IMAGE"], f"gcr.io/distroless/static-debian12:nonroot@{fake_id('2')}")
|
||||
files, profile = docker.profiles["demo-seed"]
|
||||
self.assertEqual(profile, "demo-seed")
|
||||
self.assertEqual(files, release.RELEASE_COMPOSE_FILES)
|
||||
self.assertEqual(docker.profiles["backend"][1], None)
|
||||
|
||||
|
||||
class FingerprintTest(unittest.TestCase):
|
||||
@@ -744,15 +861,45 @@ class ImmutableReleaseTest(unittest.TestCase):
|
||||
|
||||
|
||||
class ReleaseDataTest(unittest.TestCase):
|
||||
def test_default_manifest_records_source_policy_and_missing_bank_seed(self) -> None:
|
||||
def test_default_manifest_records_policy_and_seed_sources_and_missing_bank(self) -> None:
|
||||
manifest = release.build_manifest(inputs(), "t")
|
||||
versions = manifest["data_versions"]
|
||||
self.assertEqual(versions["policy"]["version"], "1")
|
||||
self.assertEqual(versions["policy"]["source_kind"], "bundled_source")
|
||||
self.assertEqual(versions["policy"]["artifacts"][0]["path"], release.POLICY_SOURCE_ARTIFACT)
|
||||
self.assertEqual(versions["bank"]["status"], "unavailable")
|
||||
self.assertEqual(versions["seed"]["status"], "unavailable")
|
||||
self.assertIn("synthetic demo bank is versioned with the seed", versions["bank"]["reason"])
|
||||
seed = versions["seed"]
|
||||
self.assertEqual(seed["status"], "available")
|
||||
self.assertEqual(seed["source_kind"], "bundled_source")
|
||||
self.assertRegex(seed["version"], r"^demo-seed\.[0-9a-f]{12}$")
|
||||
paths = [artifact["path"] for artifact in seed["artifacts"]]
|
||||
self.assertIn("backend/internal/usecase/demoseed/bank.go", paths)
|
||||
self.assertIn("backend/internal/usecase/demoseed/dataset.go", paths)
|
||||
self.assertFalse([path for path in paths if path.endswith("_test.go")])
|
||||
self.assertEqual(paths, sorted(paths))
|
||||
self.assertEqual(manifest["release"]["product_data_status"], "partial")
|
||||
self.assertEqual(release.structure_errors(manifest), [])
|
||||
|
||||
def test_seed_version_follows_the_seed_source(self) -> None:
|
||||
import tempfile
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
package = root / release.SEED_SOURCE_DIR
|
||||
package.mkdir(parents=True)
|
||||
self.assertEqual(release.default_data_versions(root)["seed"]["status"], "unavailable")
|
||||
(package / "dataset.go").write_text("package demoseed\n", encoding="utf-8")
|
||||
(package / "dataset_test.go").write_text("package demoseed\n", encoding="utf-8")
|
||||
first = release.default_data_versions(root)["seed"]
|
||||
self.assertEqual([item["path"] for item in first["artifacts"]], [f"{release.SEED_SOURCE_DIR}/dataset.go"])
|
||||
(package / "dataset_test.go").write_text("package demoseed // changed test\n", encoding="utf-8")
|
||||
self.assertEqual(release.default_data_versions(root)["seed"]["version"], first["version"])
|
||||
(package / "dataset.go").write_text("package demoseed // changed dataset\n", encoding="utf-8")
|
||||
second = release.default_data_versions(root)["seed"]
|
||||
self.assertNotEqual(second["version"], first["version"])
|
||||
with self.assertRaisesRegex(release.ReleaseError, "missing or changed"):
|
||||
release.verify_data_artifacts({"bank": {"status": "unavailable"}, "policy": {"status": "unavailable"}, "seed": first}, root)
|
||||
|
||||
def test_versioned_data_inputs_are_hashed_and_restore_rejects_tampering(self) -> None:
|
||||
import tempfile
|
||||
@@ -798,7 +945,9 @@ class ReleaseDataTest(unittest.TestCase):
|
||||
self.assertTrue(any("does not match the recorded smoke image ID" in error for error in errors), errors)
|
||||
|
||||
|
||||
class RestoreImageTest(unittest.TestCase):
|
||||
class RestoreFixtures:
|
||||
"""Fake Docker and manifest fixtures shared by the restore tests."""
|
||||
|
||||
class Docker:
|
||||
def __init__(self, manifest: dict) -> None:
|
||||
self.manifest = manifest
|
||||
@@ -821,14 +970,19 @@ class RestoreImageTest(unittest.TestCase):
|
||||
if item["name"] == "backend":
|
||||
self.images[image_info["reference"]] = image(fake_id("0"))
|
||||
|
||||
def compose_config(self, files, tag, root=ROOT):
|
||||
return {
|
||||
"services": {
|
||||
"backend": {"image": f"lincodex.invalid/backend:{tag}", "build": {"context": str(root / "backend"), "dockerfile": "Dockerfile"}},
|
||||
"frontend": {"image": f"lincodex.invalid/frontend:{tag}", "build": {"context": str(root / "frontend"), "dockerfile": "Dockerfile"}},
|
||||
"postgres": {"image": "postgres:alpine"},
|
||||
}
|
||||
def compose_config(self, files, tag, root=ROOT, profile=None):
|
||||
services = {
|
||||
"backend": {"image": f"lincodex.invalid/backend:{tag}", "build": {"context": str(root / "backend"), "dockerfile": "Dockerfile"}},
|
||||
"frontend": {"image": f"lincodex.invalid/frontend:{tag}", "build": {"context": str(root / "frontend"), "dockerfile": "Dockerfile"}},
|
||||
"postgres": {"image": "postgres:alpine"},
|
||||
}
|
||||
if profile == "demo-seed":
|
||||
services["demo-seed"] = {
|
||||
"image": f"lincodex.invalid/demo-seed:{tag}",
|
||||
"build": {"context": str(root / "backend"), "dockerfile": "Dockerfile.demo-seed"},
|
||||
"profiles": ["demo-seed"],
|
||||
}
|
||||
return {"services": services}
|
||||
|
||||
def inspect_image(self, reference: str):
|
||||
self.lookups.append(reference)
|
||||
@@ -867,8 +1021,8 @@ class RestoreImageTest(unittest.TestCase):
|
||||
def manifest(self) -> dict:
|
||||
return release.build_manifest(inputs(), "t", release_id="stage-restore")
|
||||
|
||||
def write_restore_fixture(self, root: Path) -> tuple[Path, Path, dict]:
|
||||
for name in release.CORE_COMPOSE_FILES:
|
||||
def write_restore_fixture(self, root: Path, compose_names: tuple = release.CORE_COMPOSE_FILES) -> tuple[Path, Path, dict]:
|
||||
for name in compose_names:
|
||||
path = root / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(f"# {Path(name).name}\n", encoding="utf-8")
|
||||
@@ -885,7 +1039,7 @@ class RestoreImageTest(unittest.TestCase):
|
||||
data_source = root / "data/release.json"
|
||||
data_source.write_text(json.dumps(descriptor), encoding="utf-8")
|
||||
data_versions = release.read_data_versions("data/release.json", root)
|
||||
compose_files = {name: release.file_digest(root / name) for name in release.CORE_COMPOSE_FILES}
|
||||
compose_files = {name: release.file_digest(root / name) for name in compose_names}
|
||||
manifest = release.build_manifest(
|
||||
inputs(),
|
||||
"2026-10-07T00:00:00Z",
|
||||
@@ -911,6 +1065,8 @@ class RestoreImageTest(unittest.TestCase):
|
||||
manifest=str(manifest_path),
|
||||
)
|
||||
|
||||
|
||||
class RestoreImageTest(RestoreFixtures, unittest.TestCase):
|
||||
def test_restore_uses_image_ids_and_digest_references_not_moving_tags(self) -> None:
|
||||
manifest = self.manifest()
|
||||
docker = self.Docker(manifest)
|
||||
@@ -986,5 +1142,105 @@ class RestoreImageTest(unittest.TestCase):
|
||||
self.assertEqual(docker.restore_actions, [])
|
||||
|
||||
|
||||
class DemoRestoreTest(RestoreFixtures, unittest.TestCase):
|
||||
"""The demo stand restores the same delivery from exact image IDs."""
|
||||
|
||||
def demo_fixture(self, root: Path) -> tuple[Path, dict]:
|
||||
manifest_path, _, manifest = self.write_restore_fixture(root, release.RELEASE_COMPOSE_FILES)
|
||||
self.assertEqual(manifest["restore"]["demo"]["status"], "available", manifest["restore"]["demo"]["reasons"])
|
||||
return manifest_path, manifest
|
||||
|
||||
def override_args(self, manifest_path: Path, directory: Path):
|
||||
from argparse import Namespace
|
||||
|
||||
return Namespace(manifest=str(manifest_path), output_dir=str(directory))
|
||||
|
||||
def test_override_pins_core_and_demo_seed_to_exact_images(self) -> None:
|
||||
import tempfile
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
manifest_path, manifest = self.demo_fixture(root)
|
||||
output = root / "override"
|
||||
output.mkdir()
|
||||
docker = self.Docker(manifest)
|
||||
docker.images.pop("lincodex.invalid/release/demo-seed:restore-case")
|
||||
self.assertEqual(release.command_demo_override(self.override_args(manifest_path, output), docker, root), 0)
|
||||
text = (output / "release-restore.yml").read_text(encoding="utf-8")
|
||||
for name, reference in (
|
||||
("backend", BACKEND_ID),
|
||||
("frontend", FRONTEND_ID),
|
||||
("postgres", f"docker.io/library/postgres@{POSTGRES_ID}"),
|
||||
("demo-seed", SEED_ID),
|
||||
):
|
||||
with self.subTest(service=name):
|
||||
self.assertIn(f" {name}:\n image: {json.dumps(reference)}\n pull_policy: never", text)
|
||||
self.assertEqual(docker.images["lincodex.invalid/release/demo-seed:restore-case"]["Id"], SEED_ID)
|
||||
self.assertNotIn(component(manifest, "demo-seed")["image"]["reference"], docker.lookups)
|
||||
|
||||
def test_override_refuses_a_missing_seed_image_or_changed_demo_overlay(self) -> None:
|
||||
import tempfile
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
manifest_path, manifest = self.demo_fixture(root)
|
||||
output = root / "override"
|
||||
output.mkdir()
|
||||
docker = self.Docker(manifest)
|
||||
docker.images.pop(SEED_ID)
|
||||
with self.assertRaisesRegex(release.ReleaseError, "Exact local image"):
|
||||
release.command_demo_override(self.override_args(manifest_path, output), docker, root)
|
||||
(root / release.DEMO_COMPOSE_FILES[0]).write_text("# changed\n", encoding="utf-8")
|
||||
with self.assertRaisesRegex(release.ReleaseError, "differs from the immutable release manifest"):
|
||||
release.command_demo_override(self.override_args(manifest_path, output), self.Docker(manifest), root)
|
||||
self.assertEqual(list(output.iterdir()), [])
|
||||
|
||||
def test_override_refuses_a_manifest_without_a_demo_restore(self) -> None:
|
||||
import tempfile
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
manifest_path, _, manifest = self.write_restore_fixture(root)
|
||||
self.assertEqual(manifest["restore"]["demo"]["status"], "blocked")
|
||||
output = root / "override"
|
||||
output.mkdir()
|
||||
with self.assertRaisesRegex(release.ReleaseError, "Demo stand restore is blocked"):
|
||||
release.command_demo_override(self.override_args(manifest_path, output), self.Docker(manifest), root)
|
||||
del manifest["restore"]["demo"]
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
with self.assertRaisesRegex(release.ReleaseError, "no demo stand restore entry"):
|
||||
release.command_demo_override(self.override_args(manifest_path, output), self.Docker(manifest), root)
|
||||
self.assertEqual(list(output.iterdir()), [])
|
||||
|
||||
def test_publication_retains_the_demo_seed_image(self) -> None:
|
||||
manifest = release.build_manifest(inputs(), "t", release_id="stage-demo")
|
||||
docker = self.Docker(manifest)
|
||||
for item in manifest["components"]:
|
||||
retention = (item.get("image") or {}).get("retention_reference")
|
||||
if retention:
|
||||
docker.images.pop(retention, None)
|
||||
release.prepare_manifest_images(manifest, docker)
|
||||
self.assertEqual(docker.images["lincodex.invalid/release/demo-seed:stage-demo"]["Id"], SEED_ID)
|
||||
self.assertEqual(manifest["restore"]["demo"]["status"], "available")
|
||||
|
||||
def test_manifest_without_demo_entry_stays_valid_and_demo_entry_is_checked(self) -> None:
|
||||
manifest = release.build_manifest(inputs(), "t")
|
||||
legacy = json.loads(json.dumps(manifest))
|
||||
del legacy["restore"]["demo"]
|
||||
for name in release.DEMO_COMPOSE_FILES:
|
||||
del legacy["configuration"]["compose_files"][name]
|
||||
self.assertEqual(release.structure_errors(legacy), [])
|
||||
|
||||
broken = json.loads(json.dumps(manifest))
|
||||
del broken["configuration"]["compose_files"][release.DEMO_COMPOSE_FILES[1]]
|
||||
self.assertIn("Compose file digest inventory is incomplete", release.structure_errors(broken))
|
||||
broken = json.loads(json.dumps(manifest))
|
||||
broken["restore"]["demo"]["command"] = "make -C deploy demo-seed DEMO_MODE=isolated"
|
||||
self.assertIn("demo restore status, command, or reasons are malformed", release.structure_errors(broken))
|
||||
broken = json.loads(json.dumps(manifest))
|
||||
component(broken, "demo-seed")["image"]["restore_reference"] = "lincodex.invalid/demo-seed:latest"
|
||||
self.assertIn("built demo component demo-seed is not pinned to its exact image ID", release.structure_errors(broken))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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
@@ -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
@@ -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.
|
||||
|
||||
|
||||
@@ -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
@@ -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
@@ -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.
|
||||
|
||||
|
||||
Reference in new issue
Block a user