"""Explicit application rollback with persistent intent. Database restoration is intentionally unsupported. External operations must use trusted service adapters. """ import json import os import re import stat import uuid from datetime import datetime, timezone from core.compatibility import canonical_hash from core.locking import DeploymentLock class RollbackError(RuntimeError): """Rollback failed or requires explicit inspection.""" def require(condition, message): if not condition: raise RollbackError(message) def now(): return datetime.now(timezone.utc).isoformat() class RollbackExecutor: def __init__( self, *, planner, services, health, stopped_check, ): require( callable(stopped_check), "Worker state verification is required", ) self.planner = planner self.services = services self.health = health self.stopped_check = stopped_check self.directory = planner.journal.directory self.validate_directory() def validate_directory(self): directory = self.directory require( directory.is_dir() and not directory.is_symlink() and directory.resolve() == directory, "Invalid rollback evidence directory", ) details = directory.stat() require( details.st_uid == os.getuid() and stat.S_IMODE(details.st_mode) == 0o700, "Unsafe rollback evidence directory permissions", ) def evidence_path(self, transaction_id, suffix): require( isinstance(transaction_id, str) and re.fullmatch( r"[a-f0-9]{32}", transaction_id, ) is not None, "Invalid rollback transaction identifier", ) return self.directory / ( transaction_id + suffix ) def intent_path(self, transaction_id): return self.evidence_path( transaction_id, ".rollback-intent.json", ) def result_path(self, transaction_id): return self.evidence_path( transaction_id, ".rollback-result.json", ) def publish(self, path, data): self.validate_directory() require( path.parent == self.directory, "Invalid rollback evidence path", ) data = dict(data) data["checksum"] = canonical_hash(data) temporary = self.directory / ( ".rollback-" + uuid.uuid4().hex ) fd = None created = False try: fd = os.open( temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600, ) created = True with os.fdopen(fd, "w") as handle: fd = None json.dump( data, handle, sort_keys=True, indent=2, allow_nan=False, ) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.link( temporary, path, follow_symlinks=False, ) temporary.unlink() created = False directory_fd = os.open( self.directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, ) try: os.fsync(directory_fd) finally: os.close(directory_fd) require( json.loads(path.read_text()) == data, "Rollback evidence readback failed", ) return data except OSError: raise RollbackError( "Rollback evidence persistence failed" ) from None finally: if fd is not None: os.close(fd) if created: temporary.unlink(missing_ok=True) def execute(self, confirmation, fingerprint): with DeploymentLock(self.planner.lock_path): return self._execute( confirmation, fingerprint, ) def _execute(self, confirmation, fingerprint): operation = "preflight" quiesce_started = False intent = None result_path = None try: # The deployment lock is already held. # Do not call inspect(), which reacquires it. plan = self.planner._inspect() require( plan["status"] == "ROLLBACK_REVIEW_READY", "Transaction is not eligible for rollback", ) require( isinstance(confirmation, str) and confirmation == plan["confirmation"], "Rollback confirmation mismatch", ) require( isinstance(fingerprint, str) and fingerprint == plan["plan_fingerprint"], "Rollback plan changed", ) transaction_id = plan["transaction_id"] intent_path = self.intent_path(transaction_id) result_path = self.result_path(transaction_id) for path in (intent_path, result_path): require( not os.path.lexists(path), "Existing rollback evidence requires review", ) operation = "persist rollback intent" intent = self.publish( intent_path, { "format_version": 1, "status": "ROLLBACK_INTENT", "transaction_id": transaction_id, "site": plan["site"], "source": plan["current"], "target": plan["target"], "transaction_checksum": ( plan["transaction_checksum"] ), "plan_fingerprint": fingerprint, "backup_id": plan["backup_id"], "backup_sha256": plan["backup_sha256"], "created_at": now(), }, ) operation = "quiesce workers" quiesce_started = True self.services.quiesce() require( self.stopped_check() is True, "Background workers remain active", ) operation = "revalidate recovery plan" require( self.planner._inspect() == plan, "Recovery evidence changed after shutdown", ) operation = "activate previous release" target = plan["target"] self.planner.releases.activate(target) require( self.planner.releases.current() == target, "Rollback activation verification failed", ) operation = "refresh application" self.services.refresh() operation = "restore workers" self.services.resume() operation = "verify application health" health = self.health.verify(target) require( isinstance(health, dict) and health.get("healthy") is True and health.get("release") == target, "Rollback health verification failed", ) require( self.planner.releases.current() == target, "Active release changed during rollback", ) require( self.planner.journal.load()["checksum"] == plan["transaction_checksum"], "Original transaction changed", ) operation = "persist rollback result" return self.publish( result_path, { "format_version": 1, "status": "ROLLED_BACK", "site": plan["site"], "transaction_id": transaction_id, "intent_checksum": intent["checksum"], "plan_fingerprint": fingerprint, "previous_active_release": ( plan["current"] ), "active_release": target, "health_verified": True, "database_restored": False, "completed_at": now(), }, ) except Exception: containment = None if quiesce_started: try: self.services.quiesce() containment = ( self.stopped_check() is True ) except Exception: containment = False # Preserve the original transaction and intent. # Never automatically activate another release. raise RollbackError( f"Rollback failed during {operation}; " f"workers_contained={containment}; " "explicit inspection required" ) from None