Files
absdev-deployment/core/migration_archive.py
admin d6e2317016
ABSDEV Framework CI / framework-validation (push) Canceled after 0s
Initial ABSDEV deployment framework development preview
2026-11-26 11:35:28 +00:00

475 lines
12 KiB
Python

"""Logical archival of completed migration transactions.
Original approvals, consumption records and execution
evidence are retained permanently.
"""
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
class MigrationArchiveError(RuntimeError):
"""Migration archival evidence is unsafe or incomplete."""
SUFFIXES = (
".approval.json",
".migration-intent.json",
".consumed.json",
".migration-result.json",
".activation-intent.json",
".activation-result.json",
)
ARCHIVE_SUFFIX = ".migration-archive.json"
def require(condition, message):
if not condition:
raise MigrationArchiveError(message)
def digest(record):
return canonical_hash({
key: value
for key, value in record.items()
if key != "checksum"
})
def read_record(store, path):
record = store.read(path)
require(
isinstance(record, dict)
and type(record.get("format_version")) is int
and record["format_version"] == 1
and record.get("checksum") == digest(record),
"Invalid migration archival evidence",
)
return record
def read_chain(store, identifier):
approval = store.load(identifier)
context = approval["context"]
validate_context(context)
records = {
suffix: read_record(
store,
store.path(identifier, suffix),
)
for suffix in SUFFIXES
if suffix != ".approval.json"
}
records[".approval.json"] = approval
intent = records[".migration-intent.json"]
consumed = records[".consumed.json"]
migration = records[".migration-result.json"]
activation = records[".activation-intent.json"]
result = records[".activation-result.json"]
require(
intent["status"] == "MIGRATION_INTENT"
and consumed["status"] == "CONSUMED"
and migration["status"] == "MIGRATED"
and activation["status"] == "ACTIVATION_INTENT"
and result["status"] == "VERIFIED",
"Migration is not fully completed",
)
for suffix, record in records.items():
require(
record["approval_id"] == identifier,
"Approval identity mismatch",
)
if suffix != ".approval.json":
require(
record["site"] == context["site"],
"Migration site mismatch",
)
for record in (intent, consumed, migration):
for field in (
"release",
"revision",
"database_identity",
):
require(
record[field] == context[field],
"Migration context mismatch",
)
for record in (intent, consumed):
require(
record["approval_checksum"]
== approval["checksum"]
and record["backup_sha256"]
== context["backup_sha256"]
and record["rehearsal_fingerprint"]
== context["rehearsal_fingerprint"],
"Approval evidence mismatch",
)
require(
intent["context_fingerprint"]
== canonical_hash(context)
and migration["intent_checksum"]
== intent["checksum"]
and migration["consumption_checksum"]
== consumed["checksum"]
and activation["migration_checksum"]
== migration["checksum"]
and result["intent_checksum"]
== activation["checksum"]
and result["plan_fingerprint"]
== activation["plan_fingerprint"],
"Migration evidence chain mismatch",
)
before = intent["history_before"]
pending = context["pending_migrations"]
require(
isinstance(before, list)
and all(
isinstance(name, str)
for name in before
)
and len(before) == len(set(before))
and not set(before).intersection(pending)
and intent["pending_migrations"] == pending
and migration["applied_migrations"] == pending
and migration["history_after"] == before + pending,
"Migration history evidence mismatch",
)
require(
consumed["migration_executed"] is False
and migration["automatic_database_rollback"] is False
and migration["application_activated"] is False
and migration["containment_required"] is True
and activation["target"] == context["release"]
and result["active_release"] == context["release"]
and result["health_verified"] is True
and result["database_restored"] is False
and result["migration_reexecuted"] is False,
"Invalid migration completion evidence",
)
return records
def archive_path(store, identifier):
return store.path(
identifier,
ARCHIVE_SUFFIX,
)
def verify_archived_group(store, identifier):
"""Validate a historical archive without live probes."""
try:
record = read_record(
store,
archive_path(store, identifier),
)
records = read_chain(store, identifier)
context = records[".approval.json"]["context"]
require(
set(record) == {
"format_version",
"status",
"approval_id",
"site",
"release",
"record_checksums",
"plan_fingerprint",
"database_restored",
"archived_at",
"checksum",
}
and record["status"] == "ARCHIVED"
and record["approval_id"] == identifier
and record["site"] == context["site"]
and record["release"] == context["release"]
and record["database_restored"] is False,
"Invalid migration archive marker",
)
require(
record["record_checksums"] == {
suffix: item["checksum"]
for suffix, item in records.items()
},
"Archived migration evidence changed",
)
return {
identifier + suffix
for suffix in (*SUFFIXES, ARCHIVE_SUFFIX)
}
except MigrationArchiveError:
raise
except Exception:
raise MigrationArchiveError(
"Historical migration archive validation failed"
) from None
class MigrationArchive:
def __init__(
self,
*,
site,
store,
lock_path,
identity_probe,
history_probe,
provenance_probe,
backup_probe,
current_probe,
health_probe,
writes_enabled_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,
"current_probe": current_probe,
"health_probe": health_probe,
"writes_enabled_probe": writes_enabled_probe,
}
for name, callback in callbacks.items():
require(
callable(callback),
"Missing archival verification adapter",
)
setattr(self, name, callback)
def path(self, identifier):
return archive_path(
self.store,
identifier,
)
def _plan(self, identifier):
require(
not os.path.lexists(
self.path(identifier)
),
"Migration archive already exists",
)
records = read_chain(
self.store,
identifier,
)
context = records[".approval.json"]["context"]
migration = records[".migration-result.json"]
release = context["release"]
require(
context["site"] == self.site,
"Migration belongs to another site",
)
require(
self.current_probe() == release,
"Unexpected active release",
)
require(
self.identity_probe()
== context["database_identity"]
and self.history_probe()
== migration["history_after"],
"Database state changed",
)
provenance = self.provenance_probe(release)
require(
isinstance(provenance, dict)
and provenance.get("revision")
== context["revision"]
and provenance.get("fingerprint")
== context["provenance"],
"Release provenance changed",
)
require(
self.backup_probe() is True,
"Backup verification failed",
)
require(
self.writes_enabled_probe() is True,
"Application remains contained",
)
health = self.health_probe(release)
require(
isinstance(health, dict)
and health.get("healthy") is True
and health.get("release") == release,
"Application health verification failed",
)
require(
self.current_probe() == release
and read_chain(
self.store,
identifier,
) == records,
"Migration evidence changed during planning",
)
plan = {
"format_version": 1,
"status": "ARCHIVE_READY",
"approval_id": identifier,
"site": self.site,
"release": release,
"record_checksums": {
suffix: item["checksum"]
for suffix, item in records.items()
},
"confirmation": (
"ARCHIVE-MIGRATION-" + identifier
),
}
plan["fingerprint"] = canonical_hash(plan)
return plan
def plan(self, identifier):
with DeploymentLock(self.lock_path):
try:
return self._plan(identifier)
except MigrationArchiveError:
raise
except Exception:
raise MigrationArchiveError(
"Migration archival preflight failed"
) from None
def execute(
self,
identifier,
*,
confirmation,
fingerprint,
):
with DeploymentLock(self.lock_path):
with DeploymentLock(
self.store.directory / ".approval.lock"
):
try:
plan = self._plan(identifier)
require(
confirmation == plan["confirmation"]
and fingerprint == plan["fingerprint"],
"Archive confirmation or fingerprint changed",
)
record = {
"format_version": 1,
"status": "ARCHIVED",
"approval_id": identifier,
"site": self.site,
"release": plan["release"],
"record_checksums": (
plan["record_checksums"]
),
"plan_fingerprint": fingerprint,
"database_restored": False,
"archived_at": datetime.now(
timezone.utc
).isoformat(),
}
record["checksum"] = digest(record)
self.store.publish(
self.path(identifier),
record,
)
verify_archived_group(
self.store,
identifier,
)
return record
except MigrationArchiveError:
raise
except Exception:
raise MigrationArchiveError(
"Migration archival failed; "
"inspect preserved evidence"
) from None