Fix Device Core release health contract and prove r5 restoration

This commit is contained in:
Codex
2026-09-29 19:26:33 +03:00
parent d161d7fb91
commit ed500278a0
5 changed files with 437 additions and 10 deletions
+188 -10
View File
@@ -2960,6 +2960,11 @@ GITEA_SALVAGE_UNSUPPORTED_SCHEMA_TABLES = tuple(
) )
COMPONENTS = { COMPONENTS = {
"device-core-release-reconciliation": {
"payload_root": DEVICE_PLANE_ROOT,
"artifact_only": True,
"services": (),
},
"device-core-release": { "device-core-release": {
"payload_root": DEVICE_PLANE_ROOT, "payload_root": DEVICE_PLANE_ROOT,
"compose_root": DEVICE_PLANE_ROOT, "compose_root": DEVICE_PLANE_ROOT,
@@ -4963,6 +4968,10 @@ def denied_payload_path(component, rel):
def allowed_payload_path(component, rel): def allowed_payload_path(component, rel):
validate_posix_path(rel) validate_posix_path(rel)
if component == "device-core-release-reconciliation":
if rel in ("deployment", DEVICE_RELEASE_RECONCILIATION_ENTRY):
return True
die("Device Core reconciliation accepts only its exact descriptor")
if component == "device-core-release": if component == "device-core-release":
return device_release_payload_path(rel) return device_release_payload_path(rel)
reason = denied_payload_path(component, rel) reason = denied_payload_path(component, rel)
@@ -11579,6 +11588,8 @@ def load_artifact(artifact, work_dir):
die(f"files.txt entry missing in payload: {rel}") die(f"files.txt entry missing in payload: {rel}")
validate_payload_tree(manifest["component"], payload_dir, entries) validate_payload_tree(manifest["component"], payload_dir, entries)
if manifest["component"] == "device-core-release-reconciliation":
validate_device_release_reconciliation_payload(payload_dir, entries, manifest["id"])
if manifest["component"] == "device-core-release": if manifest["component"] == "device-core-release":
validate_device_release_payload(payload_dir, entries, manifest["id"]) validate_device_release_payload(payload_dir, entries, manifest["id"])
if manifest["component"] == "gitea-actions-config": if manifest["component"] == "gitea-actions-config":
@@ -20567,6 +20578,7 @@ def validate_device_manager_control_plane_runtime(
require_edge_channel=None, require_edge_channel=None,
core_network_mode=None, core_network_mode=None,
require_persistent_data=None, require_persistent_data=None,
read_only=False,
): ):
core_ids = device_plane_service_container_ids("device-control-core") core_ids = device_plane_service_container_ids("device-control-core")
manager_ids = device_plane_service_container_ids("device-manager") manager_ids = device_plane_service_container_ids("device-manager")
@@ -20790,11 +20802,14 @@ def validate_device_manager_control_plane_runtime(
if inspect_device_edge_channel_core_identity_state() != "valid-reuse-at-apply": if inspect_device_edge_channel_core_identity_state() != "valid-reuse-at-apply":
die("Device Edge channel Core identity is not active") die("Device Edge channel Core identity is not active")
validate_device_edge_channel_public_export() validate_device_edge_channel_public_export()
ensure_platform_runtime_secret( if read_only:
PLATFORM_DEVICE_CORE_INTERNAL_TOKEN_FILE, validate_device_release_hub_secret()
MAP_GATEWAY_SECRET_RE, else:
"Device Core Hub handoff", ensure_platform_runtime_secret(
) PLATFORM_DEVICE_CORE_INTERNAL_TOKEN_FILE,
MAP_GATEWAY_SECRET_RE,
"Device Core Hub handoff",
)
return "exact" return "exact"
@@ -22425,6 +22440,10 @@ def is_platform_provider_catalog_only(entries):
def component_services(component, entries=None): def component_services(component, entries=None):
if component == "device-core-release-reconciliation":
if tuple(entries or ()) != (DEVICE_RELEASE_RECONCILIATION_ENTRY,):
die("Device Core reconciliation requires the exact descriptor entry")
return ()
if component == "device-core-release": if component == "device-core-release":
if tuple(entries or ()) != DEVICE_RELEASE_ENTRIES: if tuple(entries or ()) != DEVICE_RELEASE_ENTRIES:
die("Device Core release service selection requires exact entries") die("Device Core release service selection requires exact entries")
@@ -32370,7 +32389,8 @@ def device_release_predecessor(candidate):
applied = load_state(STATE_FILE) applied = load_state(STATE_FILE)
for row in load_state(FAILED_STATE_FILE): for row in load_state(FAILED_STATE_FILE):
if row.get("component") == "device-core-release" and row.get("started_apply") and not str(row.get("rollback_status", "")).startswith("ok:"): if row.get("component") == "device-core-release" and row.get("started_apply") and not str(row.get("rollback_status", "")).startswith("ok:"):
die("Device Core release requires reconciliation of a failed rollback") if not device_release_r5_reconciled(row):
die("Device Core release requires reconciliation of a failed rollback")
normal = [row for row in applied if row.get("component") == "device-core-release"] normal = [row for row in applied if row.get("component") == "device-core-release"]
installed = DEVICE_PLANE_ROOT / DEVICE_RELEASE_ENTRY installed = DEVICE_PLANE_ROOT / DEVICE_RELEASE_ENTRY
expected = {} expected = {}
@@ -32463,6 +32483,146 @@ def device_release_other_compose_services():
return result return result
# One exact evidence-only reconciliation of the r5 health-contract incident.
DEVICE_RELEASE_R5_ID = "device-core-release-v1-r5-67b2ae586399eb1eb7d3a6c074a292e0dbb7b406"
DEVICE_RELEASE_R5_SHA = "b8dd1384f499d1173ce7d95dc1f2433a404290f443bd612816ad9136ccbf9347"
DEVICE_RELEASE_R5_BACKUP = "device-core-release-" + DEVICE_RELEASE_R5_ID + "-20260929-190019"
DEVICE_RELEASE_RECONCILIATION_ID = "device-core-release-r5-reconciliation-v1-20260929-001"
DEVICE_RELEASE_RECONCILIATION_ENTRY = "deployment/device-core-release-r5-reconciliation-v1.json"
DEVICE_RELEASE_R5_BACKUP_HASHES = {
"device-release-before.json": "0e30ebd1a1e511da5e8026afbba9b761c5edb2fcc151b23ecc79bbae8af0b739",
"source-before.tgz": "d597d1cd1dcb1eeaf79836c40523258ae1a9aa1b6e3333a94238f40f078accb5",
"manifest.env": "484c124d22d89daf9fb869c64c5748d6ec7cb4614b0c6155b9e68f952d111248",
"files.txt": "4d02728c991e4666425d968497d3540ad95802de055db4f899411ce34e526b5a",
"existing-files.txt": "f34f96aba57759c7302c24f03dc45281eea49032deed0a4f0d55685689d79e2b",
"missing-files.txt": "8d836605cbac79413813582fbce798c80196a4bbbd259f9b97559fab90f5d2e8",
}
def validate_device_release_hub_secret():
path = PLATFORM_DEVICE_CORE_INTERNAL_TOKEN_FILE
for target, directory, mode in ((path.parent, True, 0o710), (path, False, 0o640)):
try:
info = target.lstat()
except FileNotFoundError:
die("Device Core existing Hub secret is missing")
if (stat.S_ISLNK(info.st_mode) or (not stat.S_ISDIR(info.st_mode) if directory else not stat.S_ISREG(info.st_mode))
or info.st_uid != 0 or info.st_gid != MAP_GATEWAY_RUNTIME_GID or stat.S_IMODE(info.st_mode) != mode):
die("Device Core existing Hub secret boundary mismatch")
if not directory and info.st_size > 512:
die("Device Core existing Hub secret is oversized")
try:
value = path.read_text(encoding="ascii").strip()
except (OSError, UnicodeDecodeError):
die("Device Core existing Hub secret is unreadable")
if not MAP_GATEWAY_SECRET_RE.fullmatch(value):
die("Device Core existing Hub secret format mismatch")
def device_release_healthchecks():
# Matches the preserved Core v4 + Manager v13 foundation, not the older
# disabled foundation's generic device-plane fallback.
return (
{"url": "http://127.0.0.1:18120/healthz", "expected_json": {
"ok": True, "service": "nodedc-device-control-core", "database": "ready",
"discoveryIngest": "enabled", "managementApi": "enabled",
"commandTransport": "typed-service-ping-v1",
}},
{"url": "http://127.0.0.1:18080/healthz", "headers": {"Host": "device.nodedc.ru"},
"expected_json": {"ok": True, "service": "nodedc-device-manager",
"authRequired": True, "deviceCoreConfigured": True}},
)
def device_release_reconciliation_descriptor():
return {"schemaVersion": "nodedc.device-core.release-reconciliation.v1",
"releaseId": DEVICE_RELEASE_RECONCILIATION_ID,
"failedReleaseId": DEVICE_RELEASE_R5_ID, "failedSha256": DEVICE_RELEASE_R5_SHA,
"backupId": DEVICE_RELEASE_R5_BACKUP, "mode": "prove-restored-baseline-only"}
def validate_device_release_reconciliation_payload(payload, entries, patch_id):
if tuple(entries) != (DEVICE_RELEASE_RECONCILIATION_ENTRY,) or patch_id != DEVICE_RELEASE_RECONCILIATION_ID:
die("Device Core reconciliation identity/entry mismatch")
if read_strict_json(payload / DEVICE_RELEASE_RECONCILIATION_ENTRY, "Device Core reconciliation") != device_release_reconciliation_descriptor():
die("Device Core reconciliation descriptor mismatch")
def device_release_r5_failed_row():
return {"artifact": "nodedc-" + DEVICE_RELEASE_R5_ID + ".tgz.20260929-190019",
"backup_id": DEVICE_RELEASE_R5_BACKUP, "component": "device-core-release",
"failed_at": "2026-09-29T16:06:28+00:00", "id": DEVICE_RELEASE_R5_ID,
"message": "healthcheck failed for http://127.0.0.1:18120/healthz: health response contract mismatch",
"rollback_status": "failed:DeployError", "sha256": DEVICE_RELEASE_R5_SHA,
"started_apply": True, "status": "failed"}
def device_release_r5_evidence():
expected = device_release_r5_failed_row()
rows = [r for r in load_state(FAILED_STATE_FILE) if r.get("id") == DEVICE_RELEASE_R5_ID or r.get("sha256") == DEVICE_RELEASE_R5_SHA]
if rows != [expected]:
die("Device Core reconciliation failed journal mismatch")
if any(r.get("id") == DEVICE_RELEASE_R5_ID or r.get("sha256") == DEVICE_RELEASE_R5_SHA for r in load_state(STATE_FILE)):
die("Device Core failed release conflicts with applied journal")
failed = FAILED_DIR / expected["artifact"]
if failed.is_symlink() or not failed.is_file() or sha256_file(failed) != DEVICE_RELEASE_R5_SHA:
die("Device Core reconciliation failed archive mismatch")
backup = BACKUPS_DIR / DEVICE_RELEASE_R5_BACKUP
if backup.is_symlink() or not backup.is_dir():
die("Device Core reconciliation backup is missing or unsafe")
for name, digest in DEVICE_RELEASE_R5_BACKUP_HASHES.items():
path = backup / name
if path.is_symlink() or not path.is_file() or sha256_file(path) != digest:
die("Device Core reconciliation backup digest mismatch: " + name)
before = read_strict_json(backup / "device-release-before.json", "Device Core r5 runtime backup", max_bytes=256*1024)
existing = read_backup_path_list(backup / "existing-files.txt")
missing = read_backup_path_list(backup / "missing-files.txt")
validate_backup_partition(DEVICE_RELEASE_ENTRIES, existing, missing, "Device Core reconciliation")
if missing != [DEVICE_RELEASE_ENTRY]:
die("Device Core reconciliation backup partition mismatch")
with tempfile.TemporaryDirectory(prefix="device-r5-evidence-", dir=TMP_DIR) as tmp:
root = Path(tmp)
materialize_backup_tree(backup / "source-before.tgz", root, set(existing))
if collect_exact_files(root, existing, "Device Core r5 source backup") != before["installedFiles"]:
die("Device Core reconciliation source/runtime evidence conflict")
return before
def preflight_device_release_reconciliation(payload, entries, patch_id, *, marker_installed=False):
validate_device_release_reconciliation_payload(payload, entries, patch_id)
marker = DEVICE_PLANE_ROOT / DEVICE_RELEASE_RECONCILIATION_ENTRY
if not marker_installed and (marker.exists() or marker.is_symlink()):
die("Device Core reconciliation marker already exists")
before = device_release_r5_evidence()
# Source, current image IDs, configuration and every preserved dependency
# are checked without invoking any build, Compose mutation or secret ensure.
run_healthchecks("device-core-release", DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES)
accept_device_release(before, rollback=True)
print("device_release_reconciliation=restored-baseline-proven;services=none;build=none;runtime-mutation=none")
return before
def device_release_r5_reconciled(row):
if row != device_release_r5_failed_row():
return False
marker = DEVICE_PLANE_ROOT / DEVICE_RELEASE_RECONCILIATION_ENTRY
if marker.is_symlink() or not marker.is_file():
return False
validate_device_release_reconciliation_payload(DEVICE_PLANE_ROOT, (DEVICE_RELEASE_RECONCILIATION_ENTRY,), DEVICE_RELEASE_RECONCILIATION_ID)
records = [r for r in load_state(STATE_FILE) if r.get("id") == DEVICE_RELEASE_RECONCILIATION_ID]
if len(records) != 1 or records[0].get("component") != "device-core-release-reconciliation":
die("Device Core reconciliation marker lacks its canonical applied receipt")
with tempfile.TemporaryDirectory(prefix="device-r5-marker-", dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(records[0]), Path(tmp))
if manifest.get("component") != "device-core-release-reconciliation" or manifest.get("id") != DEVICE_RELEASE_RECONCILIATION_ID:
die("Device Core reconciliation applied archive identity mismatch")
if sha256_file(payload / DEVICE_RELEASE_RECONCILIATION_ENTRY) != sha256_file(marker):
die("Device Core reconciliation installed marker drift")
# Keep original incident evidence immutable after acknowledgement.
device_release_r5_evidence()
return True
def preflight_device_release(payload, entries, patch_id): def preflight_device_release(payload, entries, patch_id):
d = validate_device_release_payload(payload, entries, patch_id) d = validate_device_release_payload(payload, entries, patch_id)
predecessor = device_release_predecessor(d) predecessor = device_release_predecessor(d)
@@ -32471,7 +32631,8 @@ def preflight_device_release(payload, entries, patch_id):
immutable = (".dockerignore", "services/device-control-core/Dockerfile", "services/device-manager/Dockerfile", "services/device-control-core/migrations") immutable = (".dockerignore", "services/device-control-core/Dockerfile", "services/device-manager/Dockerfile", "services/device-control-core/migrations")
if collect_exact_files(payload, immutable, "Device Core candidate foundation") != collect_exact_files(DEVICE_PLANE_ROOT, immutable, "Device Core installed foundation"): if collect_exact_files(payload, immutable, "Device Core candidate foundation") != collect_exact_files(DEVICE_PLANE_ROOT, immutable, "Device Core installed foundation"):
die("Device Core release changes the immutable database/build foundation") die("Device Core release changes the immutable database/build foundation")
validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True) validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True, read_only=True)
run_healthchecks("device-core-release", entries, DEVICE_RELEASE_SERVICES)
before = device_release_runtime_snapshot() before = device_release_runtime_snapshot()
compose = {str(p): sha256_file(p) for p in component_compose_files("device-plane")} compose = {str(p): sha256_file(p) for p in component_compose_files("device-plane")}
return {"descriptor": d, "predecessor": predecessor["releaseId"] if predecessor else "manager-v13/core-v4/edge-v4", return {"descriptor": d, "predecessor": predecessor["releaseId"] if predecessor else "manager-v13/core-v4/edge-v4",
@@ -32504,7 +32665,7 @@ def accept_device_release(before, *, rollback=False):
die("Device Core release changed an unrelated Compose service") die("Device Core release changed an unrelated Compose service")
if {str(p): sha256_file(p) for p in component_compose_files("device-plane")} != before["compose"]: if {str(p): sha256_file(p) for p in component_compose_files("device-plane")} != before["compose"]:
die("Device Core release changed Compose topology") die("Device Core release changed Compose topology")
validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True) validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True, read_only=True)
if rollback: if rollback:
entries = DEVICE_RELEASE_ENTRIES if DEVICE_RELEASE_ENTRY in before["installedFiles"] else DEVICE_RELEASE_ENTRIES[:-1] entries = DEVICE_RELEASE_ENTRIES if DEVICE_RELEASE_ENTRY in before["installedFiles"] else DEVICE_RELEASE_ENTRIES[:-1]
if collect_exact_files(DEVICE_PLANE_ROOT, entries, "Device Core rollback source") != before["installedFiles"]: if collect_exact_files(DEVICE_PLANE_ROOT, entries, "Device Core rollback source") != before["installedFiles"]:
@@ -32581,6 +32742,8 @@ def plan_artifact(artifact):
gitea_salvage_preflight = None gitea_salvage_preflight = None
with tempfile.TemporaryDirectory(prefix="plan-", dir=TMP_DIR) as tmp: with tempfile.TemporaryDirectory(prefix="plan-", dir=TMP_DIR) as tmp:
manifest, entries, payload_dir = load_artifact(artifact, Path(tmp)) manifest, entries, payload_dir = load_artifact(artifact, Path(tmp))
if manifest["component"] == "device-core-release-reconciliation":
preflight_device_release_reconciliation(payload_dir, entries, manifest["id"])
if manifest["component"] == "device-core-release": if manifest["component"] == "device-core-release":
release_before = preflight_device_release(payload_dir, entries, manifest["id"]) release_before = preflight_device_release(payload_dir, entries, manifest["id"])
print("device_release_source=" + release_before["descriptor"]["sourceCommit"]) print("device_release_source=" + release_before["descriptor"]["sourceCommit"])
@@ -38743,12 +38906,17 @@ process.stdout.write('engine-l2-closed-loop:0.7.0:cas+safe-profile+external-plan
def run_healthchecks(component, entries=None, services=None): def run_healthchecks(component, entries=None, services=None):
if component == "device-core-release-reconciliation":
if tuple(services or ()) != ():
die("Device Core reconciliation must not select services")
preflight_device_release_reconciliation(DEVICE_PLANE_ROOT, entries, DEVICE_RELEASE_RECONCILIATION_ID, marker_installed=True)
return
if component == "device-core-release": if component == "device-core-release":
if tuple(services or ()) != DEVICE_RELEASE_SERVICES or tuple(entries or ()) != DEVICE_RELEASE_ENTRIES: if tuple(services or ()) != DEVICE_RELEASE_SERVICES or tuple(entries or ()) != DEVICE_RELEASE_ENTRIES:
die("Device Core release health scope mismatch") die("Device Core release health scope mismatch")
for service in DEVICE_RELEASE_INVENTORY: for service in DEVICE_RELEASE_INVENTORY:
healthcheck_compose_service_with_grace("device-plane", service) healthcheck_compose_service_with_grace("device-plane", service)
for check in component_healthchecks("device-plane", entries, services): for check in device_release_healthchecks():
healthcheck_url(check) healthcheck_url(check)
return return
if component == "gitea-actions-config": if component == "gitea-actions-config":
@@ -39913,6 +40081,8 @@ def apply_artifact(artifact):
gitea_ci_before = preflight_gitea_ci(entries) gitea_ci_before = preflight_gitea_ci(entries)
if component == "gitea-actions-config": if component == "gitea-actions-config":
gitea_actions_before = preflight_gitea_actions(entries) gitea_actions_before = preflight_gitea_actions(entries)
if component == "device-core-release-reconciliation":
preflight_device_release_reconciliation(payload_dir, entries, patch_id)
if component == "device-core-release": if component == "device-core-release":
device_release_before = preflight_device_release(payload_dir, entries, patch_id) device_release_before = preflight_device_release(payload_dir, entries, patch_id)
artifact_only = component_artifact_only(component) artifact_only = component_artifact_only(component)
@@ -40650,7 +40820,15 @@ def apply_artifact(artifact):
and backup_dir is not None and backup_dir is not None
and root is not None and root is not None
): ):
if component == "device-core-release": if component == "device-core-release-reconciliation":
try:
restore_platform_overlay(root, backup_dir, entries, current_stamp)
if (root / DEVICE_RELEASE_RECONCILIATION_ENTRY).exists():
die("Device Core reconciliation rollback left a marker")
rollback_status = "ok:device-core-release-reconciliation-marker-only"
except Exception as rollback_exc:
rollback_status = "failed:" + type(rollback_exc).__name__
elif component == "device-core-release":
try: try:
rollback_device_release(root, backup_dir, entries, current_stamp, device_release_before, runtime_started) rollback_device_release(root, backup_dir, entries, current_stamp, device_release_before, runtime_started)
rollback_status = "ok:device-core-release" rollback_status = "ok:device-core-release"
@@ -0,0 +1,178 @@
"""Evidence-only r5 reconciliation never installs or starts an application."""
from contextlib import ExitStack, redirect_stdout, redirect_stderr
import copy
import hashlib
import io
import importlib.machinery
import importlib.util
import json
from pathlib import Path
import tempfile
import tarfile
import unittest
from unittest import mock
from test_device_core_release import R, fixture, runtime, put
path=Path(__file__).resolve().parents[1]/'device-core-deploy/build_reconciliation.py'
loader=importlib.machinery.SourceFileLoader('reconciliation_builder',str(path))
spec=importlib.util.spec_from_loader(loader.name,loader);B=importlib.util.module_from_spec(spec);loader.exec_module(B)
class ReconciliationTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup);self.root=Path(self.tmp.name)
self.artifact=self.root/'proof.tgz';self.artifact.write_bytes(B.bundle()[1]);self.work=self.root/'work';self.work.mkdir()
self.manifest,self.entries,self.payload=R.load_artifact(self.artifact,self.work)
def test_deterministic_descriptor_only_has_no_runtime_authority(self):
self.assertEqual(self.artifact.read_bytes(),B.bundle()[1])
self.assertEqual(tuple(self.entries),(R.DEVICE_RELEASE_RECONCILIATION_ENTRY,))
component=self.manifest['component']
self.assertTrue(R.component_artifact_only(component))
self.assertEqual(R.component_services(component,self.entries),())
self.assertEqual(R.component_builds(component,self.entries),())
self.assertEqual(R.component_compose_files(component),())
for rel in ['services/device-manager','deployment/other.json','docker-compose.yml','secrets/key']:
with self.subTest(rel=rel),self.assertRaises(R.DeployError):R.allowed_payload_path(component,rel)
for entries in [[],[R.DEVICE_RELEASE_RECONCILIATION_ENTRY,'services/device-manager']]:
with self.assertRaises(R.DeployError):R.component_services(component,entries)
with mock.patch.object(R,'run_build') as build,mock.patch.object(R,'run_compose') as compose,mock.patch.object(R,'prepare_component_runtime') as prepare:
R.run_component_runtime(component,self.entries,())
build.assert_not_called();compose.assert_not_called();prepare.assert_not_called()
def test_descriptor_cannot_reconcile_another_failure_or_enable_mutation(self):
for key,value in [('failedSha256','f'*64),('mode','restart'),('backupId','elsewhere'),('services',['device-postgres'])]:
d=R.device_release_reconciliation_descriptor();d[key]=value
(self.payload/R.DEVICE_RELEASE_RECONCILIATION_ENTRY).write_text(json.dumps(d))
with self.subTest(key=key),self.assertRaises(R.DeployError):R.validate_device_release_reconciliation_payload(self.payload,self.entries,self.manifest['id'])
def test_journal_ambiguity_and_applied_conflict_fail_closed(self):
expected=R.device_release_r5_failed_row()
for rows in [[],[expected,expected],[{**expected,'rollback_status':'ok:other'}]]:
with self.subTest(rows=len(rows)),mock.patch.object(R,'load_state',return_value=rows),self.assertRaisesRegex(R.DeployError,'journal mismatch'):R.device_release_r5_evidence()
with mock.patch.object(R,'load_state',return_value=[expected]),self.assertRaisesRegex(R.DeployError,'conflicts'):R.device_release_r5_evidence()
def test_unrelated_failed_rollback_cannot_use_this_receipt(self):
row=R.device_release_r5_failed_row();row['id']='unrelated'
self.assertFalse(R.device_release_r5_reconciled(row))
def test_marker_without_applied_receipt_never_unblocks_release(self):
with mock.patch.object(R,'DEVICE_PLANE_ROOT',self.payload),mock.patch.object(R,'load_state',return_value=[]),self.assertRaisesRegex(R.DeployError,'lacks.*receipt'):
R.device_release_r5_reconciled(R.device_release_r5_failed_row())
def test_plan_rejects_orphan_marker_before_any_runtime_check(self):
with mock.patch.object(R,'DEVICE_PLANE_ROOT',self.payload),mock.patch.object(R,'device_release_r5_evidence') as evidence,self.assertRaisesRegex(R.DeployError,'already exists'):
R.preflight_device_release_reconciliation(self.payload,self.entries,self.manifest['id'])
evidence.assert_not_called()
def test_reconciliation_requires_health_and_exact_restored_runtime_without_build(self):
calls=[]
with ExitStack() as stack:
stack.enter_context(mock.patch.object(R,'DEVICE_PLANE_ROOT',self.root/'live'))
stack.enter_context(mock.patch.object(R,'device_release_r5_evidence',return_value={'fixture':True}))
stack.enter_context(mock.patch.object(R,'run_healthchecks',side_effect=lambda *a:calls.append('health')))
accept=stack.enter_context(mock.patch.object(R,'accept_device_release',side_effect=lambda *a,**k:calls.append('restored')))
command=stack.enter_context(mock.patch.object(R.subprocess,'run'))
R.preflight_device_release_reconciliation(self.payload,self.entries,self.manifest['id'])
self.assertEqual(calls,['health','restored']);self.assertTrue(accept.call_args.kwargs['rollback']);command.assert_not_called()
def test_existing_health_contract_is_explicit_and_legacy_is_preserved(self):
expected=R.device_release_healthchecks()[0]['expected_json']
self.assertEqual(expected['discoveryIngest'],'enabled')
self.assertEqual(expected['managementApi'],'enabled')
self.assertEqual(expected['commandTransport'],'typed-service-ping-v1')
old=R.component_healthchecks('device-plane',R.DEVICE_RELEASE_ENTRIES,R.DEVICE_RELEASE_SERVICES)[0]['expected_json']
self.assertEqual(old['discoveryIngest'],'disabled');self.assertEqual(old['commandTransport'],'disabled')
with mock.patch.object(R,'healthcheck_compose_service_with_grace'),mock.patch.object(R,'healthcheck_url') as http:
R.run_healthchecks('device-core-release',R.DEVICE_RELEASE_ENTRIES,R.DEVICE_RELEASE_SERVICES)
self.assertEqual([c.args[0] for c in http.call_args_list],list(R.device_release_healthchecks()))
def evidence_fixture(self, stack):
failed = self.root/'failed';failed.mkdir()
backups = self.root/'backups';backups.mkdir()
backup = backups/R.DEVICE_RELEASE_R5_BACKUP;backup.mkdir()
source = self.root/'old-source';source.mkdir();fixture(source)
(source/R.DEVICE_RELEASE_ENTRY).unlink()
entries = R.DEVICE_RELEASE_ENTRIES[:-1]
before = {'installedFiles':R.collect_exact_files(source,entries,'fixture')}
(backup/'device-release-before.json').write_text(json.dumps(before))
(backup/'existing-files.txt').write_text('\n'.join(entries)+'\n')
(backup/'missing-files.txt').write_text(R.DEVICE_RELEASE_ENTRY+'\n')
(backup/'manifest.env').write_text('fixture')
(backup/'files.txt').write_text('\n'.join(R.DEVICE_RELEASE_ENTRIES)+'\n')
with tarfile.open(backup/'source-before.tgz','w:gz') as tar:
for entry in entries:tar.add(source/entry,arcname=entry)
failed_archive=failed/R.device_release_r5_failed_row()['artifact'];failed_archive.write_bytes(b'failed-fixture')
stack.enter_context(mock.patch.object(R,'DEVICE_RELEASE_R5_SHA',R.sha256_file(failed_archive)))
stack.enter_context(mock.patch.object(R,'DEVICE_RELEASE_R5_BACKUP_HASHES',{p.name:R.sha256_file(p) for p in backup.iterdir()}))
stack.enter_context(mock.patch.object(R,'FAILED_DIR',failed))
stack.enter_context(mock.patch.object(R,'BACKUPS_DIR',backups))
stack.enter_context(mock.patch.object(R,'TMP_DIR',self.root))
stack.enter_context(mock.patch.object(R,'load_state',side_effect=lambda p:[R.device_release_r5_failed_row()] if p==R.FAILED_STATE_FILE else []))
return backup,failed_archive,before
def test_exact_evidence_checks_bytes_and_source_partition(self):
with ExitStack() as stack:
backup,failed,before=self.evidence_fixture(stack)
self.assertEqual(R.device_release_r5_evidence(),before)
for path in [failed,*(backup/p for p in R.DEVICE_RELEASE_R5_BACKUP_HASHES)]:
saved=path.read_bytes();path.write_bytes(saved+b'tamper')
with self.subTest(path=path.name),self.assertRaises(R.DeployError):R.device_release_r5_evidence()
path.write_bytes(saved)
# Even internally hash-consistent backups must describe the same restored source.
before['installedFiles']['package.json']='f'*64
proof=backup/'device-release-before.json';proof.write_text(json.dumps(before))
with mock.patch.dict(R.DEVICE_RELEASE_R5_BACKUP_HASHES,{'device-release-before.json':R.sha256_file(proof)}),self.assertRaisesRegex(R.DeployError,'source/runtime evidence conflict'):
R.device_release_r5_evidence()
def test_restoration_rejects_wrong_images_config_and_preserved_services(self):
old=runtime();before={'runtime':old,'compose':{},'otherComposeServices':{},'installedFiles':{}}
for service,key,value in [('device-control-core','imageId','sha256:'+'e'*64),('device-manager','runtimeConfigSha256','e'*64),('device-postgres','containerId','c'*64)]:
current=copy.deepcopy(old);current[service][key]=value
with self.subTest(service=service,key=key),mock.patch.object(R,'device_release_runtime_snapshot',return_value=current),self.assertRaises(R.DeployError):
R.accept_device_release(before,rollback=True)
with mock.patch.object(R,'device_release_runtime_snapshot',return_value=old),mock.patch.object(R,'device_release_other_compose_services',return_value={'other':'drift'}),self.assertRaisesRegex(R.DeployError,'unrelated Compose service'):
R.accept_device_release(before,rollback=True)
def test_missing_secret_never_creates_or_repairs_it(self):
secret=self.root/'absent/token'
with mock.patch.object(R,'PLATFORM_DEVICE_CORE_INTERNAL_TOKEN_FILE',secret),mock.patch.object(R.os,'chown') as chown,mock.patch.object(R,'ensure_platform_runtime_secret') as ensure,self.assertRaisesRegex(R.DeployError,'missing'):
R.validate_device_release_hub_secret()
self.assertFalse(secret.parent.exists());chown.assert_not_called();ensure.assert_not_called()
def execute_metadata_apply(self,fail_health=False):
live=self.root/'live';live.mkdir();put(live,'services/device-manager/untouched',b'old')
for directory in ['inbox','applied','failed','backups','state','tmp']:(self.root/directory).mkdir()
config={**R.COMPONENTS['device-core-release-reconciliation'],'payload_root':live}
with ExitStack() as stack:
for name,value in [('INBOX',self.root/'inbox'),('APPLIED_DIR',self.root/'applied'),('FAILED_DIR',self.root/'failed'),('BACKUPS_DIR',self.root/'backups'),('STATE_DIR',self.root/'state'),('TMP_DIR',self.root/'tmp'),('STATE_FILE',self.root/'state/applied.jsonl'),('FAILED_STATE_FILE',self.root/'state/failed.jsonl'),('LOCK_DIR',self.root/'lock'),('DEVICE_PLANE_ROOT',live)]:
stack.enter_context(mock.patch.object(R,name,value))
stack.enter_context(mock.patch.dict(R.COMPONENTS,{'device-core-release-reconciliation':config}))
for name in ['require_root','ensure_layout','validate_artifact_location','preflight_device_release_reconciliation']:
stack.enter_context(mock.patch.object(R,name))
command=stack.enter_context(mock.patch.object(R.subprocess,'run'))
build=stack.enter_context(mock.patch.object(R,'run_build'))
compose=stack.enter_context(mock.patch.object(R,'run_compose'))
stack.enter_context(mock.patch.object(R,'run_healthchecks',side_effect=R.DeployError('injected health') if fail_health else None))
stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO()))
if fail_health:
with self.assertRaises(R.DeployError):R.apply_artifact(self.artifact)
else:R.apply_artifact(self.artifact)
command.assert_not_called();build.assert_not_called();compose.assert_not_called()
self.assertEqual((live/'services/device-manager/untouched').read_bytes(),b'old')
self.assertEqual((live/R.DEVICE_RELEASE_RECONCILIATION_ENTRY).exists(),not fail_health)
return R.load_state(R.STATE_FILE),R.load_state(R.FAILED_STATE_FILE)
def test_apply_records_receipt_without_runtime_action(self):
applied,failed=self.execute_metadata_apply()
self.assertEqual(len(applied),1);self.assertFalse(failed)
self.assertEqual(applied[0]['component'],'device-core-release-reconciliation')
def test_failed_reconciliation_removes_only_marker(self):
applied,failed=self.execute_metadata_apply(fail_health=True)
self.assertFalse(applied)
self.assertEqual(failed[0]['rollback_status'],'ok:device-core-release-reconciliation-marker-only')
if __name__=='__main__':unittest.main()
+25
View File
@@ -65,3 +65,28 @@ python3 -m unittest discover -s infra/gitea-ci -p 'test_*.py'
The Device Core repository's full `infra/deploy-runner` suite must also pass against The Device Core repository's full `infra/deploy-runner` suite must also pass against
the changed canonical runner. Its historical skipped tests remain reported as the changed canonical runner. Its historical skipped tests remain reported as
skipped, not as live acceptance. skipped, not as live acceptance.
## Initial r5 health-contract incident
The first normal release (run 5, source `67b2ae586399eb1eb7d3a6c074a292e0dbb7b406`)
failed acceptance and rollback acceptance because the new domain selected the old
generic disabled-foundation health expectations. The current preserved foundation
reports discovery and management enabled and `typed-service-ping-v1`. The release
now uses an explicit contract before build, after activation and during rollback.
Legacy transition contracts remain unchanged. Device Core's
`test_device_release_health_contract.py` runs the actual Core and Manager HTTP
handlers against the pinned installer; it fails on the original installer and
passes on this correction, including negative dependency/auth/capability cases.
`build_reconciliation.py` packages one fixed data descriptor for
`device-core-release-reconciliation`. Its plan and apply prove the exact failed
journal/archive, six backup digests, restored sources, old image IDs, runtime
configuration, Compose and preserved services. No build, restart, secret repair,
port or database action exists in this domain. Apply writes only a marker and a
separate canonical receipt; failure removes only that marker. It never rewrites
the original failed journal. Later releases require marker + applied archive +
receipt + original incident evidence. Other rollback failures remain blocked.
The r5 archive must never be replayed. Reconciliation does not install a release
or activate automatic deployment. Only after its live acceptance may a NEW
successful CI run become the next normal-release candidate.
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Build the exact evidence-only r5 reconciliation, never application code."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import tarfile
ROOT = Path(__file__).resolve().parent
ENTRY = 'deployment/device-core-release-r5-reconciliation-v1.json'
def bundle():
descriptor = (ROOT / 'r5-reconciliation-v1.json').read_bytes()
identity = json.loads(descriptor)['releaseId']
members = {
'manifest.env': ('id='+identity+'\ncomponent=device-core-release-reconciliation\ntype=app-overlay\n').encode(),
'files.txt': (ENTRY+'\n').encode(),
'payload/'+ENTRY: descriptor,
}
output=io.BytesIO()
with gzip.GzipFile(fileobj=output, mode='wb', mtime=0, filename='') as compressed:
with tarfile.open(fileobj=compressed, mode='w') as archive:
for name,data in sorted(members.items()):
info=tarfile.TarInfo(name);info.mode=0o644;info.size=len(data)
archive.addfile(info,io.BytesIO(data))
return identity,output.getvalue()
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output-dir',required=True,type=Path)
args=parser.parse_args();args.output_dir.mkdir(parents=True,exist_ok=True)
identity,data=bundle();path=args.output_dir/('nodedc-'+identity+'.tgz')
with path.open('xb') as stream:stream.write(data)
print(json.dumps({'artifact':str(path),'sha256':hashlib.sha256(data).hexdigest(),'id':identity}))
@@ -0,0 +1,8 @@
{
"schemaVersion": "nodedc.device-core.release-reconciliation.v1",
"releaseId": "device-core-release-r5-reconciliation-v1-20260929-001",
"failedReleaseId": "device-core-release-v1-r5-67b2ae586399eb1eb7d3a6c074a292e0dbb7b406",
"failedSha256": "b8dd1384f499d1173ce7d95dc1f2433a404290f443bd612816ad9136ccbf9347",
"backupId": "device-core-release-device-core-release-v1-r5-67b2ae586399eb1eb7d3a6c074a292e0dbb7b406-20260929-190019",
"mode": "prove-restored-baseline-only"
}