"""Migration coordination using injected trusted operations. No direct Docker, SQL, PHP or shell execution. """ import copy import os import re from pathlib import Path from core.approval import verify_approval, timestamp from core.rehearsal import approval_context from core.compatibility import canonical_hash from core.locking import DeploymentLock from core.operation_guard import OperationGuard from core.transactions import TransactionJournal class MigrationError(RuntimeError): """Migration failed or requires explicit recovery.""" def require(condition, message): if not condition: raise MigrationError(message) def validate_history(history): require( isinstance(history, list) and len(history) <= 100000, "Invalid migration history", ) for name in history: require( isinstance(name, str) and re.fullmatch( r"[A-Za-z0-9_][A-Za-z0-9_-]{0,254}", name, ) is not None, "Invalid migration history entry", ) require( len(history) == len(set(history)), "Duplicate migration history entries", ) return list(history) def validate_original_release(original): require(isinstance(original, dict) and set(original) == {"release", "revision", "fingerprint"}, "Missing original release identity") for key, pattern in (("release", r"[1-9][0-9]{0,19}"), ("revision", r"[a-f0-9]{40}"), ("fingerprint", r"[a-f0-9]{64}")): require(isinstance(original[key], str) and re.fullmatch(pattern, original[key]) is not None, "Invalid original release identity") return original class MigrationCoordinator: def __init__( self, *, store, lock_path, journal, original_release_probe, context_probe, contain, containment_probe, backup_probe, history_probe, migration_runner, application_probe, clock, ): for callback in ( original_release_probe, context_probe, contain, containment_probe, backup_probe, history_probe, migration_runner, application_probe, clock, ): require( callable(callback), "Missing migration operation adapter", ) require(isinstance(journal, TransactionJournal) and journal.migration_guard_directory() == store.directory and Path(lock_path) == journal.directory / ".deployment.lock", "Migration requires the bound ordinary journal") self.journal = journal self.original_release_probe = original_release_probe self.store = store self.operation_guard = OperationGuard(store) self.lock_path = Path(lock_path) self.context_probe = context_probe self.contain = contain self.containment_probe = containment_probe self.backup_probe = backup_probe self.history_probe = history_probe self.migration_runner = migration_runner self.application_probe = application_probe self.clock = clock def intent_path(self, identifier): return self.store.path( identifier, ".migration-intent.json" ) def result_path(self, identifier): return self.store.path( identifier, ".migration-result.json" ) def publish(self, path, data): record = dict(data) record["checksum"] = canonical_hash(record) return self.store.publish(path, record) def execute(self, identifier, rehearsal, *, confirmation): with DeploymentLock(self.lock_path): return self._execute( identifier, rehearsal, confirmation ) def _execute(self, identifier, rehearsal, confirmation): operation = "preflight" intent = None containment_started = False migration_started = False try: self.operation_guard.require_clear() intent_path = self.intent_path(identifier) result_path = self.result_path(identifier) for path in ( intent_path, result_path, self.store.consumed_path(identifier), ): require( not os.path.lexists(path), "Existing execution evidence requires review", ) rehearsal = copy.deepcopy(rehearsal) base = copy.deepcopy(self.context_probe()) current_time = timestamp(self.clock()) context = approval_context( rehearsal, base, now=current_time ) approval = self.store.load(identifier) verify_approval( approval, context, confirmation=confirmation, now=current_time, ) require( self.backup_probe() is True, "Backup verification failed", ) before = validate_history(self.history_probe()) pending = tuple(context["pending_migrations"]) require( not set(before).intersection(pending), "Pending migration already applied", ) operation = "persist migration intent" with DeploymentLock(self.journal.lock_path): self.journal.require_writes_allowed() original = copy.deepcopy(validate_original_release(self.original_release_probe())) require(original["release"] != context["release"], "Candidate is already active") intent = self.publish( intent_path, { "format_version": 1, "status": "MIGRATION_INTENT", "approval_id": identifier, "approval_checksum": approval["checksum"], "context_fingerprint": canonical_hash(context), "site": context["site"], "release": context["release"], "revision": context["revision"], "database_identity": context["database_identity"], "backup_sha256": context["backup_sha256"], "rehearsal_fingerprint": context["rehearsal_fingerprint"], "original_release": original["release"], "original_revision": original["revision"], "original_provenance": original["fingerprint"], "history_before": before, "pending_migrations": list(pending), "created_at": current_time.isoformat(), }, ) operation = "establish containment" containment_started = True require( self.contain() is True, "Write containment failed", ) require( self.containment_probe() is True, "Write containment not verified", ) operation = "revalidate migration context" require( self.context_probe() == base and self.original_release_probe() == original, "Migration context changed", ) require( self.backup_probe() is True, "Backup verification changed", ) require( validate_history(self.history_probe()) == before, "Migration history changed", ) require( self.store.load(identifier) == approval, "Stored approval changed", ) operation = "consume single-use approval" consumed = self.store.consume( identifier, base, rehearsal, confirmation=confirmation, now=self.clock(), ) require( consumed["approval_checksum"] == approval["checksum"], "Consumed approval mismatch", ) operation = "execute approved migrations" require( self.containment_probe() is True, "Write containment lost", ) migration_started = True result = self.migration_runner(pending) require( type(result) is int and result == 0, "Migration command failed", ) operation = "verify migration history" after = validate_history(self.history_probe()) require( after == before + list(pending), "Migration history differs from approval", ) require( self.containment_probe() is True, "Containment lost after migration", ) operation = "verify migrated application" require( self.application_probe() is True, "Application verification failed", ) require( self.containment_probe() is True, "Containment lost during verification", ) operation = "persist migration result" return self.publish( result_path, { "format_version": 1, "status": "MIGRATED", "approval_id": identifier, "intent_checksum": intent["checksum"], "consumption_checksum": consumed["checksum"], "site": context["site"], "release": context["release"], "revision": context["revision"], "database_identity": context["database_identity"], "history_after": after, "applied_migrations": list(pending), "automatic_database_rollback": False, "application_activated": False, "containment_required": True, "completed_at": timestamp(self.clock()).isoformat(), }, ) except Exception: containment_ok = None evidence_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: if not os.path.lexists(result_path): self.publish( result_path, { "format_version": 1, "status": "FAILED", "approval_id": identifier, "intent_checksum": intent["checksum"], "operation": operation, "migration_may_have_executed": migration_started, "manual_recovery_required": True, "automatic_database_rollback": False, "containment_verified": containment_ok, }, ) evidence_ok = True else: evidence_ok = False except Exception: evidence_ok = False raise MigrationError( f"Migration failed during {operation}; " f"containment={containment_ok}; " f"failure_evidence={evidence_ok}; " "explicit inspection required" ) from None