Wait for B2 Core readiness and reconcile exact failed foundation002

This commit is contained in:
Codex
2026-09-30 17:00:03 +03:00
parent 1e191868be
commit 39a2239563
5 changed files with 534 additions and 5 deletions
@@ -65,6 +65,55 @@ reproduction. Qualification with that fixture and with all five NAS files proves
the old failure and corrected exact comparison. This is local parser evidence,
not proof of NAS apply or runtime acceptance.
## Foundation002 failure and exact reconciliation
Runner017 was installed and plan002 passed. Apply002 created the schema and
recreated Core, then failed `Device Core predecessor service is not healthy`.
Automatic rollback recreated Core again; its acceptance also failed. Canonical
failed ledger80 records `started_apply=true`, `rollback_status=failed:DeployError`
at `2026-09-30T13:45:49+00:00`. Incident archive SHA is
`da1c97fb0fd2ed9f50acf198c0492b27a5d7273009c0a85b9231fd8c60a70222`;
backup is `device-b2-foundation-device-b2-foundation-v1-20260930-002-20260930-164433`.
The archive, journal and seven backup-file digests are pinned in the runner.
The acceptance order was wrong: the strict healthy snapshot ran before the
existing bounded readiness/HTTP checks. The tests now exercise the actual
readiness loop through `starting` to `healthy` for both apply and rollback.
Both cases fail on017 and pass on018. Persistently unhealthy containers still
fail after the existing grace window; image/config/dependency guards are intact.
Historical failed-generation health states were not saved, so `starting` is a
reproduced defect, not a retroactively observed Docker status for this incident.
Read-only SMB observation found all three foundation files and its vault absent.
Public Manager health returned200/ok. These facts do not prove restored database
and runtime. No second application attempt is allowed until exact reconciliation.
`device-b2-foundation-reconciliation` is a separate metadata-only component.
Identity: `device-b2-foundation-reconciliation-v1-20260930-001`.
Its sole payload is `deployment/device-b2-foundation-reconciliation-v1.json`;
builder: `infra/deploy-runner/build_device_b2_reconciliation.py`.
Root is `/volume1/docker/nodedc-device-plane`, with no build or selected services.
Plan and apply independently prove:
- exact failed row/archive and immutable before/schema/backup partition evidence;
- accepted r14 baseline and no different unresolved foundation transition;
- no foundation files, private directory, or any of the three new schema objects;
- readiness, original Core image/config, unchanged other containers, Compose
files and application source.
Apply writes only the descriptor and canonical backup/journal/archive, then
repeats the proof before success. Its rollback removes only that new descriptor;
neither path issues runtime mutations or DDL. Only a complete matching receipt
and applied archive can acknowledge this one failed002 record. The original
failed journal/archive/backup remain immutable. A marker alone, altered history,
another failure, remaining schema/data/keys or runtime drift blocks acceptance.
Ordinary app releases also check this barrier even if no foundation overlay is
present. No generic health/fingerprint or unrelated registry rules are weakened.
After reconciliation, a fresh foundation003 plan/apply may add the original
unchanged YAML and SQL.003 is a new immutable identity;001/002 cannot be replayed.
Preparation of018 or a local test is not production reconciliation acceptance.
Local validation: foundation boundary/negative tests, deterministic artifact,
real archive through runner loader, existing release/network-priority/autodeploy
and Device Plane registry regression. SQL was also executed after all17 existing
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Deterministic data-only receipt for the exact B2 foundation002 incident."""
import argparse
import gzip
import hashlib
import importlib.machinery
import importlib.util
import io
import json
from pathlib import Path
import tarfile
loader = importlib.machinery.SourceFileLoader('b2_reconciliation_builder_runner', str(Path(__file__).with_name('nodedc-deploy')))
spec = importlib.util.spec_from_loader(loader.name, loader)
R = importlib.util.module_from_spec(spec)
loader.exec_module(R)
def build(destination):
data = {
'manifest.env': ('id=' + R.DEVICE_B2_RECON_ID + '\ncomponent=device-b2-foundation-reconciliation\ntype=app-overlay\n').encode(),
'files.txt': (R.DEVICE_B2_RECON_ENTRY + '\n').encode(),
'payload/' + R.DEVICE_B2_RECON_ENTRY: (json.dumps(R.device_b2_reconciliation_descriptor(), indent=2) + '\n').encode(),
}
destination = Path(destination)
destination.parent.mkdir(parents=True, exist_ok=True)
with destination.open('xb') as output:
with gzip.GzipFile(filename='', mode='wb', fileobj=output, mtime=0) as gz:
with tarfile.open(fileobj=gz, mode='w', format=tarfile.PAX_FORMAT) as archive:
for name, value in sorted(data.items()):
member = tarfile.TarInfo(name)
member.size = len(value)
member.mode = 0o644
member.mtime = 0
archive.addfile(member, io.BytesIO(value))
return {'id': R.DEVICE_B2_RECON_ID, 'component': 'device-b2-foundation-reconciliation',
'artifact': str(destination), 'sha256': hashlib.sha256(destination.read_bytes()).hexdigest(),
'entries': [R.DEVICE_B2_RECON_ENTRY], 'services': [], 'build': [], 'runtimeMutation': False}
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--output', required=True)
print(json.dumps(build(parser.parse_args().output), indent=2))
+162 -3
View File
@@ -2962,6 +2962,9 @@ GITEA_SALVAGE_UNSUPPORTED_SCHEMA_TABLES = tuple(
)
COMPONENTS = {
"device-b2-foundation-reconciliation": {
"payload_root": DEVICE_PLANE_ROOT, "artifact_only": True, "services": (),
},
"device-b2-foundation": {
"payload_root": DEVICE_PLANE_ROOT, "compose_root": DEVICE_PLANE_ROOT,
"compose_project": "nodedc-device-plane", "compose_no_deps": True,
@@ -4988,6 +4991,10 @@ def denied_payload_path(component, rel):
def allowed_payload_path(component, rel):
validate_posix_path(rel)
if component == "device-b2-foundation-reconciliation":
if rel in ("deployment", DEVICE_B2_RECON_ENTRY):
return True
die("Device B2 reconciliation accepts only its fixed descriptor")
if component == "device-b2-foundation":
if rel in ("deployment", *DEVICE_B2_ENTRIES):
return True
@@ -11624,6 +11631,8 @@ def load_artifact(artifact, work_dir):
die(f"files.txt entry missing in payload: {rel}")
validate_payload_tree(manifest["component"], payload_dir, entries)
if manifest["component"] == "device-b2-foundation-reconciliation":
validate_device_b2_reconciliation_payload(payload_dir, entries, manifest["id"])
if manifest["component"] == "device-b2-foundation":
validate_device_b2_payload(payload_dir, entries, manifest["id"])
if manifest["component"] == "device-core-network-priority":
@@ -22484,6 +22493,10 @@ def is_platform_provider_catalog_only(entries):
def component_services(component, entries=None):
if component == "device-b2-foundation-reconciliation":
if tuple(entries or ()) != (DEVICE_B2_RECON_ENTRY,):
die("Device B2 reconciliation requires the exact descriptor entry")
return ()
if component == "device-b2-foundation":
if tuple(entries or ()) != DEVICE_B2_ENTRIES:
die("Device B2 foundation requires all three exact entries")
@@ -33321,6 +33334,8 @@ def plan_artifact(artifact):
gitea_salvage_preflight = None
with tempfile.TemporaryDirectory(prefix="plan-", dir=TMP_DIR) as tmp:
manifest, entries, payload_dir = load_artifact(artifact, Path(tmp))
if manifest["component"] == "device-b2-foundation-reconciliation":
preflight_device_b2_reconciliation(payload_dir, entries, manifest["id"])
if manifest["component"] == "device-b2-foundation":
preflight_device_b2(payload_dir, entries, manifest["id"])
print("device_b2_scope=core-only;same-image;build=none;new-ports=none")
@@ -39517,6 +39532,11 @@ process.stdout.write('engine-l2-closed-loop:0.7.0:cas+safe-profile+external-plan
def run_healthchecks(component, entries=None, services=None):
if component == "device-b2-foundation-reconciliation":
if tuple(services or ()) != ():
die("Device B2 reconciliation cannot select services")
preflight_device_b2_reconciliation(DEVICE_PLANE_ROOT, entries, DEVICE_B2_RECON_ID, marker_installed=True)
return
if component == "device-b2-foundation":
if tuple(entries or ()) != DEVICE_B2_ENTRIES or tuple(services or ()) != ("device-control-core",):
die("Device B2 foundation health scope mismatch")
@@ -40700,6 +40720,8 @@ def apply_artifact(artifact):
compose_root = component_compose_root(component)
bootstrap_root = bool(COMPONENTS[component].get("bootstrap_root"))
services = component_services(component, entries)
if component == "device-b2-foundation-reconciliation":
preflight_device_b2_reconciliation(payload_dir, entries, patch_id)
if component == "device-b2-foundation":
device_b2_before = preflight_device_b2(payload_dir, entries, patch_id)
if component == "device-core-network-priority":
@@ -41499,6 +41521,12 @@ def apply_artifact(artifact):
rollback_status = "ok:device-core-autodeploy-bootstrap"
except Exception as rollback_exc:
rollback_status = "failed:" + type(rollback_exc).__name__
elif component == "device-b2-foundation-reconciliation":
try:
rollback_device_b2_reconciliation(root, backup_dir, entries, current_stamp)
rollback_status = "ok:device-b2-reconciliation-marker-only"
except Exception as rollback_exc:
rollback_status = "failed:" + type(rollback_exc).__name__
elif component == "device-core-release-reconciliation":
try:
restore_platform_overlay(root, backup_dir, entries, current_stamp)
@@ -42805,7 +42833,7 @@ def main(argv):
# Additive external VPS management foundation. The payload never contains keys.
DEVICE_B2_ID = 'device-b2-foundation-v1-20260930-002'
DEVICE_B2_ID = 'device-b2-foundation-v1-20260930-003'
DEVICE_B2_DESCRIPTOR = 'deployment/device-b2-foundation-v1.json'
DEVICE_B2_SQL = 'deployment/device-b2-foundation-v1.sql'
DEVICE_B2_OVERRIDE = 'docker-compose.device-b2-foundation.yml'
@@ -42850,11 +42878,14 @@ def validate_device_b2_payload(root, entries, identity):
def device_b2_failed_barrier():
for row in load_state(FAILED_STATE_FILE):
if (row.get('component') == 'device-b2-foundation' and row.get('started_apply')
and row.get('rollback_status') != 'ok:device-b2-foundation'):
and row.get('rollback_status') != 'ok:device-b2-foundation'
and not device_b2_002_reconciled(row)):
die('Device B2 foundation requires failed-state reconciliation')
def device_b2_compose_files(files):
# A failed foundation rollback blocks ordinary releases too, even when the
# old source files were already restored and no overlay remains.
device_b2_failed_barrier()
present = [(DEVICE_PLANE_ROOT / p).exists() or (DEVICE_PLANE_ROOT / p).is_symlink() for p in DEVICE_B2_ENTRIES]
rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'device-b2-foundation']
@@ -43055,6 +43086,9 @@ def validate_installed_device_b2():
def accept_device_b2(before, backup_dir, rollback=False):
# Compose "Started" is not readiness. Both the candidate and a restored
# generation must pass the existing bounded grace + HTTP checks first.
run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES)
current = device_release_runtime_snapshot_v2()
for service, old in before['runtime'].items():
new = current[service]
@@ -43082,7 +43116,6 @@ def accept_device_b2(before, backup_dir, rollback=False):
receipt = read_strict_json(backup_dir / 'device-b2-schema.json','Device B2 schema receipt')
if validate_device_b2_schema(device_b2_schema()) != receipt['schemaSha256']:
die('Device B2 foundation schema changed after migration')
run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES)
print('device_b2_accept='+('rollback' if rollback else 'private-vault+three-tables')+';ports=preserved;image=preserved;scope=core-only')
@@ -43107,6 +43140,132 @@ def rollback_device_b2(root, backup_dir, entries, stamp, before, runtime_started
accept_device_b2(before,backup_dir,rollback=True)
DEVICE_B2_RECON_ID = 'device-b2-foundation-reconciliation-v1-20260930-001'
DEVICE_B2_RECON_ENTRY = 'deployment/device-b2-foundation-reconciliation-v1.json'
DEVICE_B2_002_ID = 'device-b2-foundation-v1-20260930-002'
DEVICE_B2_002_SHA = 'da1c97fb0fd2ed9f50acf198c0492b27a5d7273009c0a85b9231fd8c60a70222'
DEVICE_B2_002_BACKUP = 'device-b2-foundation-device-b2-foundation-v1-20260930-002-20260930-164433'
DEVICE_B2_002_BACKUP_HASHES = {
'device-b2-before.json': '70ba33a7917c75593586758a93ea9c83fb4c0d958544d1bf4d024e7449f684cb',
'device-b2-schema.json': '144b3fb60b46ead20570869452d21dd91871fc7049045b3ee969beb9ad9ac34e',
'manifest.env': '74917c5b06429307d7b875c01971a7e8e01a52d890ea11ba634357821c96cebf',
'files.txt': '83ec615f1fcc5443d7afe89c23b3dcf068f928874d62bc8bfbbc55f04d74bf23',
'existing-files.txt': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
'missing-files.txt': '83ec615f1fcc5443d7afe89c23b3dcf068f928874d62bc8bfbbc55f04d74bf23',
'source-before.tgz': '8d10ddfcb56c0b9e7b3cc4bf39cfcd7623594bbe8d68d1e13bc8115c5796991e',
}
def device_b2_002_failed_row():
return {'artifact': 'nodedc-' + DEVICE_B2_002_ID + '.tgz.20260930-164433',
'backup_id': DEVICE_B2_002_BACKUP, 'component': 'device-b2-foundation',
'failed_at': '2026-09-30T13:45:49+00:00', 'id': DEVICE_B2_002_ID,
'message': 'Device Core predecessor service is not healthy: device-control-core',
'rollback_status': 'failed:DeployError', 'sha256': DEVICE_B2_002_SHA,
'started_apply': True, 'status': 'failed'}
def device_b2_reconciliation_descriptor():
return {'schemaVersion': 'nodedc.device-b2-foundation-reconciliation.v1',
'releaseId': DEVICE_B2_RECON_ID, 'failedReleaseId': DEVICE_B2_002_ID,
'failedSha256': DEVICE_B2_002_SHA, 'backupId': DEVICE_B2_002_BACKUP,
'mode': 'prove-restored-r14;metadata-only;no-runtime-mutation'}
def validate_device_b2_reconciliation_payload(payload, entries, identity):
if tuple(entries or ()) != (DEVICE_B2_RECON_ENTRY,) or identity != DEVICE_B2_RECON_ID:
die('Device B2 reconciliation identity/entry mismatch')
if read_strict_json(payload / DEVICE_B2_RECON_ENTRY, 'Device B2 reconciliation') != device_b2_reconciliation_descriptor():
die('Device B2 reconciliation descriptor mismatch')
def device_b2_002_evidence():
expected = device_b2_002_failed_row()
failures = load_state(FAILED_STATE_FILE)
matching = [r for r in failures if r.get('id') == DEVICE_B2_002_ID or r.get('sha256') == DEVICE_B2_002_SHA]
if matching != [expected]:
die('Device B2 reconciliation failed journal mismatch')
if any(r.get('id') == DEVICE_B2_002_ID or r.get('sha256') == DEVICE_B2_002_SHA for r in load_state(STATE_FILE)):
die('Device B2 failed foundation conflicts with applied journal')
archive = FAILED_DIR / expected['artifact']
if archive.is_symlink() or not archive.is_file() or sha256_file(archive) != DEVICE_B2_002_SHA:
die('Device B2 reconciliation failed archive mismatch')
backup = BACKUPS_DIR / DEVICE_B2_002_BACKUP
if backup.is_symlink() or not backup.is_dir():
die('Device B2 reconciliation backup is missing or unsafe')
for name, digest in DEVICE_B2_002_BACKUP_HASHES.items():
path = backup / name
if path.is_symlink() or not path.is_file() or sha256_file(path) != digest:
die('Device B2 reconciliation backup digest mismatch: ' + name)
existing = read_backup_path_list(backup / 'existing-files.txt')
missing = read_backup_path_list(backup / 'missing-files.txt')
validate_backup_partition(DEVICE_B2_ENTRIES, existing, missing, 'Device B2 reconciliation')
if existing or set(missing) != set(DEVICE_B2_ENTRIES):
die('Device B2 reconciliation backup partition mismatch')
return read_strict_json(backup / 'device-b2-before.json', 'Device B2 incident baseline', max_bytes=256*1024)
def preflight_device_b2_reconciliation(payload, entries, identity, *, marker_installed=False):
validate_device_b2_reconciliation_payload(payload, entries, identity)
marker = DEVICE_PLANE_ROOT / DEVICE_B2_RECON_ENTRY
if not marker_installed and (marker.exists() or marker.is_symlink()):
die('Device B2 reconciliation marker already exists')
if marker_installed and (marker.is_symlink() or not marker.is_file()):
die('Device B2 reconciliation installed marker is unsafe')
before = device_b2_002_evidence()
# Reconciliation cannot mask a different incomplete transition.
for row in load_state(FAILED_STATE_FILE):
if (row.get('component') == 'device-b2-foundation' and row.get('started_apply')
and row.get('rollback_status') != 'ok:device-b2-foundation'
and row != device_b2_002_failed_row()):
die('Device B2 reconciliation found another unresolved foundation')
applied = load_state(STATE_FILE)
releases = [r for r in applied if r.get('component') == 'device-core-release']
if (not releases or releases[-1].get('id') != DEVICE_B2_BASELINE_ID
or releases[-1].get('sha256') != DEVICE_B2_BASELINE_SHA
or any(r.get('component') == 'device-b2-foundation' for r in applied)):
die('Device B2 reconciliation requires the exact restored r14 baseline')
if any((DEVICE_PLANE_ROOT / p).exists() or (DEVICE_PLANE_ROOT / p).is_symlink() for p in DEVICE_B2_ENTRIES):
die('Device B2 reconciliation retains unexpected foundation files')
if DEVICE_B2_SECRET_ROOT.exists() or DEVICE_B2_SECRET_ROOT.is_symlink():
die('Device B2 reconciliation retains unexpected private storage')
if device_b2_schema():
die('Device B2 reconciliation retains unexpected schema; no mutation allowed')
accept_device_b2(before, BACKUPS_DIR / DEVICE_B2_002_BACKUP, rollback=True)
print('device_b2_reconciliation=restored-r14-proven;services=none;build=none;runtime-mutation=none;schema=absent;vault=absent')
return before
def rollback_device_b2_reconciliation(root, backup_dir, entries, stamp):
if tuple(entries or ()) != (DEVICE_B2_RECON_ENTRY,):
die('Device B2 reconciliation rollback scope mismatch')
restore_platform_overlay(root, backup_dir, entries, stamp)
if (root / DEVICE_B2_RECON_ENTRY).exists() or (root / DEVICE_B2_RECON_ENTRY).is_symlink():
die('Device B2 reconciliation rollback left a marker')
def device_b2_002_reconciled(row):
if row != device_b2_002_failed_row():
return False
marker = DEVICE_PLANE_ROOT / DEVICE_B2_RECON_ENTRY
if not marker.exists() and not marker.is_symlink():
return False
if marker.is_symlink() or not marker.is_file():
die('Device B2 reconciliation marker is unsafe')
validate_device_b2_reconciliation_payload(DEVICE_PLANE_ROOT, (DEVICE_B2_RECON_ENTRY,), DEVICE_B2_RECON_ID)
records = [r for r in load_state(STATE_FILE) if r.get('id') == DEVICE_B2_RECON_ID]
if len(records) != 1 or records[0].get('component') != 'device-b2-foundation-reconciliation':
die('Device B2 reconciliation marker lacks its unique applied receipt')
with tempfile.TemporaryDirectory(prefix='device-b2-reconciled-', dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(records[0]), Path(tmp))
if manifest['component'] != 'device-b2-foundation-reconciliation' or manifest['id'] != DEVICE_B2_RECON_ID:
die('Device B2 reconciliation archive owner mismatch')
if sha256_file(payload / DEVICE_B2_RECON_ENTRY) != sha256_file(marker):
die('Device B2 reconciliation installed marker drift')
device_b2_002_evidence() # Historical evidence remains immutable after acknowledgement.
return True
if __name__ == "__main__":
try:
@@ -44,8 +44,9 @@ class Foundation(unittest.TestCase):
# Isolate the YAML/identity guard; no database or SQL execution.
with mock.patch.object(R, 'sha256_file', return_value=R.DEVICE_B2_SQL_SHA):
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, R.DEVICE_B2_ID)
with self.assertRaises(R.DeployError):
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, 'device-b2-foundation-v1-20260930-001')
for old_id in ('device-b2-foundation-v1-20260930-001', 'device-b2-foundation-v1-20260930-002'):
with self.assertRaises(R.DeployError):
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, old_id)
for replacement in ('true', 'null', '0'):
yaml.write_text(R.DEVICE_B2_YAML.replace('create_host_path: false', 'create_host_path: ' + replacement))
with self.subTest(replacement=replacement), self.assertRaises(R.DeployError):
@@ -0,0 +1,276 @@
"""Readiness convergence and metadata-only reconciliation; no Docker required."""
import copy
from contextlib import ExitStack, redirect_stdout, redirect_stderr
import hashlib
import importlib.util
import io
import json
from pathlib import Path
from types import SimpleNamespace
import tempfile
import unittest
from unittest import mock
from test_device_b2_foundation import R
spec = importlib.util.spec_from_file_location('b2_reconciliation_builder', Path(__file__).with_name('build_device_b2_reconciliation.py'))
B = importlib.util.module_from_spec(spec)
spec.loader.exec_module(B)
def baseline_fields():
return {'HostConfig': {'Mounts': []}, 'Config': {'Env': ['PRESERVED=synthetic']}, 'Mounts': [], 'networks': ['private']}
def snapshot(fields):
return {service: {'service': service, 'containerId': service + '-old', 'imageId': 'same-image',
'health': 'healthy', 'running': True, 'status': 'running', 'restartCount': 0,
'runtimeConfigSha256': R.device_release_drift_digest(fields)}
for service in R.DEVICE_RELEASE_INVENTORY}
class Readiness(unittest.TestCase):
def accept_with_startup(self, rollback, unhealthy=False, drift=None):
fields = baseline_fields()
current_fields = copy.deepcopy(fields)
if not rollback:
current_fields['Config']['Env'].append('DEVICE_B2_SECRET_ROOT=' + R.DEVICE_B2_DESTINATION)
current_fields['HostConfig']['Mounts'].append({'Type': 'bind', 'Source': str(R.DEVICE_B2_SECRET_ROOT),
'Target': R.DEVICE_B2_DESTINATION, 'ReadOnly': False})
current_fields['Mounts'].append({'Type': 'bind', 'Source': str(R.DEVICE_B2_SECRET_ROOT),
'Destination': R.DEVICE_B2_DESTINATION, 'RW': True, 'Propagation': 'rprivate'})
before = {'runtime': snapshot(fields), 'compose': {}, 'otherComposeServices': {}, 'installedFiles': {}}
state = {'health': 'starting', 'polls': 0, 'snapshots': 0}
def inspect(command, **kwargs):
self.assertEqual(command[1], 'inspect')
service = command[-1]
if service == 'device-control-core':
state['polls'] += 1
state['health'] = 'unhealthy' if unhealthy else ('starting' if state['polls'] == 1 else 'healthy')
return SimpleNamespace(stdout=state['health'], stderr='', returncode=0)
return SimpleNamespace(stdout='healthy', stderr='', returncode=0)
def samples():
state['snapshots'] += 1
result = {service: {'runtime': copy.deepcopy(row), 'fields': copy.deepcopy(fields)}
for service, row in before['runtime'].items()}
core = result['device-control-core']
core['runtime']['containerId'] = 'new-generation'
core['runtime']['health'] = state['health']
core['fields'] = copy.deepcopy(current_fields)
if drift == 'image': core['runtime']['imageId'] = 'changed-image'
if drift == 'network': core['fields']['networks'] = ['other']
if drift == 'preserved': result['device-postgres']['runtime']['containerId'] = 'unexpected-recreate'
return result
with ExitStack() as stack:
stack.enter_context(mock.patch.object(R, 'compose_service_container_id', side_effect=lambda c, s: s))
stack.enter_context(mock.patch.object(R.subprocess, 'run', side_effect=inspect))
stack.enter_context(mock.patch.object(R.time, 'sleep'))
stack.enter_context(mock.patch.object(R, 'healthcheck_url'))
stack.enter_context(mock.patch.object(R, 'device_release_drift_sample', side_effect=samples))
stack.enter_context(mock.patch.object(R, 'device_release_other_compose_services', return_value={}))
stack.enter_context(mock.patch.object(R, 'collect_exact_files', return_value={}))
stack.enter_context(mock.patch.object(R, 'device_b2_private_directory'))
stack.enter_context(mock.patch.object(R, 'device_b2_schema', return_value=R.DEVICE_B2_EXPECTED_SCHEMA))
stack.enter_context(mock.patch.object(R, 'read_strict_json', return_value={'schemaSha256': R.device_release_drift_digest(R.DEVICE_B2_EXPECTED_SCHEMA)}))
stack.enter_context(redirect_stdout(io.StringIO()))
if unhealthy or drift:
with self.assertRaises(R.DeployError): R.accept_device_b2(before, Path('/synthetic'), rollback=rollback)
else:
R.accept_device_b2(before, Path('/synthetic'), rollback=rollback)
return state
def test_apply_and_rollback_wait_for_healthy_before_strict_snapshot(self):
for rollback in (False, True):
with self.subTest(rollback=rollback):
state = self.accept_with_startup(rollback)
self.assertEqual(state['polls'], 2)
self.assertGreater(state['snapshots'], 0)
def test_persistent_unhealthy_does_not_reach_snapshot_or_accept(self):
for rollback in (False, True):
state = self.accept_with_startup(rollback, unhealthy=True)
self.assertEqual(state['polls'], 60)
self.assertEqual(state['snapshots'], 0)
def test_readiness_never_weakens_image_network_or_preserved_service_guards(self):
for rollback in (False, True):
for drift in ('image', 'network', 'preserved'):
with self.subTest(rollback=rollback, drift=drift):
self.accept_with_startup(rollback, drift=drift)
class Reconciliation(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.live = self.root / 'live'
self.live.mkdir()
self.archive = self.root / 'reconciliation.tgz'
B.build(self.archive)
self.manifest, self.entries, self.payload = R.load_artifact(self.archive, self.root / 'unpack')
def test_real_archive_is_deterministic_data_only_and_has_no_runtime_action(self):
other = self.root / 'second.tgz'
B.build(other)
self.assertEqual(self.archive.read_bytes(), other.read_bytes())
with self.assertRaises(FileExistsError): B.build(other)
self.assertEqual(self.entries, [R.DEVICE_B2_RECON_ENTRY])
self.assertEqual(R.component_services(self.manifest['component'], self.entries), ())
self.assertFalse(R.component_builds(self.manifest['component'], self.entries))
with mock.patch.object(R.subprocess, 'run', side_effect=AssertionError('runtime command forbidden')):
R.run_component_runtime(self.manifest['component'], self.entries, ())
for p in ('secrets/key', '.env', R.DEVICE_B2_SQL, R.DEVICE_B2_OVERRIDE, 'hooks.sh'):
with self.subTest(path=p), self.assertRaises(R.DeployError):
R.allowed_payload_path(self.manifest['component'], p)
for entries in ([], self.entries + ['services/device-control-core']):
with self.assertRaises(R.DeployError): R.component_services(self.manifest['component'], entries)
def test_descriptor_cannot_select_other_incident_or_commands(self):
descriptor = self.payload / R.DEVICE_B2_RECON_ENTRY
for key, value in [('failedReleaseId', 'another'), ('backupId', '../escape'), ('mode', 'restart'), ('command', 'sh')]:
d = R.device_b2_reconciliation_descriptor()
d[key] = value
descriptor.write_text(json.dumps(d))
with self.subTest(key=key), self.assertRaises(R.DeployError):
R.validate_device_b2_reconciliation_payload(self.payload, self.entries, R.DEVICE_B2_RECON_ID)
def proof_context(self, stack, **overrides):
applied = [{'component': 'device-core-release', 'id': R.DEVICE_B2_BASELINE_ID, 'sha256': R.DEVICE_B2_BASELINE_SHA}]
failures = [R.device_b2_002_failed_row()]
stack.enter_context(mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live))
stack.enter_context(mock.patch.object(R, 'DEVICE_B2_SECRET_ROOT', self.live / 'vault'))
stack.enter_context(mock.patch.object(R, 'device_b2_002_evidence', return_value={'proof': 'pinned-backup'}))
stack.enter_context(mock.patch.object(R, 'device_b2_schema', return_value=overrides.get('schema', [])))
stack.enter_context(mock.patch.object(R, 'load_state', side_effect=lambda path: overrides.get('failed', failures) if path == R.FAILED_STATE_FILE else overrides.get('applied', applied)))
return stack.enter_context(mock.patch.object(R, 'accept_device_b2'))
def test_readonly_proof_rejects_remaining_files_vault_schema_and_other_incident(self):
for case in ('good', 'file', 'symlink', 'vault', 'schema', 'newer-release', 'another-failed', 'installed-foundation'):
with self.subTest(case=case), ExitStack() as stack:
changes = {}
target = None
if case in ('file', 'symlink'):
target = self.live / R.DEVICE_B2_OVERRIDE
if case == 'file': target.write_text('retained')
else: target.symlink_to(self.live / 'missing')
if case == 'vault':
target = self.live / 'vault'; target.mkdir()
if case == 'schema': changes['schema'] = R.DEVICE_B2_EXPECTED_SCHEMA
if case == 'newer-release': changes['applied'] = []
if case == 'installed-foundation': changes['applied'] = [{'component': 'device-b2-foundation'}]
if case == 'another-failed': changes['failed'] = [R.device_b2_002_failed_row(), {'component': 'device-b2-foundation', 'started_apply': True, 'id': 'another'}]
accept = self.proof_context(stack, **changes)
stack.enter_context(redirect_stdout(io.StringIO()))
if case == 'good':
R.preflight_device_b2_reconciliation(self.payload, self.entries, R.DEVICE_B2_RECON_ID)
accept.assert_called_once()
self.assertTrue(accept.call_args.kwargs['rollback'])
else:
with self.assertRaises(R.DeployError): R.preflight_device_b2_reconciliation(self.payload, self.entries, R.DEVICE_B2_RECON_ID)
accept.assert_not_called()
if target:
if target.is_dir(): target.rmdir()
else: target.unlink()
def test_marker_alone_cannot_clear_failure_and_other_failed_rows_never_match(self):
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'load_state', return_value=[]):
self.assertFalse(R.device_b2_002_reconciled(R.device_b2_002_failed_row()))
marker = self.live / R.DEVICE_B2_RECON_ENTRY
marker.parent.mkdir()
marker.write_text(json.dumps(R.device_b2_reconciliation_descriptor()))
with self.assertRaises(R.DeployError): R.device_b2_002_reconciled(R.device_b2_002_failed_row())
wrong = R.device_b2_002_failed_row(); wrong['sha256'] = '0'*64
self.assertFalse(R.device_b2_002_reconciled(wrong))
def test_failed_foundation_blocks_ordinary_releases_even_without_overlay(self):
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'load_state', return_value=[R.device_b2_002_failed_row()]):
with self.assertRaises(R.DeployError): R.device_b2_compose_files(())
def test_incident_evidence_checks_exact_journal_archive_and_every_backup_file(self):
failed_dir = self.root/'incident-failed'; failed_dir.mkdir()
backups = self.root/'incident-backups'; backups.mkdir()
backup = backups/R.DEVICE_B2_002_BACKUP; backup.mkdir()
files = {'device-b2-before.json': b'{"runtime":{}}', 'device-b2-schema.json': b'{}',
'manifest.env': b'synthetic', 'files.txt': ('\n'.join(R.DEVICE_B2_ENTRIES)+'\n').encode(),
'existing-files.txt': b'', 'missing-files.txt': ('\n'.join(R.DEVICE_B2_ENTRIES)+'\n').encode(),
'source-before.tgz': b'synthetic-empty-source'}
for name, value in files.items(): (backup/name).write_bytes(value)
archive = failed_dir/R.device_b2_002_failed_row()['artifact']; archive.write_bytes(b'synthetic-archive')
hashes = {name: hashlib.sha256(value).hexdigest() for name, value in files.items()}
with ExitStack() as stack:
for name, value in [('FAILED_DIR', failed_dir), ('BACKUPS_DIR', backups),
('DEVICE_B2_002_SHA', hashlib.sha256(archive.read_bytes()).hexdigest()),
('DEVICE_B2_002_BACKUP_HASHES', hashes)]:
stack.enter_context(mock.patch.object(R, name, value))
failed = [R.device_b2_002_failed_row()]; applied = []
stack.enter_context(mock.patch.object(R, 'load_state', side_effect=lambda p: failed if p == R.FAILED_STATE_FILE else applied))
self.assertEqual(R.device_b2_002_evidence(), {'runtime': {}})
for name, value in files.items():
(backup/name).write_bytes(value+b'changed')
with self.subTest(file=name), self.assertRaises(R.DeployError): R.device_b2_002_evidence()
(backup/name).write_bytes(value)
archive.write_bytes(b'changed')
with self.assertRaises(R.DeployError): R.device_b2_002_evidence()
archive.write_bytes(b'synthetic-archive')
applied.append({'id': R.DEVICE_B2_002_ID})
with self.assertRaises(R.DeployError): R.device_b2_002_evidence()
applied.clear()
failed[0]['rollback_status'] = 'different'
with self.assertRaises(R.DeployError): R.device_b2_002_evidence()
def execute_metadata_apply(self, fail_after_marker=False):
for name in ('inbox', 'applied', 'failed', 'backups', 'state', 'tmp'): (self.root / name).mkdir()
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', self.live),
('DEVICE_B2_SECRET_ROOT', self.live/'vault')]:
stack.enter_context(mock.patch.object(R, name, value))
stack.enter_context(mock.patch.dict(R.COMPONENTS, {'device-b2-foundation-reconciliation': {'payload_root': self.live, 'artifact_only': True, 'services': ()}}))
for name in ('require_root', 'ensure_layout', 'validate_artifact_location'):
stack.enter_context(mock.patch.object(R, name))
for name in ('run_build', 'run_compose', 'prepare_component_runtime'):
stack.enter_context(mock.patch.object(R, name, side_effect=AssertionError('runtime mutation forbidden')))
stack.enter_context(mock.patch.object(R.subprocess, 'run', side_effect=AssertionError('external commands forbidden')))
stack.enter_context(mock.patch.object(R, 'device_b2_002_evidence', return_value={}))
stack.enter_context(mock.patch.object(R, 'device_b2_schema', return_value=[]))
events = []
def accept(*args, **kwargs):
installed = (self.live / R.DEVICE_B2_RECON_ENTRY).exists()
events.append('post' if installed else 'pre')
if fail_after_marker and installed: raise R.DeployError('injected restored runtime drift')
stack.enter_context(mock.patch.object(R, 'accept_device_b2', side_effect=accept))
R.append_jsonl(R.FAILED_STATE_FILE, R.device_b2_002_failed_row())
R.append_jsonl(R.STATE_FILE, {'component': 'device-core-release', 'id': R.DEVICE_B2_BASELINE_ID, 'sha256': R.DEVICE_B2_BASELINE_SHA})
stack.enter_context(redirect_stdout(io.StringIO())); stack.enter_context(redirect_stderr(io.StringIO()))
if fail_after_marker:
with self.assertRaises(R.DeployError): R.apply_artifact(self.archive)
self.assertFalse((self.live/R.DEVICE_B2_RECON_ENTRY).exists())
self.assertEqual(R.load_state(R.FAILED_STATE_FILE)[-1]['rollback_status'], 'ok:device-b2-reconciliation-marker-only')
self.assertEqual(len(R.load_state(R.STATE_FILE)), 1)
else:
R.apply_artifact(self.archive)
receipt = R.load_state(R.STATE_FILE)[-1]
self.assertEqual(receipt['component'], 'device-b2-foundation-reconciliation')
self.assertTrue(R.device_b2_002_reconciled(R.device_b2_002_failed_row()))
R.device_b2_failed_barrier()
self.assertEqual(len(R.load_state(R.FAILED_STATE_FILE)), 1) # Original failure retained.
(R.APPLIED_DIR/receipt['artifact']).write_bytes(b'changed archive')
with self.assertRaises(R.DeployError): R.device_b2_002_reconciled(R.device_b2_002_failed_row())
self.assertEqual(events, ['pre', 'post'])
def test_metadata_apply_uses_real_journal_archive_and_receipt_without_runtime_commands(self):
self.execute_metadata_apply()
def test_metadata_apply_failure_removes_only_new_marker_and_retains_incident(self):
self.execute_metadata_apply(fail_after_marker=True)
if __name__ == '__main__':
unittest.main()