"""Conservative migration recovery and forward activation. External operations must be supplied by trusted adapters. No direct database, Docker or shell execution. """ import os from datetime import datetime, timezone from pathlib import Path from core.approval import validate_context from core.compatibility import canonical_hash from core.locking import DeploymentLock from core.migration import validate_history, validate_original_release class MigrationRecoveryError(RuntimeError): """Migration recovery is unsafe or incomplete.""" def require(condition, message): if not condition: raise MigrationRecoveryError(message) class MigrationRecovery: def __init__( self, *, site, store, lock_path, identity_probe, history_probe, provenance_probe, backup_probe, contain, containment_probe, current_probe, activate, refresh, readiness_probe, release_containment, writes_enabled_probe, health_probe, ): self.site = site self.store = store self.lock_path = Path(lock_path) callbacks = { "identity_probe": identity_probe, "history_probe": history_probe, "provenance_probe": provenance_probe, "backup_probe": backup_probe, "contain": contain, "containment_probe": containment_probe, "current_probe": current_probe, "activate": activate, "refresh": refresh, "readiness_probe": readiness_probe, "release_containment": release_containment, "writes_enabled_probe": writes_enabled_probe, "health_probe": health_probe, } for name, callback in callbacks.items(): require( callable(callback), "Missing recovery adapter", ) setattr(self, name, callback) def intent_path(self, identifier): return self.store.path( identifier, ".activation-intent.json", ) def result_path(self, identifier): return self.store.path( identifier, ".activation-result.json", ) def read_record(self, path): record = self.store.read(path) require( isinstance(record, dict) and "checksum" in record and type(record.get("format_version")) is int and record["format_version"] == 1, "Invalid recovery evidence", ) expected = canonical_hash({ key: value for key, value in record.items() if key != "checksum" }) require( expected == record["checksum"], "Recovery evidence checksum mismatch", ) return record def publish(self, path, record): data = dict(record) data["checksum"] = canonical_hash(data) return self.store.publish(path, data) def inspect(self, identifier): with DeploymentLock(self.lock_path): try: return self._inspect(identifier) except Exception: raise MigrationRecoveryError( "Migration recovery verification failed" ) from None def _inspect(self, identifier): approval = self.store.load(identifier) self.store.require_operator_policy().verify_seal(approval) context = approval["context"] validate_context(context) intent = self.read_record( self.store.path( identifier, ".migration-intent.json", ) ) consumed = self.read_record( self.store.consumed_path(identifier) ) result = self.read_record( self.store.path( identifier, ".migration-result.json", ) ) require( intent["status"] == "MIGRATION_INTENT" and consumed["status"] == "CONSUMED" and result["status"] == "MIGRATED", "Successful migration evidence required", ) for record in (intent, consumed, result): require( record["approval_id"] == identifier and record["site"] == self.site and record["site"] == context["site"] and record["release"] == context["release"] and record["revision"] == context["revision"] and record["database_identity"] == context["database_identity"], "Migration evidence identity mismatch", ) require( intent["approval_checksum"] == approval["checksum"] and consumed["approval_checksum"] == approval["checksum"] and result["intent_checksum"] == intent["checksum"] and result["consumption_checksum"] == consumed["checksum"], "Migration evidence chain mismatch", ) require( intent["context_fingerprint"] == canonical_hash(context), "Migration context fingerprint mismatch", ) for field in ( "backup_sha256", "rehearsal_fingerprint", ): require( intent[field] == context[field] and consumed[field] == context[field], "Migration evidence context mismatch", ) require( result["automatic_database_rollback"] is False and result["application_activated"] is False and result["containment_required"] is True and consumed["migration_executed"] is False, "Unexpected migration state", ) before = validate_history( intent["history_before"] ) pending = validate_history( context["pending_migrations"] ) require( not set(before).intersection(pending) and intent["pending_migrations"] == pending and result["applied_migrations"] == pending and result["history_after"] == before + pending, "Migration history evidence mismatch", ) require( self.identity_probe() == context["database_identity"], "Database identity changed", ) require( validate_history( self.history_probe() ) == result["history_after"], "Live migration history changed", ) release = context["release"] evidence = self.provenance_probe(release) require( isinstance(evidence, dict) and evidence.get("revision") == context["revision"] and evidence.get("fingerprint") == context["provenance"], "Candidate provenance changed", ) require( self.backup_probe() is True, "Backup integrity could not be verified", ) original = validate_original_release({ "release": intent.get("original_release"), "revision": intent.get("original_revision"), "fingerprint": intent.get("original_provenance"), }) current = self.current_probe() original_evidence = self.provenance_probe(original["release"]) require( current == original["release"] and current != release and isinstance(original_evidence, dict) and original_evidence.get("revision") == original["revision"] and original_evidence.get("fingerprint") == original["fingerprint"], "Original active release identity changed", ) require( isinstance(current, str) and current.isascii() and current.isdecimal() and not current.startswith("0") and len(current) <= 20, "Invalid active release", ) for path in ( self.intent_path(identifier), self.result_path(identifier), ): require( not os.path.lexists(path), "Existing activation evidence requires inspection", ) plan = { "format_version": 1, "status": "FORWARD_ACTIVATION_READY", "site": self.site, "approval_id": identifier, "current": current, "original_revision": original["revision"], "original_provenance": original["fingerprint"], "target": release, "revision": context["revision"], "provenance": context["provenance"], "database_identity": context["database_identity"], "backup_sha256": context["backup_sha256"], "history_after": result["history_after"], "migration_checksum": result["checksum"], "approval_checksum": approval["checksum"], "confirmation": "ACTIVATE-" + identifier, "automatic_database_rollback": False, "migration_reexecution_allowed": False, } plan["plan_fingerprint"] = canonical_hash(plan) return plan def execute( self, identifier, *, confirmation, fingerprint, ): with DeploymentLock(self.lock_path): return self._execute( identifier, confirmation, fingerprint, ) def _execute( self, identifier, confirmation, fingerprint, ): operation = "preflight" intent = None containment_started = False try: plan = self._inspect(identifier) require( confirmation == plan["confirmation"] and fingerprint == plan["plan_fingerprint"], "Activation confirmation or fingerprint changed", ) operation = "establish containment" containment_started = True require( self.contain() is True and self.containment_probe() is True, "Write containment failed", ) operation = "revalidate recovery evidence" require( self._inspect(identifier) == plan, "Migration recovery plan changed", ) operation = "persist activation intent" intent = self.publish( self.intent_path(identifier), { "format_version": 1, "status": "ACTIVATION_INTENT", "approval_id": identifier, "site": self.site, "target": plan["target"], "plan_fingerprint": fingerprint, "migration_checksum": ( plan["migration_checksum"] ), "created_at": datetime.now( timezone.utc ).isoformat(), }, ) operation = "activate migrated release" require( self.containment_probe() is True, "Containment lost before activation", ) target = plan["target"] require( self.activate(target) is True and self.current_probe() == target, "Candidate activation failed", ) operation = "refresh application" require( self.refresh() is True, "Application refresh failed", ) operation = "verify contained application" require( self.readiness_probe() is True and self.containment_probe() is True, "Contained application is not ready", ) require( self.identity_probe() == plan["database_identity"] and validate_history( self.history_probe() ) == plan["history_after"], "Database state changed during activation", ) evidence = self.provenance_probe(target) require( isinstance(evidence, dict) and evidence.get("revision") == plan["revision"] and evidence.get("fingerprint") == plan["provenance"] and self.current_probe() == target, "Candidate changed during activation", ) operation = "release containment" require( self.release_containment() is True and self.writes_enabled_probe() is True, "Application reopening failed", ) operation = "verify application health" report = self.health_probe(target) require( isinstance(report, dict) and report.get("healthy") is True and report.get("release") == target and self.current_probe() == target, "Application health verification failed", ) operation = "persist activation result" return self.publish( self.result_path(identifier), { "format_version": 1, "status": "VERIFIED", "approval_id": identifier, "site": self.site, "active_release": target, "intent_checksum": intent["checksum"], "plan_fingerprint": fingerprint, "health_verified": True, "database_restored": False, "migration_reexecuted": False, "completed_at": datetime.now( timezone.utc ).isoformat(), }, ) except Exception: containment_ok = None if containment_started: try: containment_ok = ( self.contain() is True and self.containment_probe() is True ) except Exception: containment_ok = False if intent is not None: try: path = self.result_path(identifier) if not os.path.lexists(path): self.publish( path, { "format_version": 1, "status": "FAILED", "approval_id": identifier, "intent_checksum": intent["checksum"], "operation": operation, "containment_verified": containment_ok, "manual_recovery_required": True, }, ) except Exception: pass raise MigrationRecoveryError( f"Forward activation failed during {operation}; " f"containment={containment_ok}; " "explicit inspection required" ) from None