feat(deploy): preserve immutable release manifests and restore pinned images

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 11:24:14 +03:00
1 parent 4ee53d9a74
commit 7df521bd89
7 files changed
+1417 -110

No files matched your search

+16 -11
View File
@@ -24,8 +24,14 @@ RELEASE := PYTHONDONTWRITEBYTECODE=1 python3 "$(RELEASE_SCRIPT)"
RELEASE_PULL ?= missing
# Compose project whose running containers release-manifest-verify compares.
RELEASE_VERIFY_PROJECT ?= $(APP_PROJECT)
# Optional manifest path for release-manifest-verify; empty means the current tag.
# Optional manifest path for release-manifest-check, verify, and restore.
# Empty selects RELEASE_ID when set, otherwise the current commit-based ID.
RELEASE_MANIFEST ?=
# Optional immutable delivery ID; empty keeps the current commit-based ID.
RELEASE_ID ?=
# Optional repository-relative manifest describing bank, policy, and seed inputs.
RELEASE_DATA_MANIFEST ?=
RELEASE_MANIFEST_ARG = $(if $(strip $(RELEASE_MANIFEST)),--manifest "$(RELEASE_MANIFEST)",$(if $(strip $(RELEASE_ID)),--manifest "deploy/release/$(RELEASE_ID)/manifest.json",))
# Recursive on purpose: git is asked only by the targets that use the tag. The
# project-specific name keeps a generic RELEASE_TAG from enabling release mode.
LINCODEX_RELEASE_TAG ?= $(shell PYTHONDONTWRITEBYTECODE=1 python3 "$(RELEASE_SCRIPT)" tag)
@@ -137,23 +143,22 @@ release-smoke: ## Run the smoke against the release images and record passing ev
release-e2e: ## Run the Playwright suite against the release images and record passing evidence
@LINCODEX_RELEASE_TAG="$(LINCODEX_RELEASE_TAG)" bash scripts/e2e.sh
release-manifest: ## Write deploy/release/<tag>/manifest.json from local images and recorded evidence
@$(RELEASE) manifest
release-manifest: ## Publish an immutable deploy/release/<id>/manifest.json from local images and data versions
@$(RELEASE) manifest $(if $(strip $(RELEASE_ID)),--release-id "$(RELEASE_ID)",) $(if $(strip $(RELEASE_DATA_MANIFEST)),--data-manifest "$(RELEASE_DATA_MANIFEST)",)
release-manifest-verify: ## Compare running containers of RELEASE_VERIFY_PROJECT with the manifest (or RELEASE_MANIFEST)
@$(RELEASE) verify --project "$(RELEASE_VERIFY_PROJECT)" $(if $(RELEASE_MANIFEST),--manifest "$(RELEASE_MANIFEST)")
@$(RELEASE) verify --project "$(RELEASE_VERIFY_PROJECT)" $(RELEASE_MANIFEST_ARG)
release-manifest-check: ## Check the manifest structure and scan it for secrets and machine data
@$(RELEASE) check
@$(RELEASE) check $(RELEASE_MANIFEST_ARG)
release-up: ## Start the core stack from the release images without building or pulling
release-up: ## Restore the core stack from an immutable release manifest without building or pulling
@test -f "$(ENV_FILE)" || { printf 'Missing %s. Copy .env.example to .env and replace the placeholder passwords.\n' "$(ENV_FILE)" >&2; exit 2; }
@$(RELEASE) require-images --tag "$(LINCODEX_RELEASE_TAG)"
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG="$(LINCODEX_RELEASE_TAG)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" up -d --no-build --pull never --wait --wait-timeout 180
@$(RELEASE) restore --action up --project "$(APP_PROJECT)" --env-file "$(ENV_FILE)" $(RELEASE_MANIFEST_ARG)
release-down: ## Stop the core stack started by release-up and keep named volumes
release-down: ## Stop the release project selected by the immutable manifest and keep named volumes
@test -f "$(ENV_FILE)" || { printf 'Missing %s.\n' "$(ENV_FILE)" >&2; exit 2; }
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG="$(LINCODEX_RELEASE_TAG)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" down
@$(RELEASE) restore --action down --project "$(APP_PROJECT)" --env-file "$(ENV_FILE)" $(RELEASE_MANIFEST_ARG)
release-clean: ## Remove the local lincodex.invalid/* release images; keep deploy/release files
release-clean: ## Remove local release image references not retained by an immutable manifest
@$(RELEASE) clean-images
File diff suppressed because it is too large. Load diff
+390 -33
View File
@@ -9,6 +9,7 @@ image fails make -C deploy check.
from __future__ import annotations
import importlib.util
import hashlib
import json
import sys
import unittest
@@ -27,6 +28,16 @@ COMMIT = "0123456789abcdef0123456789abcdef01234567"
FAKE_PASSWORD = "fake-password-7f3c9a"
def fake_id(char: str) -> str:
return "sha256:" + char * 64
BACKEND_ID = fake_id("b")
FRONTEND_ID = fake_id("f")
POSTGRES_ID = fake_id("e")
ML_ID = fake_id("c")
def image(image_id: str, *, env: list[str] | None = None, digests: list[str] | None = None) -> dict:
return {
"Id": image_id,
@@ -67,12 +78,12 @@ def evidence_doc(check: str, source, ids: dict) -> dict:
}
CURRENT_IDS = {"backend": "sha256:b1", "frontend": "sha256:f1", "postgres": "sha256:e1"}
CURRENT_IDS = {"backend": BACKEND_ID, "frontend": FRONTEND_ID, "postgres": POSTGRES_ID}
def all_files() -> dict:
files = {name: "sha256:00" for name in release.LOCKFILES}
files.update({"backend/Dockerfile": "sha256:01", "frontend/Dockerfile": "sha256:02", "ml/Dockerfile": "sha256:03"})
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.update({".node-version": "26.10.0", ".python-version": "3.14.8"})
return files
@@ -91,12 +102,12 @@ def inputs(
source = release.Source(COMMIT, dirty, "git-tree:" + "ab" * 20 if dirty else None)
tag = source.tag
images = {
f"lincodex.invalid/backend:{tag}": image("sha256:b1"),
f"lincodex.invalid/frontend:{tag}": image("sha256:f1", env=["NGINX_VERSION=1.29.0"]),
f"lincodex.invalid/backend:{tag}": image(BACKEND_ID),
f"lincodex.invalid/frontend:{tag}": image(FRONTEND_ID, env=["NGINX_VERSION=1.29.0"]),
"postgres:alpine": image(
"sha256:e1", env=["PG_VERSION=18.6"], digests=["postgres@sha256:e1"] if postgres_digests is None else postgres_digests
POSTGRES_ID, env=["PG_VERSION=18.6"], digests=[f"postgres@{POSTGRES_ID}"] if postgres_digests is None else postgres_digests
),
f"lincodex.invalid/ml:{tag}": image("sha256:c1", env=["PYTHON_VERSION=3.14.8"]),
f"lincodex.invalid/ml:{tag}": image(ML_ID, env=["PYTHON_VERSION=3.14.8"]),
"prom/prometheus:latest": None,
}
build = {
@@ -105,21 +116,21 @@ def inputs(
"source_fingerprint": source.fingerprint,
"services": {
"backend": {
"image_id": "sha256:b1",
"build_args": {"GO_IMAGE": "golang:1.26.8-alpine@sha256:g1"},
"image_id": BACKEND_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": "sha256:g1", "versions": {"GOLANG_VERSION": "1.26.8"}}
{"arg": "GO_IMAGE", "reference": "golang:1.26.8-alpine", "digest": fake_id("a"), "versions": {"GOLANG_VERSION": "1.26.8"}}
],
},
"frontend": {
"image_id": "sha256:f1",
"image_id": FRONTEND_ID,
"build_args": {},
"base_images": [{"arg": "NODE_IMAGE", "reference": "node:alpine", "digest": "sha256:n1", "versions": {"NODE_VERSION": node_version}}],
"base_images": [{"arg": "NODE_IMAGE", "reference": "node:alpine", "digest": fake_id("d"), "versions": {"NODE_VERSION": node_version}}],
},
"ml": {
"image_id": "sha256:c1",
"image_id": ML_ID,
"build_args": {},
"base_images": [{"arg": "PYTHON_IMAGE", "reference": "python:alpine", "digest": "sha256:y1", "versions": {"PYTHON_VERSION": python_version}}],
"base_images": [{"arg": "PYTHON_IMAGE", "reference": "python:alpine", "digest": fake_id("9"), "versions": {"PYTHON_VERSION": python_version}}],
},
},
}
@@ -203,16 +214,16 @@ class ManifestTest(unittest.TestCase):
manifest = release.build_manifest(inputs(), "2026-10-06T00:00:00Z")
self.assertEqual(manifest["release"]["status"], "verified", manifest["release"]["reasons"])
self.assertEqual(component(manifest, "backend")["verification"], {"status": "verified", "checks": ["e2e", "smoke"]})
self.assertEqual(component(manifest, "postgres")["image"]["repo_digest"], "sha256:e1")
self.assertEqual(component(manifest, "postgres")["image"]["repo_digest"], POSTGRES_ID)
self.assertEqual(component(manifest, "postgres")["image"]["versions"], {"PG_VERSION": "18.6"})
self.assertEqual(manifest["toolchains"]["go"]["binary"], "go1.26.8")
self.assertEqual(manifest["toolchains"]["go"]["build_image_version"], "1.26.8")
self.assertTrue(manifest["toolchains"]["node"]["matches_version_file"])
self.assertEqual(component(manifest, "postgres")["image"]["repo_digests"], ["postgres@sha256:e1"])
self.assertEqual(component(manifest, "postgres")["image"]["repo_digests"], [f"postgres@{POSTGRES_ID}"])
self.assertEqual(release.structure_errors(manifest), [])
def test_built_images_do_not_inherit_base_labels_as_versions(self) -> None:
info = image("sha256:f1", env=["NGINX_VERSION=1.29.0"], digests=["x@sha256:f1"])
info = image(FRONTEND_ID, env=["NGINX_VERSION=1.29.0"], digests=[f"x@{FRONTEND_ID}"])
info["Config"]["Labels"]["org.opencontainers.image.version"] = "base-1.0"
self.assertEqual(release.image_record(info, "x", built=True)["versions"], {"NGINX_VERSION": "1.29.0"})
self.assertIsNone(release.image_record(info, "x", built=True)["repo_digest"])
@@ -230,7 +241,7 @@ class ManifestTest(unittest.TestCase):
self.assertIsNone(component(manifest, name)["image"])
def test_evidence_for_other_images_does_not_verify(self) -> None:
manifest = release.build_manifest(inputs(evidence_ids={"backend": "sha256:0d"}), "t")
manifest = release.build_manifest(inputs(evidence_ids={"backend": fake_id("4")}), "t")
self.assertEqual(component(manifest, "backend")["verification"]["status"], "not_verified")
self.assertEqual(component(manifest, "frontend")["verification"]["status"], "not_verified")
self.assertEqual(manifest["release"]["status"], "unverified")
@@ -327,13 +338,24 @@ class ScannerTest(unittest.TestCase):
class ReferenceTest(unittest.TestCase):
def test_repo_digest_matches_normalized_repository(self) -> None:
info = {"RepoDigests": ["other@sha256:1", "postgres@sha256:2"]}
self.assertEqual(release.repo_digest(info, "postgres:alpine"), "sha256:2")
self.assertEqual(release.repo_digest(info, "docker.io/library/postgres:alpine"), "sha256:2")
info = {"RepoDigests": ["gcr.io/distroless/static-debian12@sha256:3"]}
self.assertEqual(release.repo_digest(info, "gcr.io/distroless/static-debian12:nonroot"), "sha256:3")
info = {"RepoDigests": [f"other@{fake_id('1')}", f"postgres@{fake_id('2')}"]}
self.assertEqual(release.repo_digest(info, "postgres:alpine"), fake_id("2"))
self.assertEqual(release.repo_digest(info, "docker.io/library/postgres:alpine"), fake_id("2"))
info = {"RepoDigests": [f"gcr.io/distroless/static-debian12@{fake_id('3')}"]}
self.assertEqual(release.repo_digest(info, "gcr.io/distroless/static-debian12:nonroot"), fake_id("3"))
self.assertIsNone(release.repo_digest({"RepoDigests": []}, "redis:alpine"))
def test_manifest_rejects_short_image_ids_and_repository_digests(self) -> None:
manifest = release.build_manifest(inputs(), "t")
component(manifest, "backend")["image"]["image_id"] = "sha256:b1"
errors = release.structure_errors(manifest)
self.assertIn("component backend image ID is invalid", errors)
manifest = release.build_manifest(inputs(), "t")
component(manifest, "postgres")["image"]["repo_digest"] = "sha256:e1"
errors = release.structure_errors(manifest)
self.assertTrue(any("pulled core component postgres has no repository digest" in error for error in errors), errors)
def test_release_tag_is_validated_before_it_becomes_a_path(self) -> None:
with self.assertRaises(release.ReleaseError):
release.release_dir("../../etc")
@@ -404,7 +426,7 @@ class ReleaseRequirementsTest(unittest.TestCase):
def test_e2e_on_other_images_does_not_verify_the_release(self) -> None:
data = inputs()
data.evidence["e2e"] = evidence_doc("e2e", data.source, {**CURRENT_IDS, "backend": "sha256:0d"})
data.evidence["e2e"] = evidence_doc("e2e", data.source, {**CURRENT_IDS, "backend": fake_id("4")})
manifest = release.build_manifest(data, "t")
self.assertEqual(manifest["release"]["status"], "unverified")
self.assertEqual(component(manifest, "backend")["verification"]["checks"], ["smoke"])
@@ -449,7 +471,7 @@ class FakeDocker:
def inspect_image(self, reference):
base = reference.split(":")[0]
return image("sha256:" + "1" * 8, digests=[f"{base}@sha256:{'2' * 8}"])
return image(fake_id("1"), digests=[f"{base}@{fake_id('2')}"])
def pull(self, reference):
raise AssertionError("no pull expected")
@@ -500,7 +522,7 @@ class BuildStabilityTest(unittest.TestCase):
self.assertIsNone(error)
self.assertTrue(written)
backend_args = dict(docker.built)["backend"]
self.assertEqual(backend_args["GO_IMAGE"], "golang:1.26.8-alpine@sha256:" + "2" * 8)
self.assertEqual(backend_args["GO_IMAGE"], f"golang:1.26.8-alpine@{fake_id('2')}")
class FingerprintTest(unittest.TestCase):
@@ -576,9 +598,9 @@ class VerifyTest(unittest.TestCase):
def test_matching_project_passes(self) -> None:
tag = release.Source(COMMIT, False, None).tag
running = {
"backend": {"reference": f"lincodex.invalid/backend:{tag}", "image_id": "sha256:b1"},
"frontend": {"reference": f"lincodex.invalid/frontend:{tag}", "image_id": "sha256:f1"},
"postgres": {"reference": "postgres:alpine", "image_id": "sha256:e1"},
"backend": {"reference": f"lincodex.invalid/backend:{tag}", "image_id": BACKEND_ID},
"frontend": {"reference": f"lincodex.invalid/frontend:{tag}", "image_id": FRONTEND_ID},
"postgres": {"reference": "postgres:alpine", "image_id": POSTGRES_ID},
}
ok, lines = release.compare_running(self.manifest(), running)
self.assertTrue(ok, lines)
@@ -586,9 +608,9 @@ class VerifyTest(unittest.TestCase):
def test_changed_digest_missing_or_unknown_service_fails(self) -> None:
tag = release.Source(COMMIT, False, None).tag
running = {
"backend": {"reference": f"lincodex.invalid/backend:{tag}", "image_id": "sha256:other"},
"frontend": {"reference": f"lincodex.invalid/frontend:{tag}", "image_id": "sha256:f1"},
"extra": {"reference": "busybox:latest", "image_id": "sha256:x"},
"backend": {"reference": f"lincodex.invalid/backend:{tag}", "image_id": fake_id("8")},
"frontend": {"reference": f"lincodex.invalid/frontend:{tag}", "image_id": FRONTEND_ID},
"extra": {"reference": "busybox:latest", "image_id": fake_id("7")},
}
ok, lines = release.compare_running(self.manifest(), running)
self.assertFalse(ok)
@@ -600,7 +622,7 @@ class VerifyTest(unittest.TestCase):
def test_running_services_skip_one_off_and_stopped_containers(self) -> None:
def container(service: str, running: bool = True, oneoff: str = "False") -> dict:
return {
"Image": f"sha256:{service}",
"Image": fake_id(service),
"Config": {"Image": f"{service}:x", "Labels": {"com.docker.compose.service": service, "com.docker.compose.oneoff": oneoff}},
"State": {"Running": running},
}
@@ -609,5 +631,340 @@ class VerifyTest(unittest.TestCase):
self.assertEqual(sorted(found), ["a"])
class ImmutableReleaseTest(unittest.TestCase):
def test_release_ids_are_bounded_slugs(self) -> None:
for release_id in ("..", "../outside", "a/b", " space", "a" * 65):
with self.subTest(release_id=release_id), self.assertRaises(release.ReleaseError):
release.release_artifact_dir(release_id, ROOT)
self.assertEqual(release.release_artifact_dir("stage-2.1", ROOT).name, "stage-2.1")
def test_atomic_publication_preserves_bytes_and_mtime_on_idempotent_rerun(self) -> None:
import tempfile
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
path = root / "deploy/release/stage-one/manifest.json"
document = {"release": {"id": "stage-one"}, "generated_at": "first"}
self.assertTrue(release.write_json_immutable(path, document, root))
original = path.read_bytes()
original_mtime = path.stat().st_mtime_ns
rerun = {**document, "generated_at": "later"}
self.assertFalse(release.write_json_immutable(path, rerun, root))
self.assertEqual(path.read_bytes(), original)
self.assertEqual(path.stat().st_mtime_ns, original_mtime)
with self.assertRaises(release.ReleaseError):
release.write_json_immutable(path, {"release": {"id": "stage-one", "data": 2}}, root)
self.assertEqual(path.read_bytes(), original)
def test_concurrent_create_if_absent_never_replaces_the_winner(self) -> None:
import tempfile
import threading
from concurrent.futures import ThreadPoolExecutor
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
path = root / "deploy/release/stage-one/manifest.json"
documents = (
{"release": {"id": "stage-one", "source": "first"}},
{"release": {"id": "stage-one", "source": "second"}},
)
barrier = threading.Barrier(2)
def publish(document: dict) -> str:
barrier.wait()
try:
return "created" if release.write_json_immutable(path, document, root) else "same"
except release.ReleaseError:
return "collision"
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(publish, documents))
self.assertCountEqual(results, ["created", "collision"])
self.assertIn(json.loads(path.read_text(encoding="utf-8")), documents)
def test_command_reread_is_unchanged_and_changed_data_needs_a_new_id(self) -> None:
import tempfile
from argparse import Namespace
from unittest import mock
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
descriptor = root / "data/release.json"
descriptor.parent.mkdir()
def write_descriptor(reason: str) -> None:
document = {
"schema": release.DATA_SCHEMA,
**{
name: {"status": "unavailable", "reason": reason}
for name in release.DATA_COMPONENTS
},
}
descriptor.write_text(json.dumps(document), encoding="utf-8")
data = inputs()
args = Namespace(release_id="stage-one", data_manifest="data/release.json")
write_descriptor("No accepted snapshot.")
with mock.patch.object(release, "collect_inputs", return_value=data), mock.patch.object(
release, "prepare_manifest_images"
):
self.assertEqual(release.command_manifest(args, object(), root), 0)
path = root / "deploy/release/stage-one/manifest.json"
original = path.read_bytes()
mtime = path.stat().st_mtime_ns
self.assertEqual(release.command_manifest(args, object(), root), 0)
self.assertEqual(path.read_bytes(), original)
self.assertEqual(path.stat().st_mtime_ns, mtime)
write_descriptor("A newer seed was supplied.")
with self.assertRaises(release.ReleaseError):
release.command_manifest(args, object(), root)
args.release_id = "stage-two"
self.assertEqual(release.command_manifest(args, object(), root), 0)
self.assertEqual(path.read_bytes(), original)
class ReleaseDataTest(unittest.TestCase):
def test_default_manifest_records_source_policy_and_missing_bank_seed(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.assertEqual(manifest["release"]["product_data_status"], "partial")
def test_versioned_data_inputs_are_hashed_and_restore_rejects_tampering(self) -> None:
import tempfile
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
artifact = root / "data/policy.json"
artifact.parent.mkdir()
artifact.write_text('{"policy":"v1"}\n', encoding="utf-8")
descriptor = {
"schema": release.DATA_SCHEMA,
**{
name: {"status": "available", "version": f"{name}-v1", "artifacts": [{"path": "data/policy.json"}]}
for name in release.DATA_COMPONENTS
},
}
source = root / "data/release.json"
source.write_text(json.dumps(descriptor), encoding="utf-8")
versions = release.read_data_versions("data/release.json", root)
self.assertEqual(versions["policy"]["source_kind"], "snapshot")
self.assertEqual(versions["policy"]["artifacts"][0]["sha256"], "sha256:" + hashlib.sha256(artifact.read_bytes()).hexdigest())
release.verify_data_artifacts(versions, root)
artifact.write_text('{"policy":"changed"}\n', encoding="utf-8")
with self.assertRaisesRegex(release.ReleaseError, "missing or changed"):
release.verify_data_artifacts(versions, root)
artifact.unlink()
with self.assertRaises(release.ReleaseError):
release.verify_data_artifacts(versions, root)
def test_data_inputs_reject_traversal_and_environment_paths(self) -> None:
import tempfile
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
for path in ("../outside.json", ".env", "backend/.env.local"):
with self.subTest(path=path), self.assertRaises(release.ReleaseError):
release.project_file(path, root, maximum_size=1024, label="test")
def test_verified_component_must_match_each_check_fake_id(self) -> None:
manifest = release.build_manifest(inputs(), "t")
component(manifest, "backend")["image"]["image_id"] = fake_id("6")
errors = release.structure_errors(manifest)
self.assertTrue(any("does not match the recorded smoke image ID" in error for error in errors), errors)
class RestoreImageTest(unittest.TestCase):
class Docker:
def __init__(self, manifest: dict) -> None:
self.manifest = manifest
self.lookups: list[str] = []
self.restore_config_calls = 0
self.restore_actions: list[str] = []
self.images: dict[str, dict] = {}
for item in manifest["components"]:
image_info = item.get("image")
if not item.get("present") and not isinstance(image_info, dict):
continue
if not isinstance(image_info, dict) or not image_info.get("present"):
continue
image_id = image_info["image_id"]
metadata = image(image_id, digests=image_info.get("repo_digests", []))
self.images[image_id] = metadata
for reference in (image_info.get("restore_reference"), image_info.get("retention_reference")):
if reference:
self.images[reference] = metadata
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 inspect_image(self, reference: str):
self.lookups.append(reference)
return self.images.get(reference)
def tag_image(self, image_id: str, reference: str) -> None:
self.images[reference] = self.images[image_id]
def compose_restore_config(self, project, env_file, tag, override, root=ROOT):
self.restore_config_calls += 1
return {
"services": {
item["name"]: {"image": item["image"]["restore_reference"]}
for item in self.manifest["components"]
if item.get("group") == "core"
}
}
def compose_restore(self, action, project, env_file, tag, override, root=ROOT):
self.restore_actions.append(action)
def project_containers(self, project):
return [
{
"Image": item["image"]["image_id"],
"Config": {
"Image": item["image"]["restore_reference"],
"Labels": {"com.docker.compose.service": item["name"]},
},
"State": {"Running": True},
}
for item in self.manifest["components"]
if item.get("group") == "core"
]
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:
path = root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(f"# {Path(name).name}\n", encoding="utf-8")
artifact = root / "data/state.json"
artifact.parent.mkdir(parents=True, exist_ok=True)
artifact.write_text('{"release":"v1"}\n', encoding="utf-8")
descriptor = {
"schema": release.DATA_SCHEMA,
**{
name: {"status": "available", "version": f"{name}-v1", "artifacts": [{"path": "data/state.json"}]}
for name in release.DATA_COMPONENTS
},
}
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}
manifest = release.build_manifest(
inputs(),
"2026-10-07T00:00:00Z",
"restore-case",
data_versions,
compose_files,
root,
)
manifest_path = root / "deploy/release/restore-case/manifest.json"
manifest_path.parent.mkdir(parents=True)
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
env_file = root / "restore.env"
env_file.write_text("SYNTHETIC=1\n", encoding="utf-8")
return manifest_path, env_file, manifest
def restore_args(self, manifest_path: Path, env_file: Path):
from argparse import Namespace
return Namespace(
action="up",
project="release-restore-test",
env_file=str(env_file),
manifest=str(manifest_path),
)
def test_restore_uses_image_ids_and_digest_references_not_moving_tags(self) -> None:
manifest = self.manifest()
docker = self.Docker(manifest)
resolved = release.restore_images(manifest, docker, ROOT)
self.assertEqual(resolved["backend"], BACKEND_ID)
self.assertEqual(resolved["frontend"], FRONTEND_ID)
self.assertEqual(resolved["postgres"], f"docker.io/library/postgres@{POSTGRES_ID}")
self.assertNotIn(component(manifest, "backend")["image"]["reference"], docker.lookups)
def test_missing_exact_image_and_digest_mismatch_fail_before_compose(self) -> None:
manifest = self.manifest()
docker = self.Docker(manifest)
docker.images.pop(BACKEND_ID)
with self.assertRaisesRegex(release.ReleaseError, "Exact local image"):
release.restore_images(manifest, docker, ROOT)
manifest = self.manifest()
docker = self.Docker(manifest)
docker.images[component(manifest, "postgres")["image"]["restore_reference"]] = image(
fake_id("5"), digests=[f"postgres@{POSTGRES_ID}"]
)
with self.assertRaisesRegex(release.ReleaseError, "different image ID"):
release.restore_images(manifest, docker, ROOT)
def test_compose_override_uses_exact_ids_and_mode_0600(self) -> None:
import os
import tempfile
with tempfile.TemporaryDirectory() as directory:
override = release.write_compose_override(Path(directory), {"backend": fake_id("a")})
self.assertIn('image: "sha256:' + "a" * 64, override.read_text(encoding="utf-8"))
self.assertIn("pull_policy: never", override.read_text(encoding="utf-8"))
self.assertEqual(os.stat(override).st_mode & 0o777, 0o600)
down_directory = Path(directory) / "down"
down_directory.mkdir()
down_override = release.write_compose_override(down_directory, {})
self.assertEqual(down_override.read_text(encoding="utf-8"), "services: {}\n")
def test_tampered_data_and_component_mismatch_fail_before_compose_start(self) -> None:
import tempfile
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
manifest_path, env_file, manifest = self.write_restore_fixture(root)
artifact = root / "data/state.json"
artifact.write_text('{"release":"changed"}\n', encoding="utf-8")
docker = self.Docker(manifest)
with self.assertRaisesRegex(release.ReleaseError, "missing or changed"):
release.command_restore(self.restore_args(manifest_path, env_file), docker, root)
self.assertEqual(docker.restore_config_calls, 0)
self.assertEqual(docker.restore_actions, [])
artifact.write_text('{"release":"v1"}\n', encoding="utf-8")
component(manifest, "backend")["image"]["image_id"] = fake_id("6")
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
docker = self.Docker(manifest)
with self.assertRaisesRegex(release.ReleaseError, "verified component backend"):
release.command_restore(self.restore_args(manifest_path, env_file), docker, root)
self.assertEqual(docker.restore_config_calls, 0)
self.assertEqual(docker.restore_actions, [])
def test_missing_exact_image_fails_before_compose_start(self) -> None:
import tempfile
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
manifest_path, env_file, manifest = self.write_restore_fixture(root)
docker = self.Docker(manifest)
docker.images.pop(BACKEND_ID)
with self.assertRaisesRegex(release.ReleaseError, "Exact local image"):
release.command_restore(self.restore_args(manifest_path, env_file), docker, root)
self.assertEqual(docker.restore_config_calls, 0)
self.assertEqual(docker.restore_actions, [])
if __name__ == "__main__":
unittest.main()
+4
View File
@@ -461,6 +461,10 @@ Referencing a version (planned): tables that record a decision built under a pol
Test fixtures use their own values. Since `product` is the only family, the integration tests give every case its own database, and no fixture stands in for the demo policy.
## 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.
## Repository map and package purpose
```text
+19 -14
View File
@@ -540,36 +540,41 @@ The backend builds with Go 1.26.8; its runtime image is selected in backend/Dock
## Release manifest
A release manifest records what a verified local release consists of: the commit, the toolchain versions, the lockfile hashes, the image of every service with its actual digest, and which components a check really ran. Moving `latest` and `alpine` tags stay in Compose and in the Dockerfiles by agreement; the manifest pins what they resolved to at release time. The interface is `make -C deploy release-manifest`; the other `release-*` targets prepare its inputs and check its result:
A release manifest records the source, toolchains, lockfile hashes, Compose file hashes, image IDs and digests, and versioned data inputs for one local delivery. Compose may keep moving `latest` and `alpine` tags; restoring a release uses the image IDs or repository digests recorded in its manifest, never a fresh lookup of those tags. The default release ID is the commit-based tag. Use a short `RELEASE_ID` when the same source has more than one delivery or when its data or stage changes:
make -C deploy release-build
make -C deploy release-smoke
make -C deploy release-e2e
make -C deploy release-manifest
make -C deploy release-manifest-check
make -C deploy release-manifest RELEASE_ID=demo-stage-1
make -C deploy release-manifest-check 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-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 only local images, the build record, and the evidence; it pulls nothing. A missing image is listed as not present. Evidence or a build record that is malformed or was recorded for another tag, commit, or working tree state is not used; the manifest lists the rejected evidence under `rejected_checks`.
- `release-manifest-check` checks the structure of the manifest and scans it for secrets and machine data.
- `release-up` and `release-down` run the core stack from the release images with `ENV_FILE` and `APP_PROJECT`, without building or pulling. `make -C deploy release-manifest-verify RELEASE_VERIFY_PROJECT=<project>` compares every running container of that Compose project with the manifest of the current tag, or with `RELEASE_MANIFEST=<path>`, by image ID. It prints the release status and exits with status 1 on a different digest, a missing service, or a service the manifest does not list.
- `release-clean` removes the local `lincodex.invalid/*` images and keeps the files in `deploy/release/`.
- `release-manifest` reads local images, the build record, evidence, and optionally a data descriptor. It pulls nothing. `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.
- 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.
- `release-clean` removes local release image references that no immutable manifest retains and keeps the files in `deploy/release/`.
The release 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. All files go to `deploy/release/<tag>/`, which Git and the root `.dockerignore` ignore. Manifests are not committed: built image IDs depend on the machine, platform, and build time, and the manifest describes what this machine built and checked. Attach the manifest to the release instead.
The source tag is the first 12 characters of the commit, with `-dirty` when the working tree differs from it. The working tree fingerprint is the Git tree ID written from a temporary index (seeded from HEAD, then `git add -A`), with line ending, file mode, symlink, and fsmonitor settings pinned. It covers modified, deleted, and untracked files, does not depend on diff settings, and leaves the real index untouched. Build and evidence records go to `deploy/release/<source-tag>/`; immutable manifests go to `deploy/release/<release-id>/`. Git and the root `.dockerignore` ignore these local artifacts. Manifests are not committed: built image IDs depend on the machine, platform, and build time, and each manifest describes what this machine built and checked. Attach a manifest to the delivery when needed.
### Format
The manifest is JSON with sorted keys and schema `lincodex.release-manifest/v1`:
The manifest is JSON with sorted keys and schema `lincodex.release-manifest/v2`:
| Key | Content |
| --- | --- |
| `schema`, `generated_at` | Schema version and UTC generation time |
| `release` | `tag`, `status` (`verified` or `unverified`), `scope` (`core`), `required_checks` (`smoke`, `e2e`), and the `reasons` that keep it unverified |
| `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 |
| `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 |
| `lockfiles` | SHA-256 of `backend/go.mod`, `backend/go.sum`, `frontend/package.json`, `frontend/pnpm-lock.yaml`, `ml/pyproject.toml`, and `ml/uv.lock` |
| `checks`, `rejected_checks` | Accepted evidence with its scope, finish time, commit, fingerprint, and tool image, such as the Playwright image; rejected evidence with the reason |
| `components` | Each Compose service of core, ML, and monitoring and each missing component: `group`, `kind` (`built`, `pulled`, `absent`), the image (`reference`, `present`, `image_id`, `repo_digest` for the tag's repository, all `repo_digests`, `platform`, and allowlisted `versions`), for built images the Dockerfile, its hash, build arguments, and base images, and `verification` |
| `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 |
| `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` |
`verification.status` is one of:
@@ -588,7 +593,7 @@ The release is `verified` only when all of the following hold; otherwise `releas
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 not refused: the manifest is written with `unverified` and the reason, so a local candidate can be checked before the commit.
Generating the manifest again for the same source, images, and evidence gives the same document apart from `generated_at`; the target says whether anything else changed since the previous manifest of the tag. Version fields are copied only from an allowlist of image variables and OCI labels. The manifest never contains environment values, `.env` content, container labels, mounts, local paths, user or host names; every file is scanned for those, for values of variables whose names suggest secrets (also as substrings and in base64), and for secret patterns before it is written, and `release-manifest-check` repeats the scan.
Generating the manifest again for the same ID, source, images, evidence, and data leaves the submitted file unchanged. A new data snapshot or stage gets a new ID. Version fields are copied only from an allowlist of image variables and OCI labels. The manifest never contains environment values, `.env` content, container labels, mounts, local paths, user or host names; every file is scanned for those, for values of variables whose names suggest secrets (also as substrings and in base64), and for secret patterns before it is written, and `release-manifest-check` repeats the scan.
### Go pin
@@ -596,7 +601,7 @@ go.mod declares `go 1.26.8` without a separate `toolchain` line, the default `GO
### Not covered
- The manifest is not an SBOM, a license inventory, a signature, or a provenance attestation, and it is not pushed to a registry.
- The manifest is not an SBOM, a license inventory, a signature, or a provenance attestation, and it is not pushed to a registry. A restore reinstates images and Compose configuration; it does not restore or validate database contents or persistent volume backups.
- The files in `deploy/release/` are local and not tamper-proof; evidence is not signed and proves only what this machine recorded.
- Git-ignored files are not part of the fingerprint. A build context still receives such files unless `.dockerignore` excludes them.
- Images are built for the local platform only. Versions without an image variable or label, such as Kafka, are identified only by digest.
+4
View File
@@ -461,6 +461,10 @@ Offsets и партиции. Каждый обработчик - один уча
Тестовые фикстуры используют собственные значения. Поскольку `product` - единственное семейство, интеграционные тесты дают каждому случаю отдельную базу данных, и ни одна фикстура не подменяет демонстрационную политику.
## Артефакты выпуска и восстановление
Локальный манифест разделяет проверку core-образов и наличие продуктовых данных. Он записывает неизменяемый ID выпуска, хеши исходников и Compose-файлов, точные image ID собранных образов, registry digest скачанных образов и ограниченные хеши версионированных артефактов данных. До старта Compose восстановление сверяет эти ссылки и хеши и не разрешает плавающие теги заново. Исходник демонстрационной политики в составе проекта имеет версию 1, но это не показывает, какая строка политики активна в PostgreSQL. Банк оценивания и демонстрационный seed пока недоступны до появления принятых снимков, поэтому `product_data_status` равен `partial`. Именованные Compose volumes сохраняются при перезапуске выпуска, но манифест не является резервной копией базы или снимком данных. Команды и схема описаны в [DEPLOY.md](DEPLOY.md#манифест-выпуска).
## Структура репозитория и назначение пакетов
```text
+18 -13
View File
@@ -542,36 +542,41 @@ Backend строится с Go 1.26.8; образ runtime выбран в backen
## Манифест выпуска
Манифест выпуска фиксирует, из чего состоит проверенный локальный выпуск: коммит, версии toolchain, хеши lockfiles, образ каждого сервиса с фактическим digest и компоненты, на которых проверка действительно выполнялась. Плавающие теги `latest` и `alpine` по договоренности остаются в Compose и Dockerfile; манифест закрепляет, во что они разрешились в момент выпуска. Интерфейс - `make -C deploy release-manifest`; остальные цели `release-*` готовят его входные данные и проверяют результат:
Манифест фиксирует исходники, toolchain, lockfiles, Compose-файлы, image ID и digest образов, а также версионированные входные данные одной локальной поставки. Плавающие теги `latest` и `alpine` могут оставаться в Compose: восстановление использует записанные image ID или repository digest, не разрешая эти теги заново. По умолчанию ID выпуска строится из коммита. Для разных поставок одного исходника, этапов или набора данных задайте короткий `RELEASE_ID`:
make -C deploy release-build
make -C deploy release-smoke
make -C deploy release-e2e
make -C deploy release-manifest
make -C deploy release-manifest-check
make -C deploy release-manifest RELEASE_ID=demo-stage-1
make -C deploy release-manifest-check 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-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; ничего не скачивает. Отсутствующий образ указывается как отсутствующий. Evidence или запись сборки с неверной структурой или записанные для другого тега, коммита или состояния рабочего дерева не используются; отклоненный evidence перечисляется в `rejected_checks`.
- `release-manifest-check` проверяет структуру манифеста и ищет в нем секреты и данные машины.
- `release-up` и `release-down` запускают core-стек из образов выпуска с `ENV_FILE` и `APP_PROJECT` без сборки и скачивания. `make -C deploy release-manifest-verify RELEASE_VERIFY_PROJECT=<project>` сравнивает каждый запущенный контейнер этого Compose-проекта по image ID с манифестом текущего тега или с `RELEASE_MANIFEST=<path>`. Цель печатает статус выпуска и завершается со статусом 1 при другом digest, незапущенном сервисе или сервисе, которого нет в манифесте.
- `release-clean` удаляет локальные образы `lincodex.invalid/*` и оставляет файлы в `deploy/release/`.
- `release-manifest` читает локальные образы, запись сборки, 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.
- Публикация выполняется один раз в `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 при несовпадении, отсутствии сервиса или неизвестном сервисе.
- `release-clean` удаляет ссылки на образы выпуска, которые не удерживает ни один неизменяемый манифест; файлы в `deploy/release/` остаются.
Тег выпуска - первые 12 символов коммита, с суффиксом `-dirty`, если рабочее дерево отличается от коммита. Отпечаток рабочего дерева - Git tree ID, записанный из временного индекса (заполняется из HEAD, затем `git add -A`) с закрепленными настройками переводов строк, режима файлов, symlink и fsmonitor. Он учитывает измененные, удаленные и неотслеживаемые файлы, не зависит от настроек diff и не меняет настоящий индекс. Все файлы пишутся в `deploy/release/<tag>/`, который игнорируют Git и корневой `.dockerignore`. Манифесты не коммитятся: image ID собранных образов зависят от машины, платформы и времени сборки, а манифест описывает то, что собрала и проверила эта машина. Прикладывайте манифест к выпуску.
Тег исходников - первые 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 собранных образов зависят от машины, платформы и времени сборки, а файл описывает конкретную локальную поставку.
### Формат
Манифест - JSON с отсортированными ключами и схемой `lincodex.release-manifest/v1`:
Манифест - JSON с отсортированными ключами и схемой `lincodex.release-manifest/v2`:
| Ключ | Содержимое |
| --- | --- |
| `schema`, `generated_at` | Версия схемы и время генерации в UTC |
| `release` | `tag`, `status` (`verified` или `unverified`), `scope` (`core`), `required_checks` (`smoke`, `e2e`) и `reasons`, по которым выпуск не проверен |
| `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 |
| `lockfiles` | SHA-256 `backend/go.mod`, `backend/go.sum`, `frontend/package.json`, `frontend/pnpm-lock.yaml`, `ml/pyproject.toml` и `ml/uv.lock` |
| `checks`, `rejected_checks` | Принятый evidence с охватом, временем завершения, коммитом, отпечатком и образом инструмента, например Playwright; отклоненный evidence с причиной |
| `components` | Каждый Compose-сервис core, ML и monitoring и каждый отсутствующий компонент: `group`, `kind` (`built`, `pulled`, `absent`), образ (`reference`, `present`, `image_id`, `repo_digest` для репозитория тега, все `repo_digests`, `platform` и разрешенные `versions`), для собранных образов - Dockerfile, его хеш, build-аргументы и базовые образы, а также `verification` |
| `restore` | Можно ли восстановить core Compose-проект, точная команда и причины блокировки preflight |
| `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` |
`verification.status` принимает значения:
@@ -590,7 +595,7 @@ Backend строится с Go 1.26.8; образ runtime выбран в backen
Версия Python, отличная от `ml/.python-version`, отражается в `matches_version_file`, но не блокирует выпуск: ML вне проверяемого охвата. Поэтому плавающий тег `node:alpine` может сделать выпуск непроверенным, пока не обновлен `.node-version`. Грязное дерево не отклоняется: манифест пишется со статусом `unverified` и причиной, чтобы локального кандидата можно было проверить до коммита.
Повторная генерация для тех же исходников, образов и evidence дает тот же документ, кроме `generated_at`; цель сообщает, изменилось ли что-то еще по сравнению с предыдущим манифестом тега. Поля версий копируются только из разрешенного списка переменных образа и OCI labels. Манифест никогда не содержит значений окружения, содержимого `.env`, labels контейнеров, mounts, локальных путей, имен пользователя или хоста; перед записью каждый файл проверяется на них, на значения переменных с именами, похожими на секреты (в том числе как подстроки и в base64), и на шаблоны секретов, а `release-manifest-check` повторяет проверку.
`source_kind` равен `bundled_source` для исходника демонстрационной политики и `snapshot` для входного снимка данных. `bundled_source` не доказывает, какая версия политики находится в runtime-базе. Bank и seed остаются недоступны, пока для них нет принятых снимков. Поля версий образа копируются только из разрешенных переменных и OCI labels. Манифест не содержит значения окружения, содержимое `.env`, labels контейнеров, mounts, локальные пути, имя пользователя или хоста. До публикации он проверяется на эти данные и секреты; `release-manifest-check` повторяет сканирование.
### Go pin