diff --git a/infra/cms-deploy/test_runner.py b/infra/cms-deploy/test_runner.py index d66a71a..966f73b 100644 --- a/infra/cms-deploy/test_runner.py +++ b/infra/cms-deploy/test_runner.py @@ -66,15 +66,30 @@ class CmsRunnerTests(unittest.TestCase): restore.assert_called_once();compose.assert_called_once();accept.assert_called_once_with(before,rollback=True) self.assertEqual(run.call_args.args[0],[str(r.DOCKER),'image','tag','old-id','dc-cms-cms-app']) - def test_existing_device_domain_unchanged(self): + def test_unrelated_domains_unchanged_except_reviewed_r46_extension(self): old=subprocess.check_output(['git','show','27c155276a703dd4fd39385011fc5e3f86afcae4:infra/deploy-runner/nodedc-deploy'],cwd=ROOT,text=True) current=RUNNER.read_text() - def domain(source):return source[source.index('# Device Core outbound automatic deployment.'):source.index('# END GENERATED DEVICE CORE AUTODEPLOY LIBRARY')] - self.assertEqual(domain(old),domain(current)) allowed={'allowed_payload_path','load_artifact','component_services','plan_artifact','apply_artifact','run_healthchecks','main'} + # The separately reviewed r46 recovery now changes these Device entry + # points. Its exact identity, v1/v2 compatibility and queue transitions + # are tested in device-core-deploy/test_r46_reconciliation.py. + allowed.update({'device_release_predecessor','validate_device_release_reconciliation_payload', + 'preflight_device_release_reconciliation','device_release_capture_field_digests', + 'device_release_runtime_drift_message','preflight_device_release','accept_device_release', + 'DeviceAutodeployInstaller','device_autodeploy_library'}) old_functions={n.name:ast.dump(n,include_attributes=False) for n in ast.parse(old).body if isinstance(n,(ast.FunctionDef,ast.ClassDef))} current_functions={n.name:ast.dump(n,include_attributes=False) for n in ast.parse(current).body if isinstance(n,(ast.FunctionDef,ast.ClassDef))} for name,node in old_functions.items(): if name not in allowed:self.assertEqual(current_functions[name],node,name) + def methods(source): + cls=next(n for n in ast.parse(source).body if isinstance(n,ast.ClassDef) and n.name=='DeviceAutodeployInstaller') + return {n.name:ast.dump(n,include_attributes=False) for n in cls.body if isinstance(n,ast.FunctionDef)} + before,after=methods(old),methods(current) + for name,node in before.items(): + if name!='receipt':self.assertEqual(after[name],node,name) + # None of the CMS runtime changes as part of Device recovery. + baseline=subprocess.check_output(['git','show','6cf7a91:infra/deploy-runner/nodedc-deploy'],cwd=ROOT,text=True) + def cms(source):return source.split('# BEGIN GENERATED CMS DEPLOYMENT\n',1)[1].split('# END GENERATED CMS DEPLOYMENT\n',1)[0] + self.assertEqual(cms(baseline),cms(current)) if __name__=='__main__':unittest.main() diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index 5083416..2c16a92 100755 --- a/infra/deploy-runner/nodedc-deploy +++ b/infra/deploy-runner/nodedc-deploy @@ -5053,7 +5053,7 @@ def allowed_payload_path(component, rel): return True die("Device Core drift audit accepts only its exact descriptor") if component == "device-core-release-reconciliation": - if rel in ("deployment", DEVICE_RELEASE_RECONCILIATION_ENTRY, DEVICE_RELEASE_RECONCILIATION_V2_ENTRY): + if rel in ("deployment", DEVICE_RELEASE_RECONCILIATION_ENTRY, DEVICE_RELEASE_RECONCILIATION_V2_ENTRY, DEVICE_R46_RECON_ENTRY): return True die("Device Core reconciliation accepts only its exact descriptor") if component == "device-core-release": @@ -22581,7 +22581,7 @@ def component_services(component, entries=None): die("Device Core drift audit requires the exact descriptor entry") return () if component == "device-core-release-reconciliation": - if tuple(entries or ()) not in ((DEVICE_RELEASE_RECONCILIATION_ENTRY,), (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,)): + if tuple(entries or ()) not in ((DEVICE_RELEASE_RECONCILIATION_ENTRY,), (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,), (DEVICE_R46_RECON_ENTRY,)): die("Device Core reconciliation requires the exact descriptor entry") return () if component == "device-core-release": @@ -32715,7 +32715,7 @@ def device_release_predecessor(candidate): applied = load_state(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 not device_release_r5_reconciled(row): + if not device_release_r5_reconciled(row) and not device_r46_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"] installed = DEVICE_PLANE_ROOT / DEVICE_RELEASE_ENTRY @@ -32878,6 +32878,8 @@ def device_release_reconciliation_v2_descriptor(): def validate_device_release_reconciliation_payload(payload, entries, patch_id): + if tuple(entries) == (DEVICE_R46_RECON_ENTRY,): + return validate_device_r46_payload(payload, entries, patch_id) if tuple(entries) == (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,): if (patch_id != DEVICE_RELEASE_RECONCILIATION_V2_ID or read_strict_json(payload / DEVICE_RELEASE_RECONCILIATION_V2_ENTRY, "Device Core reconciliation v2") != device_release_reconciliation_v2_descriptor()): @@ -32930,6 +32932,8 @@ def device_release_r5_evidence(): def preflight_device_release_reconciliation(payload, entries, patch_id, *, marker_installed=False): + if tuple(entries) == (DEVICE_R46_RECON_ENTRY,): + return preflight_device_r46_reconciliation(payload, entries, patch_id, marker_installed=marker_installed) validate_device_release_reconciliation_payload(payload, entries, patch_id) v2 = tuple(entries) == (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,) marker = DEVICE_PLANE_ROOT / entries[0] @@ -33181,7 +33185,7 @@ def device_release_field_digests(fields): return result -def device_release_capture_field_digests(expected_runtime): +def device_release_capture_field_digests(expected_runtime, version=2): """Bind diagnostics to the already checked container generation and digest.""" observations = device_release_drift_sample() if set(observations) != set(expected_runtime): @@ -33189,7 +33193,7 @@ def device_release_capture_field_digests(expected_runtime): result = {} for service, sample in observations.items(): expected = expected_runtime[service] - fields = device_release_mounts_v2(sample["fields"]) + fields = (device_release_fields_v3 if version == 3 else device_release_mounts_v2)(sample["fields"]) if (sample["runtime"]["containerId"] != expected["containerId"] or sample["runtime"]["imageId"] != expected["imageId"] or device_release_drift_digest(fields) != expected["runtimeConfigSha256"]): @@ -33213,7 +33217,7 @@ def device_release_runtime_drift_message(before, current, service): or not isinstance(value, str) or not re.fullmatch(r"[a-f0-9]{64}", value) for key, value in expected.items()): die("Device Core saved runtime field digests are invalid") - actual = device_release_capture_field_digests(current)[service] + actual = device_release_capture_field_digests(current, before.get("runtimeFingerprintVersion", 1))[service] changed = sorted(key for key in set(expected) | set(actual) if expected.get(key) != actual.get(key)) report["changedFields"] = [{"path": key, "expectedSha256": expected.get(key), "actualSha256": actual.get(key)} for key in changed[:64]] @@ -33285,11 +33289,11 @@ def preflight_device_release(payload, entries, patch_id): 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, read_only=True) run_healthchecks("device-core-release", entries, DEVICE_RELEASE_SERVICES) - before = device_release_runtime_snapshot_v2() - field_digests = device_release_capture_field_digests(before) + before = device_release_runtime_snapshot_v3() + field_digests = device_release_capture_field_digests(before, 3) validate_installed_device_b2() compose = {str(p): sha256_file(p) for p in component_compose_files("device-core-release")} - return {"runtimeFingerprintVersion": 2, "descriptor": d, "predecessor": predecessor["releaseId"] if predecessor else "manager-v13/core-v4/edge-v4", + return {"runtimeFingerprintVersion": 3, "descriptor": d, "predecessor": predecessor["releaseId"] if predecessor else "manager-v13/core-v4/edge-v4", "runtime": before, "runtimeFieldDigests": field_digests, "compose": compose, "otherComposeServices": device_release_other_compose_services(), "installedFiles": collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES if predecessor else DEVICE_RELEASE_ENTRIES[:-1], "Device Core rollback baseline")} @@ -33297,9 +33301,9 @@ def preflight_device_release(payload, entries, patch_id): def accept_device_release(before, *, rollback=False): version = before.get("runtimeFingerprintVersion", 1) - if type(version) is not int or version not in (1, 2): + if type(version) is not int or version not in (1, 2, 3): die("Device Core release runtime fingerprint version mismatch") - current = device_release_runtime_snapshot_v2() if version == 2 else device_release_runtime_snapshot() + current = (device_release_runtime_snapshot_v3 if version == 3 else device_release_runtime_snapshot_v2 if version == 2 else device_release_runtime_snapshot)() for service, old in before["runtime"].items(): new = current[service] if service not in DEVICE_RELEASE_SERVICES: @@ -39646,7 +39650,8 @@ 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") - identity = DEVICE_RELEASE_RECONCILIATION_V2_ID if tuple(entries or ()) == (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,) else DEVICE_RELEASE_RECONCILIATION_ID + identity = (DEVICE_R46_RECON_ID if tuple(entries or ()) == (DEVICE_R46_RECON_ENTRY,) else + DEVICE_RELEASE_RECONCILIATION_V2_ID if tuple(entries or ()) == (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,) else DEVICE_RELEASE_RECONCILIATION_ID) preflight_device_release_reconciliation(DEVICE_PLANE_ROOT, entries, identity, marker_installed=True) return if component == "device-core-release": @@ -42390,6 +42395,8 @@ class DeviceAutodeployInstaller: return 'ambiguous', 'canonical-archive-or-backup-mismatch' if applied and record.get('status') == 'ok': outcome = 'deployed' + elif failed and device_r46_reconciled(record): + return 'rolled-back', 'canonical-reconciled:' + DEVICE_R46_RECON_ID elif failed and record.get('rollback_status') == 'ok:device-core-release': outcome = 'rolled-back' else: @@ -42634,6 +42641,30 @@ def device_autodeploy_library(): self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity)) self.transaction(apply) + def reconcile_r46(self, identity, *, digest, artifact, receipt): + """Exact terminal blocked -> failed recovery after canonical proof. + + This never makes the failed artifact ready again. The caller verifies + the immutable failed evidence and the separate successful recovery. + """ + sha = 'e30a6dd2a1eae306d811977188f5d118aefed4ab' + expected_receipt = 'canonical-reconciled:device-core-release-r46-reconciliation-v1-20261105-001' + if (type(identity) is not int or identity != 46 + or digest != 'b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba' + or artifact != 'nodedc-device-core-release-v1-r46-'+sha+'.tgz' + or receipt != expected_receipt): + raise QueueError('r46_reconciliation_identity_mismatch') + def apply(): + row = self.db.execute('SELECT * FROM runs WHERE id=?', (identity,)).fetchone() + if row is None or tuple(row[k] for k in ('number','sha','event','branch','workflow','digest','artifact')) != (39,sha,'push','main',WORKFLOW,digest,artifact): + raise QueueError('r46_reconciliation_row_mismatch') + if row['phase'] == 'failed' and row['receipt'] == receipt: + return + if row['phase'] != 'blocked' or row['receipt'] != 'canonical-rollback-unconfirmed': + raise QueueError('r46_reconciliation_predecessor_mismatch') + self.db.execute("UPDATE runs SET phase='failed',receipt=? WHERE id=?", (receipt,identity)) + self.transaction(apply) + def snapshot(self): return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")] @@ -42907,6 +42938,13 @@ def device_autodeploy_library(): def reconcile(self): for row in self.queue.snapshot(): + if row['phase'] == 'blocked': + outcome, receipt = self.installer.receipt(row) + if outcome == 'rolled-back': + self.queue.reconcile_r46(row['id'], digest=row['digest'], artifact=row['artifact'], receipt=receipt) + elif outcome != 'ambiguous': + raise QueueError('blocked_run_requires_exact_recovery') + continue if row['phase'] != 'deploying': continue outcome, receipt = self.installer.receipt(row) @@ -45031,6 +45069,232 @@ def cms_autodeploy_library(): return DeploymentQueue, GiteaSource, Controller, (QueueError, SourceError) # END GENERATED CMS DEPLOYMENT +# BEGIN GENERATED DEVICE R46 RECOVERY +"""Versioned DNS representation fingerprint and exact r46 evidence-only recovery. + +Embedded into the root-owned runner. No production code is imported from SMB. +Historical v1/v2 hashes are never reinterpreted without an exact preimage proof. +""" +DEVICE_R46_EVIDENCE = {'backupHashes': {'device-release-before.json': '52927379518030d1e979d897e5cb298481d81a78fb694c5ab68896bfeb8a64d4', 'existing-files.txt': '4d02728c991e4666425d968497d3540ad95802de055db4f899411ce34e526b5a', 'files.txt': '4d02728c991e4666425d968497d3540ad95802de055db4f899411ce34e526b5a', 'manifest.env': 'c126a1df2b28d0474e80727e5716311ea6b9aa5702f6b76e9d4742205d87ba62', 'missing-files.txt': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'source-before.tgz': 'dc40d86d52be8f7e02fb7ec0928da371e37f813676bba182fb883212cc7ec967'}, 'cms': [{'backupSha256': '1156f7bdc0313cb4ad8f2541cbe260e965784201b18baacb548480ee6add902d', 'row': {'applied_at': '2026-11-05T10:32:58+00:00', 'artifact': 'nodedc-dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1.tgz', 'backup_id': 'dc-cms-release-dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1-20261105-133137', 'component': 'dc-cms-release', 'id': 'dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1', 'sha256': 'dfd7bbc8753af8b6693253a5a7030995fc6745e541e5206ca1e708bf17555a5d', 'status': 'ok'}}, {'backupSha256': '6a800c80d6cd533bf7d31745baa20ab9912ac9c93f1e9febbe19a61006650547', 'row': {'applied_at': '2026-11-05T10:35:39+00:00', 'artifact': 'nodedc-dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835.tgz', 'backup_id': 'dc-cms-release-dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835-20261105-133344', 'component': 'dc-cms-release', 'id': 'dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835', 'sha256': 'd69852e99b251310bc96ec88dcc89d9d16ca704c49f35d8a168c2835440652b0', 'status': 'ok'}}, {'backupSha256': '2b96d060d5aee54998dabb1c432fe495469cebc92a59b859ff00a0c1183690ca', 'row': {'applied_at': '2026-11-05T10:54:15+00:00', 'artifact': 'nodedc-dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3.tgz', 'backup_id': 'dc-cms-release-dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3-20261105-135303', 'component': 'dc-cms-release', 'id': 'dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3', 'sha256': '88a09153b860280c0a28c51e13bbe8d68cb39e7030ce2ba70bc9a0bf8a367c43', 'status': 'ok'}}], 'failedRow': {'artifact': 'nodedc-device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab.tgz.20261105-132438', 'backup_id': 'device-core-release-device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab-20261105-132438', 'component': 'device-core-release', 'failed_at': '2026-11-05T10:30:32+00:00', 'id': 'device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab', 'message': 'Device Core release runtime configuration drift: device-control-core; field_evidence={"actualSha256":"103d405d730b8de86f1c83f4aa5b31f99e1cfc04de76e48bbb4dbab54149b018","changedFields":[{"actualSha256":"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b","expectedSha256":"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945","path":"HostConfig.Dns"},{"actualSha256":"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b","expectedSha256":"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945","path":"HostConfig.DnsOptions"},{"actualSha256":"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b","expectedSha256":"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945","path":"HostConfig.DnsSearch"}],"evidence":"captured","expectedSha256":"37c24299b8eeede7707905a435e99360de08eb2a852d1f4750db353efa17c7b2","schema":"nodedc.device-core.runtime-drift-fields.v1","service":"device-control-core","truncated":false}', 'rollback_status': 'failed:DeployError', 'sha256': 'b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba', 'started_apply': True, 'status': 'failed'}, 'predecessor': 'device-core-release-v1-r38-dcb0c76ac8e9403c05cc64e9cdde5ebf859f2766'} +DEVICE_R46_RECON_ID = 'device-core-release-r46-reconciliation-v1-20261105-001' +DEVICE_R46_RECON_ENTRY = 'deployment/device-core-release-r46-reconciliation-v1.json' +DEVICE_DNS_FIELDS = ('Dns', 'DnsOptions', 'DnsSearch') + + +def device_release_fields_v3(fields): + result = device_release_mounts_v2(fields) + host = result['HostConfig'] + for key in DEVICE_DNS_FIELDS: + if key not in host: + die('Device Core v3 DNS field is missing') + value = host[key] + if value is None: + host[key] = [] + elif not isinstance(value, list) or any(not isinstance(v, str) for v in value): + die('Device Core v3 DNS field is malformed') + return result + + +def device_release_runtime_snapshot_v3(): + result = {} + for service, sample in device_release_drift_sample().items(): + row = dict(sample['runtime']) + if not row['running'] or row['health'] not in (None, 'healthy'): + die('Device Core predecessor service is not healthy: ' + service) + row['runtimeConfigSha256'] = device_release_drift_digest(device_release_fields_v3(sample['fields'])) + result[service] = row + return result + + +def device_r46_dns_proof(fields, expected): + device_release_fields_v3(fields) # Validate, without altering the v2 preimage. + candidate = device_release_mounts_v2(fields) + if not isinstance(expected, str) or not re.fullmatch('[a-f0-9]{64}', expected): + die('Device Core r46 saved digest is invalid') + if any(candidate['HostConfig'][k] not in (None, []) for k in DEVICE_DNS_FIELDS): + die('Device Core r46 proof requires empty DNS settings') + for checked, values in enumerate(itertools.product((None, []), repeat=3), 1): + for key, value in zip(DEVICE_DNS_FIELDS, values): + candidate['HostConfig'][key] = value + if device_release_drift_digest(candidate) == expected: + return checked + die('Device Core r46 runtime differs beyond empty DNS representation') + + +def device_r46_descriptor(): + e = DEVICE_R46_EVIDENCE + return {'schemaVersion': 'nodedc.device-core.r46-reconciliation.v1', + 'releaseId': DEVICE_R46_RECON_ID, 'failedReleaseId': e['failedRow']['id'], + 'failedSha256': e['failedRow']['sha256'], 'backupId': e['failedRow']['backup_id'], + 'runtimeFingerprintVersion': 3, 'mode': 'prove-restored-baseline-empty-dns-only', + 'cmsSuccessor': e['cms'][-1]['row']['id']} + + +def validate_device_r46_payload(payload, entries, identity): + if tuple(entries or ()) != (DEVICE_R46_RECON_ENTRY,) or identity != DEVICE_R46_RECON_ID: + die('Device Core r46 reconciliation identity/entry mismatch') + marker = payload / DEVICE_R46_RECON_ENTRY + expected = (json.dumps(device_r46_descriptor(), sort_keys=True, indent=2) + '\n').encode() + if marker.is_symlink() or not marker.is_file() or marker.read_bytes() != expected: + die('Device Core r46 reconciliation descriptor mismatch') + + +def device_r46_evidence(): + e = DEVICE_R46_EVIDENCE + row = e['failedRow'] + records = [r for r in load_state(FAILED_STATE_FILE) + if r.get('id') == row['id'] or r.get('sha256') == row['sha256']] + if records != [row] or any(r.get('id') == row['id'] or r.get('sha256') == row['sha256'] + for r in load_state(STATE_FILE)): + die('Device Core r46 failed receipt mismatch') + archive = FAILED_DIR / row['artifact'] + if archive.is_symlink() or not archive.is_file() or sha256_file(archive) != row['sha256']: + die('Device Core r46 failed archive mismatch') + backup = BACKUPS_DIR / row['backup_id'] + if backup.is_symlink() or not backup.is_dir(): + die('Device Core r46 backup is unsafe') + for name, digest in e['backupHashes'].items(): + path = backup / name + if path.is_symlink() or not path.is_file() or sha256_file(path) != digest: + die('Device Core r46 backup digest mismatch: ' + name) + before = read_strict_json(backup / 'device-release-before.json', 'Device Core r46 backup', max_bytes=256*1024) + if before.get('runtimeFingerprintVersion') != 2 or before.get('predecessor') != e['predecessor']: + die('Device Core r46 predecessor/version mismatch') + 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 r46 reconciliation') + if missing: + die('Device Core r46 backup partition mismatch') + with tempfile.TemporaryDirectory(prefix='device-r46-evidence-', dir=TMP_DIR) as tmp: + materialize_backup_tree(backup / 'source-before.tgz', Path(tmp), set(existing)) + if collect_exact_files(Path(tmp), existing, 'Device Core r46 source backup') != before['installedFiles']: + die('Device Core r46 source/runtime evidence conflict') + return before + + +def device_r46_cms_evidence(): + """Read only the three exact accepted CMS successors, not arbitrary drift.""" + evidence = DEVICE_R46_EVIDENCE['cms'] + applied = load_state(STATE_FILE) + failed = load_state(FAILED_STATE_FILE) + backups = [] + for item in evidence: + row = item['row'] + if [r for r in applied if r.get('id') == row['id'] or r.get('sha256') == row['sha256']] != [row]: + die('Device Core r46 CMS successor receipt mismatch') + if any(r.get('id') == row['id'] or r.get('sha256') == row['sha256'] for r in failed): + die('Device Core r46 CMS successor has conflicting receipt') + backup = BACKUPS_DIR / row['backup_id'] + path = backup / 'cms-runtime-before.json' + if (backup.is_symlink() or not backup.is_dir() or path.is_symlink() or not path.is_file() + or sha256_file(path) != item['backupSha256']): + die('Device Core r46 CMS successor backup mismatch') + before = read_strict_json(path, 'Device Core r46 CMS backup', max_bytes=2*1024*1024) + with tempfile.TemporaryDirectory(prefix='device-r46-cms-', dir=TMP_DIR) as tmp: + manifest, entries, payload = load_artifact(device_release_applied_archive(row), Path(tmp)) + if manifest['component'] != 'dc-cms-release' or manifest['id'] != row['id']: + die('Device Core r46 CMS archive identity mismatch') + descriptor = validate_cms_release_payload(payload, entries, row['id']) + if descriptor != before['descriptor']: + die('Device Core r46 CMS source/backup identity mismatch') + backups.append(before) + for previous, current in zip(backups, backups[1:]): + if (current['predecessor'] != previous['descriptor']['sourceCommit'] + or current['otherServices'] != previous['otherServices']): + die('Device Core r46 CMS successor chain mismatch') + return backups + + +def device_r46_other_services(before, cms_backups): + # A new CMS container is permitted only after proving the exact r47/r49/r50 + # chain and current r50 app bytes, health, config and all unrelated services. + latest = cms_backups[-1] + if cms_installed_release() != latest['descriptor']: + die('Device Core r46 requires the exact accepted CMS successor') + cms_healthchecks() + runtime = cms_runtime_snapshot_v2() + if (runtime['configSha256'] != latest['runtime']['configSha256'] + or runtime['imageRef'] != latest['runtime']['imageRef'] + or runtime['id'] == latest['runtime']['id']): + die('Device Core r46 CMS configuration/generation drift') + actual, metadata = cms_application_inventory() + if (metadata != latest['installedMetadata'] or cms_foundation() != latest['foundation'] + or cms_image_files(runtime['id']) != {k: v for k, v in actual.items() if k not in CMS_DEPENDENCY_FILES} + or cms_other_services() != latest['otherServices']): + die('Device Core r46 CMS source or preserved services differ') + old_id = cms_backups[0]['runtime']['id'] + saved = before['otherComposeServices'] + current = device_release_other_compose_services() + if old_id not in saved or runtime['id'] not in current or old_id in current: + die('Device Core r46 CMS predecessor container identity mismatch') + unchanged = {k: v for k, v in saved.items() if k != old_id} + if (any(cms_backups[0]['otherServices'].get(k) != v for k, v in unchanged.items()) + or {k: v for k, v in current.items() if k != runtime['id']} != unchanged): + die('Device Core r46 changed an unrelated Compose service') + return current + + +def device_r46_restored_baseline(before): + if before.get('runtimeFingerprintVersion') != 2 or set(before['runtime']) != set(DEVICE_RELEASE_INVENTORY): + die('Device Core r46 requires the exact v2 inventory') + samples = [device_release_drift_sample() for _ in range(3)] + if any(sample != samples[0] for sample in samples): + die('Device Core r46 runtime changed during reconciliation') + baseline = json.loads(json.dumps(before)) + baseline['runtimeFingerprintVersion'] = 3 + baseline.pop('runtimeFieldDigests', None) # Historical v2 diagnostics stay in the immutable backup. + for service in DEVICE_RELEASE_INVENTORY: + sample = samples[0][service] + row, fields, old = sample['runtime'], sample['fields'], before['runtime'][service] + if (not row['running'] or row['health'] not in (None, 'healthy') or row['imageId'] != old['imageId'] + or row['runtimeConfigSha256'] != device_release_drift_digest(fields)): + die('Device Core r46 image/health/evidence mismatch: ' + service) + v2 = dict(row, runtimeConfigSha256=device_release_drift_digest(device_release_mounts_v2(fields))) + if service not in DEVICE_RELEASE_SERVICES and v2 != old: + die('Device Core r46 preserved service differs: ' + service) + device_r46_dns_proof(fields, old['runtimeConfigSha256']) + baseline['runtime'][service]['runtimeConfigSha256'] = device_release_drift_digest(device_release_fields_v3(fields)) + return baseline + + +def preflight_device_r46_reconciliation(payload, entries, identity, *, marker_installed=False): + require_root() + validate_device_r46_payload(payload, entries, identity) + marker = DEVICE_PLANE_ROOT / DEVICE_R46_RECON_ENTRY + if not marker_installed and (marker.exists() or marker.is_symlink()): + die('Device Core r46 marker already exists') + before = device_r46_evidence() + baseline = device_r46_restored_baseline(before) + baseline['otherComposeServices'] = device_r46_other_services(before, device_r46_cms_evidence()) + run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES) + accept_device_release(baseline, rollback=True) + print('device_r46_reconciliation=exact-v2-sha;dns-empty-only;samples=3;fingerprint=v3;' + 'cms-successor=r50;services=none;build=none;runtime-mutation=none') + return baseline + + +def device_r46_reconciled(row): + if row != DEVICE_R46_EVIDENCE['failedRow']: + return False + records = [r for r in load_state(STATE_FILE) if r.get('id') == DEVICE_R46_RECON_ID] + if not records: + return False # Marker alone, including in-progress apply, grants nothing. + if (len(records) != 1 or records[0].get('component') != 'device-core-release-reconciliation' + or records[0].get('status') != 'ok'): + die('Device Core r46 reconciliation receipt mismatch') + validate_device_r46_payload(DEVICE_PLANE_ROOT, (DEVICE_R46_RECON_ENTRY,), DEVICE_R46_RECON_ID) + with tempfile.TemporaryDirectory(prefix='device-r46-marker-', dir=TMP_DIR) as tmp: + manifest, entries, payload = load_artifact(device_release_applied_archive(records[0]), Path(tmp)) + if manifest['component'] != 'device-core-release-reconciliation' or manifest['id'] != DEVICE_R46_RECON_ID: + die('Device Core r46 reconciliation archive identity mismatch') + validate_device_r46_payload(payload, entries, manifest['id']) + device_r46_evidence() + device_r46_cms_evidence() + return True + +# END GENERATED DEVICE R46 RECOVERY + + def main(argv): if argv == ["--dc-cms-autodeploy-tick"]: return cms_autodeploy_tick() diff --git a/infra/deploy-runner/test_device_core_mount_order.py b/infra/deploy-runner/test_device_core_mount_order.py index e3c062e..68e8ec3 100644 --- a/infra/deploy-runner/test_device_core_mount_order.py +++ b/infra/deploy-runner/test_device_core_mount_order.py @@ -152,21 +152,21 @@ class MountOrderTests(unittest.TestCase): new['descriptor'] = {'releaseId':'fixture','sourceCommit':'a'*40} stack.enter_context(mock.patch.object(R,'docker_json',side_effect=lambda args,label:[{'Id':new['runtime'][args[-1].split('/')[1].split(':')[0]]['imageId']}])) with redirect_stdout(io.StringIO()):R.accept_device_release(new) - for version in [True,0,3,'2']: + for version in [True,0,4,'2']: with self.subTest(version=version),self.assertRaisesRegex(R.DeployError,'version mismatch'):R.accept_device_release({**before,'runtimeFingerprintVersion':version}) - def test_preflight_records_v2_for_new_normal_release(self): + def test_preflight_records_v3_for_new_normal_release(self): with ExitStack() as stack: - for name,value in [('validate_device_release_payload',{}),('device_release_predecessor',None),('collect_exact_files',{}),('component_compose_files',()),('device_release_other_compose_services',{}),('device_release_runtime_snapshot_v2',runtime())]: + for name,value in [('validate_device_release_payload',{}),('device_release_predecessor',None),('collect_exact_files',{}),('component_compose_files',()),('device_release_other_compose_services',{}),('device_release_runtime_snapshot_v3',runtime())]: stack.enter_context(mock.patch.object(R,name,return_value=value)) for name in ['validate_device_manager_control_plane_runtime','run_healthchecks']: stack.enter_context(mock.patch.object(R,name)) legacy = stack.enter_context(mock.patch.object(R,'device_release_runtime_snapshot')) detail = stack.enter_context(mock.patch.object(R,'device_release_capture_field_digests',return_value={'device-manager':{'Config.Env':'a'*64}})) before = R.preflight_device_release(self.root,R.DEVICE_RELEASE_ENTRIES,'id') - self.assertEqual(before['runtimeFingerprintVersion'],2);legacy.assert_not_called() + self.assertEqual(before['runtimeFingerprintVersion'],3);legacy.assert_not_called() self.assertEqual(before['runtimeFieldDigests'],{'device-manager':{'Config.Env':'a'*64}}) - detail.assert_called_once_with(before['runtime']) + detail.assert_called_once_with(before['runtime'],3) def test_preflight_and_post_health_dispatch_v2_only_with_exact_identity(self): old = samples_fixture();before = evidence_fixture(old);current = reorder(old) diff --git a/infra/deploy-runner/test_device_core_r46_evidence.py b/infra/deploy-runner/test_device_core_r46_evidence.py new file mode 100644 index 0000000..21cf231 --- /dev/null +++ b/infra/deploy-runner/test_device_core_r46_evidence.py @@ -0,0 +1,115 @@ +"""r46 immutable evidence, v3 acceptance and marker-only runtime boundary.""" +import copy +from contextlib import ExitStack +import json +from pathlib import Path +import tarfile +import tempfile +import unittest +from unittest.mock import patch +from test_device_core_release import R, fixture, runtime + + +class R46EvidenceTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + + def evidence(self, stack): + e = copy.deepcopy(R.DEVICE_R46_EVIDENCE) + failed, backups, source = (self.root / p for p in ('failed', 'backups', 'source')) + for p in (failed, backups, source): + p.mkdir() + fixture(source) + backup = backups / e['failedRow']['backup_id'] + backup.mkdir() + entries = R.DEVICE_RELEASE_ENTRIES + before = {'runtimeFingerprintVersion': 2, 'predecessor': e['predecessor'], + 'installedFiles': R.collect_exact_files(source, entries, 'fixture')} + (backup / 'device-release-before.json').write_text(json.dumps(before)) + for name in ('existing-files.txt', 'files.txt'): + (backup / name).write_text('\n'.join(entries) + '\n') + (backup / 'missing-files.txt').write_text('') + (backup / 'manifest.env').write_text('fixture') + with tarfile.open(backup / 'source-before.tgz', 'w:gz') as tar: + for entry in entries: + tar.add(source / entry, arcname=entry) + archive = failed / e['failedRow']['artifact'] + archive.write_bytes(b'exact failed archive') + e['failedRow']['sha256'] = R.sha256_file(archive) + e['backupHashes'] = {p.name: R.sha256_file(p) for p in backup.iterdir()} + for name, value in [('DEVICE_R46_EVIDENCE', e), ('TMP_DIR', self.root), + ('FAILED_DIR', failed), ('BACKUPS_DIR', backups)]: + stack.enter_context(patch.object(R, name, value)) + ledger = stack.enter_context(patch.object(R, 'load_state', side_effect=lambda p: [e['failedRow']] if p == R.FAILED_STATE_FILE else [])) + return e, before, backup, archive, ledger + + def test_exact_receipt_backup_and_source_evidence(self): + with ExitStack() as stack: + e, before, backup, archive, ledger = self.evidence(stack) + self.assertEqual(R.device_r46_evidence(), before) + for path in [archive, *backup.iterdir()]: + old = path.read_bytes() + path.write_bytes(old + b'changed') + with self.subTest(path=path.name), self.assertRaises(R.DeployError): + R.device_r46_evidence() + path.write_bytes(old) + ledger.side_effect = lambda p: [e['failedRow']] + with self.assertRaisesRegex(R.DeployError, 'receipt mismatch'): + R.device_r46_evidence() + + def test_hash_consistent_but_conflicting_backup_is_rejected(self): + with ExitStack() as stack: + e, before, backup, _, _ = self.evidence(stack) + before['installedFiles']['package.json'] = 'f' * 64 + target = backup / 'device-release-before.json' + target.write_text(json.dumps(before)) + e['backupHashes'][target.name] = R.sha256_file(target) + with self.assertRaisesRegex(R.DeployError, 'source/runtime evidence conflict'): + R.device_r46_evidence() + + def test_v3_acceptance_preserves_images_database_topology_and_source(self): + old = runtime() + before = {'runtimeFingerprintVersion': 3, 'runtime': old, 'compose': {}, + 'otherComposeServices': {}, 'installedFiles': {}} + with ExitStack() as stack: + stack.enter_context(patch.object(R, 'DEVICE_PLANE_ROOT', self.root / 'live')) + for name, value in [('component_compose_files', ()), ('collect_exact_files', {}), + ('device_release_other_compose_services', {}), + ('validate_device_manager_control_plane_runtime', None), + ('validate_installed_device_b2', None)]: + stack.enter_context(patch.object(R, name, return_value=value)) + current = stack.enter_context(patch.object(R, 'device_release_runtime_snapshot_v3', return_value=old)) + R.accept_device_release(before, rollback=True) + for service, key, value in [('device-manager', 'imageId', 'wrong-image'), + ('device-control-core', 'runtimeConfigSha256', 'wrong-config'), + ('device-postgres', 'containerId', 'recreated'), + ('device-gateway', 'restartCount', 1), + ('device-backhaul-target', 'containerId', 'recreated')]: + changed = copy.deepcopy(old) + changed[service][key] = value + current.return_value = changed + with self.subTest(service=service, key=key), self.assertRaises(R.DeployError): + R.accept_device_release(before, rollback=True) + current.return_value = old + with patch.object(R, 'collect_exact_files', return_value={'unexpected.js': 'sha'}), self.assertRaisesRegex(R.DeployError, 'source mismatch'): + R.accept_device_release(before, rollback=True) + with patch.object(R, 'device_release_other_compose_services', return_value={'other': {}}), self.assertRaisesRegex(R.DeployError, 'unrelated Compose'): + R.accept_device_release(before, rollback=True) + + def test_marker_runtime_dispatch_has_no_build_or_restart(self): + entries = (R.DEVICE_R46_RECON_ENTRY,) + component = 'device-core-release-reconciliation' + with patch.object(R, 'run_build') as build, patch.object(R, 'run_compose') as compose, patch.object(R, 'prepare_component_runtime') as prepare: + R.run_component_runtime(component, entries, ()) + build.assert_not_called() + compose.assert_not_called() + prepare.assert_not_called() + with patch.object(R, 'preflight_device_r46_reconciliation') as preflight: + R.run_healthchecks(component, entries, ()) + preflight.assert_called_once_with(R.DEVICE_PLANE_ROOT, entries, R.DEVICE_R46_RECON_ID, marker_installed=True) + + +if __name__ == '__main__': + unittest.main() diff --git a/infra/device-core-deploy/R46_DNS_RECONCILIATION.md b/infra/device-core-deploy/R46_DNS_RECONCILIATION.md new file mode 100644 index 0000000..4b48083 --- /dev/null +++ b/infra/device-core-deploy/R46_DNS_RECONCILIATION.md @@ -0,0 +1,75 @@ +# Device Core r46: empty DNS representation + +The r46 release (`e30a6dd2a1eae306d811977188f5d118aefed4ab`) failed +acceptance on 2026-11-05. Its rollback restored the accepted r38 source, +but failed the v2 configuration fingerprint. The recorded field evidence +identifies exactly `HostConfig.Dns`, `DnsOptions`, and `DnsSearch`: saved +`[]`, observed `null`. The failed artifact and original backups stay immutable. +An accessible UI and 79 matching source files alone do not prove runtime rollback. + +## Registered transition + +`device-core-release-reconciliation` gains one exact marker: +`deployment/device-core-release-r46-reconciliation-v1.json`, identity +`device-core-release-r46-reconciliation-v1-20261105-001`. + +The live root remains `/volume1/docker/nodedc-device-plane`. The marker selects +no service, build, Compose operation, runtime mutation, database or secret. +The existing marker-only rollback removes only the newly installed marker. +The builder accepts no authority from command-line or payload metadata. + +`r46-evidence.json` pins the exact failed receipt, archive, six backup files and +the successful CMS r47/r49/r50 receipts plus their immutable runtime backups. +`r46_runtime.py` is embedded in the standalone root-owned installer by +`embed_r46.py`; no code is loaded from SMB at runtime. + +## Runtime proof + +The recovery reads three stable observations of all five Device services. +It enumerates at most eight combinations of the three **empty** DNS fields +and must reproduce each saved whole v2 SHA exactly. No field hash substitutes +for this whole-configuration proof. Nonempty DNS settings, environment, mounts, +bind order, ports, security flags and networks cannot be changed by the proof. +Every image must equal the saved image ID. Preserved Postgres, gateway and +backhaul also retain their complete identity and state. Source, Compose, +B2 foundation, runtime boundaries and health are checked by existing acceptance. + +Fingerprint v3 keeps the existing v2 mount normalization and converts only +explicit `null` values in the three DNS fields to `[]`. Missing fields and +malformed values fail closed. Nonempty lists retain every value and their +order. Historic v1/v2 fingerprints and their exact acceptance remain intact. +New normal Device releases record v3 and version-matched diagnostic hashes. + +## Concurrent CMS releases + +CMS legitimately replaced its container after the Device incident. Recovery +does not ignore CMS or arbitrary unrelated drift. It validates only the pinned +r47 → r49 → r50 chain, every canonical receipt/archive/backup, the current r50 +source, running application bytes, configuration and health. The original CMS +container ID comes from the pinned r47 backup. Only that one old/new CMS entry +is substituted in the derived in-memory baseline. The other 61 Compose entries +must be unchanged. CMS's own preserved-service snapshot must also match. +A newer CMS successor or unexplained container change requires new review. +CMS source, sites, configuration, credentials and runtime are never written. + +## Queue and operator gates + +A marker alone, including an in-progress apply, grants nothing. Only a separate +successful canonical recovery receipt with the matching archived marker permits +the exact run46/run-number39/digest/source tuple to move from `blocked` to +terminal `failed`. It is never made `ready` and never retried. The next qualified +commit follows the ordinary outbound Git deployment route. + +1. Review source/tests and promote the SHA-pinned root-owned installer, checking + the exact previous installer SHA and an idle deploy lock. +2. Run `verify-install` immediately from the installed path. +3. Stage the deterministic marker artifact, inspect its lifecycle, then obtain a + fresh canonical `plan`. The plan itself performs the read-only runtime proof. +4. Review the plan and apply once. `apply` repeats all proof before and after + marker installation; no application runtime changes are selected. +5. Observe the ordinary next release receipt, then check the resulting Device UI. + +Tests cover integrity failures, real configuration drift, image and dependency +changes, unstable observations, unsupported versions, exact artifact scope, +CMS generation drift, historical v1/v2 compatibility, queue identity and +idempotency, marker-only runtime dispatch and Python 3.8 syntax. diff --git a/infra/device-core-deploy/build_r46_reconciliation.py b/infra/device-core-deploy/build_r46_reconciliation.py new file mode 100644 index 0000000..a667382 --- /dev/null +++ b/infra/device-core-deploy/build_r46_reconciliation.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Deterministic data-only marker for the exact r46 rollback reconciliation.""" +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-r46-reconciliation-v1.json' + + +def bundle(): + descriptor = (ROOT / 'r46-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, info.size = 0o644, 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), 'id': identity, 'sha256': hashlib.sha256(data).hexdigest()})) diff --git a/infra/device-core-deploy/controller.py b/infra/device-core-deploy/controller.py index 61e436c..0a1b8c6 100644 --- a/infra/device-core-deploy/controller.py +++ b/infra/device-core-deploy/controller.py @@ -8,6 +8,13 @@ class Controller: def reconcile(self): for row in self.queue.snapshot(): + if row['phase'] == 'blocked': + outcome, receipt = self.installer.receipt(row) + if outcome == 'rolled-back': + self.queue.reconcile_r46(row['id'], digest=row['digest'], artifact=row['artifact'], receipt=receipt) + elif outcome != 'ambiguous': + raise QueueError('blocked_run_requires_exact_recovery') + continue if row['phase'] != 'deploying': continue outcome, receipt = self.installer.receipt(row) diff --git a/infra/device-core-deploy/deployment_queue.py b/infra/device-core-deploy/deployment_queue.py index c2f1e0d..93e8b7a 100644 --- a/infra/device-core-deploy/deployment_queue.py +++ b/infra/device-core-deploy/deployment_queue.py @@ -174,5 +174,29 @@ class DeploymentQueue: self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity)) self.transaction(apply) + def reconcile_r46(self, identity, *, digest, artifact, receipt): + """Exact terminal blocked -> failed recovery after canonical proof. + + This never makes the failed artifact ready again. The caller verifies + the immutable failed evidence and the separate successful recovery. + """ + sha = 'e30a6dd2a1eae306d811977188f5d118aefed4ab' + expected_receipt = 'canonical-reconciled:device-core-release-r46-reconciliation-v1-20261105-001' + if (type(identity) is not int or identity != 46 + or digest != 'b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba' + or artifact != 'nodedc-device-core-release-v1-r46-'+sha+'.tgz' + or receipt != expected_receipt): + raise QueueError('r46_reconciliation_identity_mismatch') + def apply(): + row = self.db.execute('SELECT * FROM runs WHERE id=?', (identity,)).fetchone() + if row is None or tuple(row[k] for k in ('number','sha','event','branch','workflow','digest','artifact')) != (39,sha,'push','main',WORKFLOW,digest,artifact): + raise QueueError('r46_reconciliation_row_mismatch') + if row['phase'] == 'failed' and row['receipt'] == receipt: + return + if row['phase'] != 'blocked' or row['receipt'] != 'canonical-rollback-unconfirmed': + raise QueueError('r46_reconciliation_predecessor_mismatch') + self.db.execute("UPDATE runs SET phase='failed',receipt=? WHERE id=?", (receipt,identity)) + self.transaction(apply) + def snapshot(self): return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")] diff --git a/infra/device-core-deploy/embed_r46.py b/infra/device-core-deploy/embed_r46.py new file mode 100644 index 0000000..b07eddc --- /dev/null +++ b/infra/device-core-deploy/embed_r46.py @@ -0,0 +1,24 @@ +"""Embed the reviewed r46 recovery into the standalone root-owned runner.""" +import json +from pathlib import Path +ROOT = Path(__file__).resolve().parent +RUNNER = ROOT.parent / 'deploy-runner/nodedc-deploy' +START = '# BEGIN GENERATED DEVICE R46 RECOVERY\n' +END = '# END GENERATED DEVICE R46 RECOVERY\n' + + +def section(): + source = (ROOT / 'r46_runtime.py').read_text() + evidence = json.loads((ROOT / 'r46-evidence.json').read_text()) + return START + source.replace('__DEVICE_R46_EVIDENCE__', repr(evidence)) + '\n' + END + + +if __name__ == '__main__': + current = RUNNER.read_text() + if START in current: + before, rest = current.split(START, 1) + _, after = rest.split(END, 1) + current = before + section() + after + else: + current = current.replace('\ndef main(argv):', '\n' + section() + '\n\ndef main(argv):', 1) + RUNNER.write_text(current) diff --git a/infra/device-core-deploy/r46-evidence.json b/infra/device-core-deploy/r46-evidence.json new file mode 100644 index 0000000..1c53133 --- /dev/null +++ b/infra/device-core-deploy/r46-evidence.json @@ -0,0 +1,61 @@ +{ + "backupHashes": { + "device-release-before.json": "52927379518030d1e979d897e5cb298481d81a78fb694c5ab68896bfeb8a64d4", + "existing-files.txt": "4d02728c991e4666425d968497d3540ad95802de055db4f899411ce34e526b5a", + "files.txt": "4d02728c991e4666425d968497d3540ad95802de055db4f899411ce34e526b5a", + "manifest.env": "c126a1df2b28d0474e80727e5716311ea6b9aa5702f6b76e9d4742205d87ba62", + "missing-files.txt": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "source-before.tgz": "dc40d86d52be8f7e02fb7ec0928da371e37f813676bba182fb883212cc7ec967" + }, + "cms": [ + { + "backupSha256": "1156f7bdc0313cb4ad8f2541cbe260e965784201b18baacb548480ee6add902d", + "row": { + "applied_at": "2026-11-05T10:32:58+00:00", + "artifact": "nodedc-dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1.tgz", + "backup_id": "dc-cms-release-dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1-20261105-133137", + "component": "dc-cms-release", + "id": "dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1", + "sha256": "dfd7bbc8753af8b6693253a5a7030995fc6745e541e5206ca1e708bf17555a5d", + "status": "ok" + } + }, + { + "backupSha256": "6a800c80d6cd533bf7d31745baa20ab9912ac9c93f1e9febbe19a61006650547", + "row": { + "applied_at": "2026-11-05T10:35:39+00:00", + "artifact": "nodedc-dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835.tgz", + "backup_id": "dc-cms-release-dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835-20261105-133344", + "component": "dc-cms-release", + "id": "dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835", + "sha256": "d69852e99b251310bc96ec88dcc89d9d16ca704c49f35d8a168c2835440652b0", + "status": "ok" + } + }, + { + "backupSha256": "2b96d060d5aee54998dabb1c432fe495469cebc92a59b859ff00a0c1183690ca", + "row": { + "applied_at": "2026-11-05T10:54:15+00:00", + "artifact": "nodedc-dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3.tgz", + "backup_id": "dc-cms-release-dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3-20261105-135303", + "component": "dc-cms-release", + "id": "dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3", + "sha256": "88a09153b860280c0a28c51e13bbe8d68cb39e7030ce2ba70bc9a0bf8a367c43", + "status": "ok" + } + } + ], + "failedRow": { + "artifact": "nodedc-device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab.tgz.20261105-132438", + "backup_id": "device-core-release-device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab-20261105-132438", + "component": "device-core-release", + "failed_at": "2026-11-05T10:30:32+00:00", + "id": "device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab", + "message": "Device Core release runtime configuration drift: device-control-core; field_evidence={\"actualSha256\":\"103d405d730b8de86f1c83f4aa5b31f99e1cfc04de76e48bbb4dbab54149b018\",\"changedFields\":[{\"actualSha256\":\"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b\",\"expectedSha256\":\"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945\",\"path\":\"HostConfig.Dns\"},{\"actualSha256\":\"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b\",\"expectedSha256\":\"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945\",\"path\":\"HostConfig.DnsOptions\"},{\"actualSha256\":\"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b\",\"expectedSha256\":\"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945\",\"path\":\"HostConfig.DnsSearch\"}],\"evidence\":\"captured\",\"expectedSha256\":\"37c24299b8eeede7707905a435e99360de08eb2a852d1f4750db353efa17c7b2\",\"schema\":\"nodedc.device-core.runtime-drift-fields.v1\",\"service\":\"device-control-core\",\"truncated\":false}", + "rollback_status": "failed:DeployError", + "sha256": "b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba", + "started_apply": true, + "status": "failed" + }, + "predecessor": "device-core-release-v1-r38-dcb0c76ac8e9403c05cc64e9cdde5ebf859f2766" +} diff --git a/infra/device-core-deploy/r46-reconciliation-v1.json b/infra/device-core-deploy/r46-reconciliation-v1.json new file mode 100644 index 0000000..e568f5b --- /dev/null +++ b/infra/device-core-deploy/r46-reconciliation-v1.json @@ -0,0 +1,10 @@ +{ + "backupId": "device-core-release-device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab-20261105-132438", + "cmsSuccessor": "dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3", + "failedReleaseId": "device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab", + "failedSha256": "b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba", + "mode": "prove-restored-baseline-empty-dns-only", + "releaseId": "device-core-release-r46-reconciliation-v1-20261105-001", + "runtimeFingerprintVersion": 3, + "schemaVersion": "nodedc.device-core.r46-reconciliation.v1" +} diff --git a/infra/device-core-deploy/r46_runtime.py b/infra/device-core-deploy/r46_runtime.py new file mode 100644 index 0000000..5e6d5ab --- /dev/null +++ b/infra/device-core-deploy/r46_runtime.py @@ -0,0 +1,221 @@ +"""Versioned DNS representation fingerprint and exact r46 evidence-only recovery. + +Embedded into the root-owned runner. No production code is imported from SMB. +Historical v1/v2 hashes are never reinterpreted without an exact preimage proof. +""" +DEVICE_R46_EVIDENCE = __DEVICE_R46_EVIDENCE__ +DEVICE_R46_RECON_ID = 'device-core-release-r46-reconciliation-v1-20261105-001' +DEVICE_R46_RECON_ENTRY = 'deployment/device-core-release-r46-reconciliation-v1.json' +DEVICE_DNS_FIELDS = ('Dns', 'DnsOptions', 'DnsSearch') + + +def device_release_fields_v3(fields): + result = device_release_mounts_v2(fields) + host = result['HostConfig'] + for key in DEVICE_DNS_FIELDS: + if key not in host: + die('Device Core v3 DNS field is missing') + value = host[key] + if value is None: + host[key] = [] + elif not isinstance(value, list) or any(not isinstance(v, str) for v in value): + die('Device Core v3 DNS field is malformed') + return result + + +def device_release_runtime_snapshot_v3(): + result = {} + for service, sample in device_release_drift_sample().items(): + row = dict(sample['runtime']) + if not row['running'] or row['health'] not in (None, 'healthy'): + die('Device Core predecessor service is not healthy: ' + service) + row['runtimeConfigSha256'] = device_release_drift_digest(device_release_fields_v3(sample['fields'])) + result[service] = row + return result + + +def device_r46_dns_proof(fields, expected): + device_release_fields_v3(fields) # Validate, without altering the v2 preimage. + candidate = device_release_mounts_v2(fields) + if not isinstance(expected, str) or not re.fullmatch('[a-f0-9]{64}', expected): + die('Device Core r46 saved digest is invalid') + if any(candidate['HostConfig'][k] not in (None, []) for k in DEVICE_DNS_FIELDS): + die('Device Core r46 proof requires empty DNS settings') + for checked, values in enumerate(itertools.product((None, []), repeat=3), 1): + for key, value in zip(DEVICE_DNS_FIELDS, values): + candidate['HostConfig'][key] = value + if device_release_drift_digest(candidate) == expected: + return checked + die('Device Core r46 runtime differs beyond empty DNS representation') + + +def device_r46_descriptor(): + e = DEVICE_R46_EVIDENCE + return {'schemaVersion': 'nodedc.device-core.r46-reconciliation.v1', + 'releaseId': DEVICE_R46_RECON_ID, 'failedReleaseId': e['failedRow']['id'], + 'failedSha256': e['failedRow']['sha256'], 'backupId': e['failedRow']['backup_id'], + 'runtimeFingerprintVersion': 3, 'mode': 'prove-restored-baseline-empty-dns-only', + 'cmsSuccessor': e['cms'][-1]['row']['id']} + + +def validate_device_r46_payload(payload, entries, identity): + if tuple(entries or ()) != (DEVICE_R46_RECON_ENTRY,) or identity != DEVICE_R46_RECON_ID: + die('Device Core r46 reconciliation identity/entry mismatch') + marker = payload / DEVICE_R46_RECON_ENTRY + expected = (json.dumps(device_r46_descriptor(), sort_keys=True, indent=2) + '\n').encode() + if marker.is_symlink() or not marker.is_file() or marker.read_bytes() != expected: + die('Device Core r46 reconciliation descriptor mismatch') + + +def device_r46_evidence(): + e = DEVICE_R46_EVIDENCE + row = e['failedRow'] + records = [r for r in load_state(FAILED_STATE_FILE) + if r.get('id') == row['id'] or r.get('sha256') == row['sha256']] + if records != [row] or any(r.get('id') == row['id'] or r.get('sha256') == row['sha256'] + for r in load_state(STATE_FILE)): + die('Device Core r46 failed receipt mismatch') + archive = FAILED_DIR / row['artifact'] + if archive.is_symlink() or not archive.is_file() or sha256_file(archive) != row['sha256']: + die('Device Core r46 failed archive mismatch') + backup = BACKUPS_DIR / row['backup_id'] + if backup.is_symlink() or not backup.is_dir(): + die('Device Core r46 backup is unsafe') + for name, digest in e['backupHashes'].items(): + path = backup / name + if path.is_symlink() or not path.is_file() or sha256_file(path) != digest: + die('Device Core r46 backup digest mismatch: ' + name) + before = read_strict_json(backup / 'device-release-before.json', 'Device Core r46 backup', max_bytes=256*1024) + if before.get('runtimeFingerprintVersion') != 2 or before.get('predecessor') != e['predecessor']: + die('Device Core r46 predecessor/version mismatch') + 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 r46 reconciliation') + if missing: + die('Device Core r46 backup partition mismatch') + with tempfile.TemporaryDirectory(prefix='device-r46-evidence-', dir=TMP_DIR) as tmp: + materialize_backup_tree(backup / 'source-before.tgz', Path(tmp), set(existing)) + if collect_exact_files(Path(tmp), existing, 'Device Core r46 source backup') != before['installedFiles']: + die('Device Core r46 source/runtime evidence conflict') + return before + + +def device_r46_cms_evidence(): + """Read only the three exact accepted CMS successors, not arbitrary drift.""" + evidence = DEVICE_R46_EVIDENCE['cms'] + applied = load_state(STATE_FILE) + failed = load_state(FAILED_STATE_FILE) + backups = [] + for item in evidence: + row = item['row'] + if [r for r in applied if r.get('id') == row['id'] or r.get('sha256') == row['sha256']] != [row]: + die('Device Core r46 CMS successor receipt mismatch') + if any(r.get('id') == row['id'] or r.get('sha256') == row['sha256'] for r in failed): + die('Device Core r46 CMS successor has conflicting receipt') + backup = BACKUPS_DIR / row['backup_id'] + path = backup / 'cms-runtime-before.json' + if (backup.is_symlink() or not backup.is_dir() or path.is_symlink() or not path.is_file() + or sha256_file(path) != item['backupSha256']): + die('Device Core r46 CMS successor backup mismatch') + before = read_strict_json(path, 'Device Core r46 CMS backup', max_bytes=2*1024*1024) + with tempfile.TemporaryDirectory(prefix='device-r46-cms-', dir=TMP_DIR) as tmp: + manifest, entries, payload = load_artifact(device_release_applied_archive(row), Path(tmp)) + if manifest['component'] != 'dc-cms-release' or manifest['id'] != row['id']: + die('Device Core r46 CMS archive identity mismatch') + descriptor = validate_cms_release_payload(payload, entries, row['id']) + if descriptor != before['descriptor']: + die('Device Core r46 CMS source/backup identity mismatch') + backups.append(before) + for previous, current in zip(backups, backups[1:]): + if (current['predecessor'] != previous['descriptor']['sourceCommit'] + or current['otherServices'] != previous['otherServices']): + die('Device Core r46 CMS successor chain mismatch') + return backups + + +def device_r46_other_services(before, cms_backups): + # A new CMS container is permitted only after proving the exact r47/r49/r50 + # chain and current r50 app bytes, health, config and all unrelated services. + latest = cms_backups[-1] + if cms_installed_release() != latest['descriptor']: + die('Device Core r46 requires the exact accepted CMS successor') + cms_healthchecks() + runtime = cms_runtime_snapshot_v2() + if (runtime['configSha256'] != latest['runtime']['configSha256'] + or runtime['imageRef'] != latest['runtime']['imageRef'] + or runtime['id'] == latest['runtime']['id']): + die('Device Core r46 CMS configuration/generation drift') + actual, metadata = cms_application_inventory() + if (metadata != latest['installedMetadata'] or cms_foundation() != latest['foundation'] + or cms_image_files(runtime['id']) != {k: v for k, v in actual.items() if k not in CMS_DEPENDENCY_FILES} + or cms_other_services() != latest['otherServices']): + die('Device Core r46 CMS source or preserved services differ') + old_id = cms_backups[0]['runtime']['id'] + saved = before['otherComposeServices'] + current = device_release_other_compose_services() + if old_id not in saved or runtime['id'] not in current or old_id in current: + die('Device Core r46 CMS predecessor container identity mismatch') + unchanged = {k: v for k, v in saved.items() if k != old_id} + if (any(cms_backups[0]['otherServices'].get(k) != v for k, v in unchanged.items()) + or {k: v for k, v in current.items() if k != runtime['id']} != unchanged): + die('Device Core r46 changed an unrelated Compose service') + return current + + +def device_r46_restored_baseline(before): + if before.get('runtimeFingerprintVersion') != 2 or set(before['runtime']) != set(DEVICE_RELEASE_INVENTORY): + die('Device Core r46 requires the exact v2 inventory') + samples = [device_release_drift_sample() for _ in range(3)] + if any(sample != samples[0] for sample in samples): + die('Device Core r46 runtime changed during reconciliation') + baseline = json.loads(json.dumps(before)) + baseline['runtimeFingerprintVersion'] = 3 + baseline.pop('runtimeFieldDigests', None) # Historical v2 diagnostics stay in the immutable backup. + for service in DEVICE_RELEASE_INVENTORY: + sample = samples[0][service] + row, fields, old = sample['runtime'], sample['fields'], before['runtime'][service] + if (not row['running'] or row['health'] not in (None, 'healthy') or row['imageId'] != old['imageId'] + or row['runtimeConfigSha256'] != device_release_drift_digest(fields)): + die('Device Core r46 image/health/evidence mismatch: ' + service) + v2 = dict(row, runtimeConfigSha256=device_release_drift_digest(device_release_mounts_v2(fields))) + if service not in DEVICE_RELEASE_SERVICES and v2 != old: + die('Device Core r46 preserved service differs: ' + service) + device_r46_dns_proof(fields, old['runtimeConfigSha256']) + baseline['runtime'][service]['runtimeConfigSha256'] = device_release_drift_digest(device_release_fields_v3(fields)) + return baseline + + +def preflight_device_r46_reconciliation(payload, entries, identity, *, marker_installed=False): + require_root() + validate_device_r46_payload(payload, entries, identity) + marker = DEVICE_PLANE_ROOT / DEVICE_R46_RECON_ENTRY + if not marker_installed and (marker.exists() or marker.is_symlink()): + die('Device Core r46 marker already exists') + before = device_r46_evidence() + baseline = device_r46_restored_baseline(before) + baseline['otherComposeServices'] = device_r46_other_services(before, device_r46_cms_evidence()) + run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES) + accept_device_release(baseline, rollback=True) + print('device_r46_reconciliation=exact-v2-sha;dns-empty-only;samples=3;fingerprint=v3;' + 'cms-successor=r50;services=none;build=none;runtime-mutation=none') + return baseline + + +def device_r46_reconciled(row): + if row != DEVICE_R46_EVIDENCE['failedRow']: + return False + records = [r for r in load_state(STATE_FILE) if r.get('id') == DEVICE_R46_RECON_ID] + if not records: + return False # Marker alone, including in-progress apply, grants nothing. + if (len(records) != 1 or records[0].get('component') != 'device-core-release-reconciliation' + or records[0].get('status') != 'ok'): + die('Device Core r46 reconciliation receipt mismatch') + validate_device_r46_payload(DEVICE_PLANE_ROOT, (DEVICE_R46_RECON_ENTRY,), DEVICE_R46_RECON_ID) + with tempfile.TemporaryDirectory(prefix='device-r46-marker-', dir=TMP_DIR) as tmp: + manifest, entries, payload = load_artifact(device_release_applied_archive(records[0]), Path(tmp)) + if manifest['component'] != 'device-core-release-reconciliation' or manifest['id'] != DEVICE_R46_RECON_ID: + die('Device Core r46 reconciliation archive identity mismatch') + validate_device_r46_payload(payload, entries, manifest['id']) + device_r46_evidence() + device_r46_cms_evidence() + return True diff --git a/infra/device-core-deploy/test_r46_reconciliation.py b/infra/device-core-deploy/test_r46_reconciliation.py new file mode 100644 index 0000000..914d687 --- /dev/null +++ b/infra/device-core-deploy/test_r46_reconciliation.py @@ -0,0 +1,298 @@ +import ast +import copy +from contextlib import ExitStack, redirect_stdout +import importlib.machinery +import importlib.util +import io +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import Mock, patch + +from build_r46_reconciliation import bundle +from deployment_queue import DeploymentQueue, QueueError, REPOSITORY, REPOSITORY_ID, WORKFLOW +from controller import Controller +from embed_r46 import section, START, END + +ROOT = Path(__file__).resolve().parents[2] +RUNNER = ROOT / 'infra/deploy-runner/nodedc-deploy' +loader = importlib.machinery.SourceFileLoader('device_r46_runner', str(RUNNER)) +spec = importlib.util.spec_from_loader(loader.name, loader) +r = importlib.util.module_from_spec(spec) +loader.exec_module(r) + + +def fields(): + return {'HostConfig': {'Dns': [], 'DnsOptions': [], 'DnsSearch': [], + 'Mounts': [{'Target': '/a', 'Source': '/source/a', 'Type': 'bind'}, + {'Target': '/b', 'Source': '/source/b', 'Type': 'bind'}], + 'Binds': ['/a:/a:ro', '/b:/b:ro'], 'NetworkMode': 'private-egress', + 'ReadonlyRootfs': True, 'CapAdd': [], 'PortBindings': {}}, + 'Config': {'Env': ['TOKEN=fixture-do-not-log'], 'Cmd': ['node', 'server.js'], 'User': '123'}, + 'Mounts': [{'Source': '/source/a', 'Destination': '/a', 'RW': False}], + 'networks': ['private-egress']} + + +def incident(): + samples, runtime = {}, {} + for service in r.DEVICE_RELEASE_INVENTORY: + f = fields() + row = {'service': service, 'containerId': 'old-' + service, 'imageId': 'image-' + service, + 'running': True, 'health': 'healthy', 'restartCount': 0, 'status': 'running', + 'runtimeConfigSha256': r.device_release_drift_digest(r.device_release_mounts_v2(f))} + runtime[service] = copy.deepcopy(row) + if service in r.DEVICE_RELEASE_SERVICES: + row['containerId'] = 'restored-' + service + for key in r.DEVICE_DNS_FIELDS: + f['HostConfig'][key] = None + row['runtimeConfigSha256'] = r.device_release_drift_digest(f) + samples[service] = {'runtime': row, 'fields': f} + return {'runtimeFingerprintVersion': 2, 'runtime': runtime, + 'installedFiles': {'app.js': 'sha'}, 'otherComposeServices': {}, 'compose': {}}, samples + + +class FingerprintTests(unittest.TestCase): + def test_v3_only_empty_dns_and_existing_v2_mount_order(self): + old = fields() + new = copy.deepcopy(old) + new['HostConfig']['Mounts'].reverse() + for key in r.DEVICE_DNS_FIELDS: + new['HostConfig'][key] = None + saved = copy.deepcopy(new) + self.assertNotEqual(r.device_release_mounts_v2(old), r.device_release_mounts_v2(new)) + self.assertEqual(r.device_release_fields_v3(old), r.device_release_fields_v3(new)) + self.assertEqual(r.device_r46_dns_proof(new, r.device_release_drift_digest(r.device_release_mounts_v2(old))), 8) + self.assertEqual(new, saved) + + def test_nonempty_dns_order_is_preserved_not_reconciled(self): + old = fields() + for key in r.DEVICE_DNS_FIELDS: + new = copy.deepcopy(old) + new['HostConfig'][key] = ['one', 'two'] + self.assertEqual(r.device_release_fields_v3(new)['HostConfig'][key], ['one', 'two']) + rev = copy.deepcopy(new) + rev['HostConfig'][key].reverse() + self.assertNotEqual(r.device_release_fields_v3(new), r.device_release_fields_v3(rev)) + with self.assertRaises(r.DeployError): + r.device_r46_dns_proof(new, r.device_release_drift_digest(old)) + + def test_real_drift_remains_rejected(self): + old = fields() + mutations = [lambda f: f['Config'].update(Env=['TOKEN=changed']), + lambda f: f['Config'].update(Cmd=['wrong']), + lambda f: f['HostConfig'].update(NetworkMode='host'), + lambda f: f['HostConfig'].update(ReadonlyRootfs=False), + lambda f: f['HostConfig'].update(CapAdd=['SYS_ADMIN']), + lambda f: f['HostConfig'].update(PortBindings={'80/tcp': []}), + lambda f: f['HostConfig']['Binds'].reverse(), + lambda f: f['HostConfig']['Mounts'][0].update(Source='/different'), + lambda f: f['Mounts'][0].update(RW=True), + lambda f: f.update(networks=['other'])] + for mutate in mutations: + new = copy.deepcopy(old) + mutate(new) + with self.subTest(mutate=mutate), self.assertRaises(r.DeployError): + r.device_r46_dns_proof(new, r.device_release_drift_digest(r.device_release_mounts_v2(old))) + + def test_malformed_dns_and_mounts_fail_closed(self): + for key in r.DEVICE_DNS_FIELDS: + for value in ('', False, 0, {}, [1], [None]): + f = fields() + f['HostConfig'][key] = value + with self.subTest(key=key, value=value), self.assertRaises(r.DeployError): + r.device_release_fields_v3(f) + f = fields() + del f['HostConfig'][key] + with self.assertRaises(r.DeployError): + r.device_release_fields_v3(f) + f = fields() + f['HostConfig']['Mounts'][1]['Target'] = '/a' + with self.assertRaises(r.DeployError): + r.device_release_fields_v3(f) + + def test_stable_exact_old_images_and_preserved_services(self): + before, samples = incident() + saved = copy.deepcopy(before) + with patch.object(r, 'device_release_drift_sample', return_value=samples) as read: + baseline = r.device_r46_restored_baseline(before) + self.assertEqual(read.call_count, 3) + self.assertEqual(before, saved) + self.assertEqual(baseline['runtimeFingerprintVersion'], 3) + for service in r.DEVICE_RELEASE_INVENTORY: + self.assertEqual(baseline['runtime'][service]['imageId'], before['runtime'][service]['imageId']) + self.assertEqual(baseline['installedFiles'], before['installedFiles']) + + def test_unstable_unhealthy_changed_images_and_preserved_identity_rejected(self): + before, samples = incident() + service = r.DEVICE_RELEASE_SERVICES[0] + for key, value in [('imageId', 'new'), ('running', False), ('health', 'unhealthy')]: + changed = copy.deepcopy(samples) + changed[service]['runtime'][key] = value + with patch.object(r, 'device_release_drift_sample', return_value=changed), self.assertRaises(r.DeployError): + r.device_r46_restored_baseline(before) + changed = copy.deepcopy(samples) + changed[service]['runtime']['containerId'] = 'unstable' + with patch.object(r, 'device_release_drift_sample', side_effect=[samples, changed, samples]), self.assertRaises(r.DeployError): + r.device_r46_restored_baseline(before) + preserved = next(s for s in r.DEVICE_RELEASE_INVENTORY if s not in r.DEVICE_RELEASE_SERVICES) + changed = copy.deepcopy(samples) + changed[preserved]['runtime']['containerId'] = 'recreated-db' + with patch.object(r, 'device_release_drift_sample', return_value=changed), self.assertRaises(r.DeployError): + r.device_r46_restored_baseline(before) + + +class ArtifactTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.artifact = self.root / 'candidate.tgz' + self.artifact.write_bytes(bundle()[1]) + unpack = self.root / 'unpack' + unpack.mkdir() + self.manifest, self.entries, self.payload = r.load_artifact(self.artifact, unpack) + + def test_exact_deterministic_data_only_scope(self): + self.assertEqual(self.artifact.read_bytes(), bundle()[1]) + self.assertEqual(self.entries, [r.DEVICE_R46_RECON_ENTRY]) + component = self.manifest['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 path in ('services/device-manager/app.js', '.env', 'deployment/other.json', 'data/db'): + with self.assertRaises(r.DeployError): + r.allowed_payload_path(component, path) + for key, value in [('runtimeFingerprintVersion', 2), ('mode', 'restart'), ('cmsSuccessor', 'other')]: + d = r.device_r46_descriptor() + d[key] = value + (self.payload / r.DEVICE_R46_RECON_ENTRY).write_text(json.dumps(d)) + with self.assertRaises(r.DeployError): + r.validate_device_r46_payload(self.payload, self.entries, r.DEVICE_R46_RECON_ID) + + def test_preflight_owns_all_checks_and_no_runtime_mutation(self): + before, samples = incident() + with ExitStack() as stack: + for name, value in [('require_root', None), ('device_r46_evidence', before), + ('device_release_drift_sample', samples), ('device_r46_cms_evidence', []), + ('device_r46_other_services', {})]: + stack.enter_context(patch.object(r, name, return_value=value)) + stack.enter_context(patch.object(r, 'DEVICE_PLANE_ROOT', self.root / 'live')) + health = stack.enter_context(patch.object(r, 'run_healthchecks')) + accept = stack.enter_context(patch.object(r, 'accept_device_release')) + mutation = stack.enter_context(patch.object(r.subprocess, 'run', side_effect=AssertionError('unexpected command'))) + with redirect_stdout(io.StringIO()): + result = r.preflight_device_r46_reconciliation(self.payload, self.entries, r.DEVICE_R46_RECON_ID) + health.assert_called_once_with('device-core-release', r.DEVICE_RELEASE_ENTRIES, r.DEVICE_RELEASE_SERVICES) + accept.assert_called_once_with(result, rollback=True) + mutation.assert_not_called() + accept.side_effect = r.DeployError('guard rejection') + with self.assertRaises(r.DeployError): + r.preflight_device_r46_reconciliation(self.payload, self.entries, r.DEVICE_R46_RECON_ID) + + def test_marker_without_success_receipt_never_releases_queue(self): + row = r.DEVICE_R46_EVIDENCE['failedRow'] + with patch.object(r, 'load_state', return_value=[]): + self.assertFalse(r.device_r46_reconciled(row)) + with patch.object(r, 'load_state', return_value=[{'id': r.DEVICE_R46_RECON_ID, 'status': 'failed'}]), self.assertRaises(r.DeployError): + r.device_r46_reconciled(row) + self.assertFalse(r.device_r46_reconciled({**row, 'sha256': 'a' * 64})) + + def test_registered_routes_and_embedded_source_are_current(self): + source = RUNNER.read_text() + self.assertEqual(source.split(START, 1)[1].split(END, 1)[0], section().split(START, 1)[1].split(END, 1)[0]) + ast.parse(source, feature_version=(3, 8)) + self.assertIn('device_release_runtime_snapshot_v3()', source) + self.assertIn('not device_release_r5_reconciled(row) and not device_r46_reconciled(row)', source) + self.assertIn('ok:device-core-release-reconciliation-marker-only', source) + + +class CmsSuccessorTests(unittest.TestCase): + def fixture(self, stack): + preserved = {'stable': {'fingerprint': 'exact', 'running': True, 'startedAt': 'old'}} + old = {'old-cms': {'fingerprint': 'old'}, **preserved} + current = {'new-cms': {'fingerprint': 'new'}, **preserved} + latest = {'runtime': {'id': 'cms49', 'configSha256': 'config', 'imageRef': 'cms'}, + 'descriptor': {'releaseId': 'cms50'}, 'installedMetadata': {}, 'foundation': {'compose': 'sha'}, + 'otherServices': {**preserved, 'device': {'fingerprint': 'restored'}}} + backups = [{'runtime': {'id': 'old-cms'}, 'otherServices': latest['otherServices']}, latest] + values = {'cms_installed_release': latest['descriptor'], 'cms_healthchecks': None, + 'cms_runtime_snapshot_v2': {'id': 'new-cms', 'configSha256': 'config', 'imageRef': 'cms'}, + 'cms_application_inventory': ({'admin/index.html': 'exact'}, {}), + 'cms_foundation': latest['foundation'], 'cms_image_files': {'admin/index.html': 'exact'}, + 'cms_other_services': latest['otherServices'], 'device_release_other_compose_services': current} + mocks = {name: stack.enter_context(patch.object(r, name, return_value=value)) for name, value in values.items()} + return {'otherComposeServices': old}, backups, current, mocks + + def test_only_exact_accepted_cms_generation_may_change(self): + with ExitStack() as stack: + before, backups, current, mocks = self.fixture(stack) + self.assertEqual(r.device_r46_other_services(before, backups), current) + self.assertIn('old-cms', before['otherComposeServices']) + mocks['device_release_other_compose_services'].return_value = {**current, 'foreign': {}} + with self.assertRaises(r.DeployError): + r.device_r46_other_services(before, backups) + + def test_cms_drift_or_other_container_changes_not_ignored(self): + mutations = [('cms_installed_release', {'releaseId': 'unreviewed51'}), + ('cms_image_files', {'admin/index.html': 'changed'}), + ('cms_other_services', {}), ('cms_foundation', {}), + ('cms_runtime_snapshot_v2', {'id': 'new-cms', 'configSha256': 'changed', 'imageRef': 'cms'}), + ('cms_application_inventory', ({'admin/index.html': 'exact'}, {'unexpected': 'metadata'})), + ('device_release_other_compose_services', {'new-cms': {}, 'stable': {'fingerprint': 'changed'}})] + for name, value in mutations: + with self.subTest(name=name), ExitStack() as stack: + before, backups, _, mocks = self.fixture(stack) + mocks[name].return_value = value + with self.assertRaises(r.DeployError): + r.device_r46_other_services(before, backups) + + +class QueueRecoveryTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.q = DeploymentQueue(Path(self.tmp.name) / 'queue.db', first_run_number=1) + self.addCleanup(self.q.close) + self.sha = 'e30a6dd2a1eae306d811977188f5d118aefed4ab' + self.digest = r.DEVICE_R46_EVIDENCE['failedRow']['sha256'] + self.artifact = 'nodedc-device-core-release-v1-r46-' + self.sha + '.tgz' + self.receipt = 'canonical-reconciled:' + r.DEVICE_R46_RECON_ID + run = {'id': 46, 'run_number': 39, 'run_attempt': 1, 'head_sha': self.sha, + 'status': 'completed', 'conclusion': 'success', 'event': 'push', 'head_branch': 'main', 'path': WORKFLOW} + self.q.observe([run], repository=REPOSITORY, repository_id=REPOSITORY_ID) + self.q.reserve(46, digest=self.digest, artifact=self.artifact) + self.q.reconcile(46, digest=self.digest, artifact=self.artifact, outcome='ambiguous', receipt='canonical-rollback-unconfirmed') + + def test_exact_blocked_to_failed_is_idempotent_never_ready(self): + for _ in range(2): + self.q.reconcile_r46(46, digest=self.digest, artifact=self.artifact, receipt=self.receipt) + self.assertEqual(self.q.snapshot()[0]['phase'], 'failed') + self.assertIsNone(self.q.next_ready()) + + def test_wrong_identity_digest_receipt_or_row_stays_blocked(self): + for values in [(47, self.digest, self.artifact, self.receipt), + (46, 'a' * 64, self.artifact, self.receipt), + (46, self.digest, self.artifact, 'canonical:unconfirmed')]: + with self.assertRaises(QueueError): + self.q.reconcile_r46(values[0], digest=values[1], artifact=values[2], receipt=values[3]) + self.q.db.execute("UPDATE runs SET branch='other' WHERE id=46") + with self.assertRaises(QueueError): + self.q.reconcile_r46(46, digest=self.digest, artifact=self.artifact, receipt=self.receipt) + self.assertEqual(self.q.snapshot()[0]['phase'], 'blocked') + + def test_controller_reconciles_only_canonical_receipt(self): + installer = Mock() + controller = Controller(self.q, Mock(), installer) + installer.receipt.return_value = ('ambiguous', 'canonical-rollback-unconfirmed') + controller.reconcile() + self.assertEqual(self.q.snapshot()[0]['phase'], 'blocked') + installer.receipt.return_value = ('rolled-back', self.receipt) + controller.reconcile() + self.assertEqual(self.q.snapshot()[0]['phase'], 'failed') + installer.apply.assert_not_called() + installer.plan.assert_not_called() + + +if __name__ == '__main__': + unittest.main()