"""Archival of successfully rolled-back transactions. Preserve original evidence and quarantine failed candidates. Never restore databases or automatically repeat a rollback. """ import os import re from datetime import datetime, timezone from core.approval_store import ApprovalStore from core.archive import ArchiveError, require, digest, sync_directory from core.backup_evidence import FIELDS from core.compatibility import ( canonical_hash, require_compatible, validate_provenance, ) from core.locking import DeploymentLock from core.recovery import ROLLBACK_ELIGIBLE_PHASES class RollbackArchiveReader: def __init__(self, *, site, journal, directory, backup_evidence): self.site = site self.journal = journal self.backup_evidence = backup_evidence self.source = ApprovalStore(journal.directory) self.destination = ApprovalStore(directory) require(self.source.directory != self.destination.directory, "Archive directory must be separate") def path(self, identifier): return self.destination.path( identifier, ".rollback-archive.json", ) def read_record(self, suffix, identifier): record = self.source.read( self.source.path(identifier, suffix) ) require( isinstance(record, dict) and type(record.get("format_version")) is int and record["format_version"] == 1 and record.get("checksum") == digest(record), "Invalid rollback evidence", ) return record def read_chain(self, transaction): identifier = transaction["transaction_id"] intent = self.read_record( ".rollback-intent.json", identifier, ) result = self.read_record( ".rollback-result.json", identifier, ) require( transaction["phase"] in ROLLBACK_ELIGIBLE_PHASES and intent["status"] == "ROLLBACK_INTENT" and result["status"] == "ROLLED_BACK", "Completed rollback of a failed or interrupted activation required", ) phases = { event["phase"] for event in transaction["history"] } require( {"BACKED_UP", "QUIESCED", "ACTIVATING"} <= phases, "Incomplete deployment transaction history", ) for record in (intent, result): require( record["transaction_id"] == identifier and record["site"] == transaction["site"], "Rollback identity mismatch", ) require( intent["transaction_checksum"] == transaction["checksum"] and result["intent_checksum"] == intent["checksum"] and result["plan_fingerprint"] == intent["plan_fingerprint"], "Rollback evidence chain mismatch", ) require( isinstance(intent["plan_fingerprint"], str) and re.fullmatch( r"[a-f0-9]{64}", intent["plan_fingerprint"], ) is not None, "Invalid rollback plan fingerprint", ) require( intent["source"] == transaction["candidate"] and intent["target"] == transaction["previous"] and result["previous_active_release"] == transaction["candidate"] and result["active_release"] == transaction["previous"] and result["health_verified"] is True and result["database_restored"] is False, "Rollback result mismatch", ) evidence = self.backup_evidence.load( identifier ) require( evidence["backup"]["backup_id"] == intent["backup_id"] and evidence["backup"]["sha256"] == intent["backup_sha256"], "Rollback backup evidence mismatch", ) return intent, result, evidence def load(self, identifier): try: record = self.destination.read( self.path(identifier) ) require( isinstance(record, dict) and record.get("status") == "ARCHIVED" and record.get("site") == self.site and record.get("database_restored") is False and record.get("checksum") == digest(record), "Invalid rollback archive", ) transaction = record["transaction"] self.journal.validate(transaction) require( transaction["transaction_id"] == identifier and transaction["site"] == self.site, "Archived transaction identity mismatch", ) intent, result, evidence = self.read_chain( transaction ) require( record["rollback_intent"] == intent and record["rollback_result"] == result and record["backup_evidence"] == evidence, "Archived evidence mismatch", ) return record except ArchiveError: raise except Exception: raise ArchiveError( "Rollback archive validation failed" ) from None class RollbackArchive(RollbackArchiveReader): def __init__(self, *, planner, directory, health_probe): require(callable(health_probe), "Health verification is required") super().__init__(site=planner.site, journal=planner.journal, directory=directory, backup_evidence=planner.backup_evidence) self.planner = planner self.releases = planner.releases self.health_probe = health_probe def _plan(self): self.destination.validate_directory() transaction = self.journal.load() require( transaction is not None and transaction["phase"] in ROLLBACK_ELIGIBLE_PHASES and transaction["site"] == self.planner.site, "Failed or interrupted deployment transaction required", ) identifier = transaction["transaction_id"] require( not os.path.lexists(self.path(identifier)), "Existing archive requires inspection", ) intent, result, evidence = self.read_chain( transaction ) previous = transaction["previous"] candidate = transaction["candidate"] require( self.releases.current() == previous, "Previous release is not active", ) old = self.planner.provenance.verify( self.releases.validate(previous) ) new = self.planner.provenance.verify( self.releases.validate(candidate) ) validate_provenance(old) validate_provenance(new) require( old["revision"] == transaction["previous_revision"] and old["fingerprint"] == transaction["previous_provenance"] and new["revision"] == transaction["revision"] and new["fingerprint"] == transaction["provenance"], "Release provenance changed", ) require_compatible(new, old) backup = evidence["backup"] manifest = self.planner.backup_verify( backup["backup_id"] ) require( isinstance(manifest, dict) and FIELDS <= set(manifest) and { field: manifest[field] for field in FIELDS } == backup, "Backup verification failed", ) require( self.planner.runtime_check() is True, "Database runtime verification failed", ) health = self.health_probe(previous) require( isinstance(health, dict) and health.get("healthy") is True and health.get("release") == previous, "Rolled-back application is unhealthy", ) marker = ( self.releases.release_path(candidate) / "BAD_RELEASE" ) require( not os.path.lexists(marker), "Existing failed-release marker requires review", ) require( self.journal.load() == transaction and self.releases.current() == previous and self.read_chain(transaction) == (intent, result, evidence), "Rollback state changed", ) plan = { "format_version": 1, "status": "ARCHIVE_READY", "site": transaction["site"], "transaction_id": identifier, "transaction_checksum": transaction["checksum"], "intent_checksum": intent["checksum"], "result_checksum": result["checksum"], "backup_evidence_checksum": evidence["checksum"], "active_release": previous, "failed_release": candidate, "confirmation": "ARCHIVE-ROLLBACK-" + identifier, } plan["fingerprint"] = canonical_hash(plan) return plan def plan(self): with DeploymentLock(self.planner.lock_path): try: return self._plan() except ArchiveError: raise except Exception: raise ArchiveError( "Rollback archival preflight failed" ) from None def execute(self, *, confirmation, fingerprint): with DeploymentLock(self.planner.lock_path): with DeploymentLock(self.journal.lock_path): try: return self._execute( confirmation, fingerprint, ) except ArchiveError: raise except Exception: raise ArchiveError( "Rollback archival interrupted; " "inspect preserved evidence" ) from None def _execute(self, confirmation, fingerprint): self.journal.require_writes_allowed() plan = self._plan() require( confirmation == plan["confirmation"] and fingerprint == plan["fingerprint"], "Rollback archival confirmation mismatch", ) transaction = self.journal.load() identifier = plan["transaction_id"] require( transaction["checksum"] == plan["transaction_checksum"], "Transaction changed", ) intent, result, evidence = self.read_chain( transaction ) require( intent["checksum"] == plan["intent_checksum"] and result["checksum"] == plan["result_checksum"] and evidence["checksum"] == plan["backup_evidence_checksum"], "Rollback evidence changed", ) record = { "format_version": 1, "status": "ARCHIVED", "site": plan["site"], "transaction": transaction, "rollback_intent": intent, "rollback_result": result, "backup_evidence": evidence, "plan_fingerprint": fingerprint, "database_restored": False, "archived_at": datetime.now( timezone.utc ).isoformat(), } record["checksum"] = digest(record) # Preserve all transaction evidence before modifying # the failed release or retiring the active journal. self.destination.publish( self.path(identifier), record, ) require( self.load(identifier) == record, "Archive readback failed", ) require( self.releases.current() == plan["active_release"] and self.journal.load() == transaction and self.planner.runtime_check() is True, "Runtime state changed before retirement", ) candidate = self.releases.validate( plan["failed_release"] ) marker = candidate / "BAD_RELEASE" fd = os.open( marker, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600, ) with os.fdopen(fd, "w") as handle: handle.write( identifier + "\n" + record["checksum"] + "\n" ) handle.flush() os.fsync(handle.fileno()) sync_directory(candidate) require( self.releases.current() == plan["active_release"] and self.journal.load() == transaction, "Deployment state changed during retirement", ) # Only retire the journal once the durable archive # and failed-release marker are present. self.journal.path.unlink() sync_directory(self.journal.directory) require( self.journal.load() is None, "Journal retirement failed", ) return record