Retain releases from verified rollback archives
ABSDEV Framework CI / framework-ci (push) Successful in 20s

This commit is contained in:
Mark Gregory
2026-11-30 10:21:15 +00:00
parent 84a7a5b237
commit 2a001b1269
4 changed files with 110 additions and 33 deletions
+39 -7
View File
@@ -6,7 +6,9 @@ inventory of releases and transaction protections.
No filesystem modification is performed. No filesystem modification is performed.
""" """
import os
import re import re
import stat
from core.compatibility import canonical_hash from core.compatibility import canonical_hash
@@ -191,6 +193,19 @@ def plan_retention(policy):
return plan return plan
def verify_rollback_marker(releases, archived):
transaction = archived["transaction"]
marker = releases.release_path(transaction["candidate"]) / "BAD_RELEASE"
expected = (transaction["transaction_id"] + "\n" + archived["checksum"] + "\n").encode()
descriptor = os.open(marker, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC)
with os.fdopen(descriptor, "rb") as stream:
info = os.fstat(stream.fileno())
require(stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid()
and stat.S_IMODE(info.st_mode) == 0o600 and info.st_nlink == 1,
"Unsafe rollback quarantine marker")
require(stream.read(len(expected) + 1) == expected, "Rollback quarantine marker mismatch")
def plan_site_retention(runtime_root, *, keep, site=None): def plan_site_retention(runtime_root, *, keep, site=None):
"""Read canonical runtime state under its deployment and journal locks.""" """Read canonical runtime state under its deployment and journal locks."""
from pathlib import Path from pathlib import Path
@@ -201,6 +216,7 @@ def plan_site_retention(runtime_root, *, keep, site=None):
from core.locking import DeploymentLock from core.locking import DeploymentLock
from core.operation_guard import OperationGuard from core.operation_guard import OperationGuard
from core.releases import ReleaseManager from core.releases import ReleaseManager
from core.rollback_archive import RollbackArchiveReader
from core.transactions import TransactionJournal from core.transactions import TransactionJournal
root = Path(runtime_root) root = Path(runtime_root)
@@ -216,6 +232,8 @@ def plan_site_retention(runtime_root, *, keep, site=None):
inventory = releases.inventory() inventory = releases.inventory()
current = releases.current() current = releases.current()
protected = set() protected = set()
failed = set()
retired = False
archive_directory = root / "archive" archive_directory = root / "archive"
if archive_directory.exists() or archive_directory.is_symlink(): if archive_directory.exists() or archive_directory.is_symlink():
require(isinstance(site, str) and re.fullmatch(r"[a-z0-9][a-z0-9-]{0,62}", site), require(isinstance(site, str) and re.fullmatch(r"[a-z0-9][a-z0-9-]{0,62}", site),
@@ -226,25 +244,39 @@ def plan_site_retention(runtime_root, *, keep, site=None):
releases=releases, provenance=None, backup_evidence=BackupEvidence(journal.directory), releases=releases, provenance=None, backup_evidence=BackupEvidence(journal.directory),
backup_verify=None, health_probe=None, backup_verify=None, health_probe=None,
) )
rollbacks = RollbackArchiveReader(
site=site, journal=journal, directory=archive_directory,
backup_evidence=BackupEvidence(journal.directory),
)
matching = [] matching = []
for path in archive_directory.iterdir(): for path in archive_directory.iterdir():
require(re.fullmatch(r"[a-f0-9]{32}\.archive\.json", path.name), match = re.fullmatch(r"([a-f0-9]{32})\.(archive|rollback-archive)\.json", path.name)
"Unexpected retention archive entry") require(match is not None, "Unexpected retention archive entry")
archived = archives.load(path.name[:32])["transaction"] identifier, kind = match.groups()
if kind == "rollback-archive":
record = rollbacks.load(identifier)
verify_rollback_marker(releases, record)
archived = record["transaction"]
failed.add(archived["candidate"])
active = archived["previous"]
else:
archived = archives.load(identifier)["transaction"]
active = archived["candidate"]
protected.update((archived["previous"], archived["candidate"])) protected.update((archived["previous"], archived["candidate"]))
if archived["candidate"] == current: if active == current:
matching.append(archived) matching.append(archived)
if transaction is None: if transaction is None:
require(len(matching) == 1, "Active release has no unambiguous verified archive") require(len(matching) == 1, "Active release has no unambiguous verified archive")
transaction = matching[0] transaction = matching[0]
retired = True
require(transaction is not None, "No verified retention transaction") require(transaction is not None, "No verified retention transaction")
require(site is None or transaction["site"] == site, "Retention transaction belongs to another site") require(site is None or transaction["site"] == site, "Retention transaction belongs to another site")
references = [transaction["previous"], transaction["candidate"]] references = [transaction["previous"], transaction["candidate"]]
protected.update(references) protected.update(references)
require(current in references, "Live active release differs from the transaction") require(current in references, "Live active release differs from the transaction")
unresolved = ( unresolved = (
transaction["phase"] != "VERIFIED" (not retired and (transaction["phase"] != "VERIFIED"
or current != transaction["candidate"] or current != transaction["candidate"]))
or guard["status"] != "CLEAR" or guard["status"] != "CLEAR"
) )
plan = plan_retention({ plan = plan_retention({
@@ -252,7 +284,7 @@ def plan_site_retention(runtime_root, *, keep, site=None):
"current": current, "current": current,
"keep": keep, "keep": keep,
"protected": sorted(protected), "protected": sorted(protected),
"failed": [], "failed": sorted(failed),
"unresolved": inventory if unresolved else [], "unresolved": inventory if unresolved else [],
}) })
del plan["fingerprint"] del plan["fingerprint"]
+20 -22
View File
@@ -20,26 +20,15 @@ from core.compatibility import (
from core.locking import DeploymentLock from core.locking import DeploymentLock
class RollbackArchive: class RollbackArchiveReader:
def __init__(self, *, site, journal, directory, backup_evidence):
def __init__(self, *, planner, directory, health_probe): self.site = site
require( self.journal = journal
callable(health_probe), self.backup_evidence = backup_evidence
"Health verification is required", self.source = ApprovalStore(journal.directory)
)
self.planner = planner
self.journal = planner.journal
self.releases = planner.releases
self.health_probe = health_probe
self.source = ApprovalStore(self.journal.directory)
self.destination = ApprovalStore(directory) self.destination = ApprovalStore(directory)
require(self.source.directory != self.destination.directory,
require( "Archive directory must be separate")
self.source.directory != self.destination.directory,
"Archive directory must be separate",
)
def path(self, identifier): def path(self, identifier):
return self.destination.path( return self.destination.path(
@@ -130,7 +119,7 @@ class RollbackArchive:
"Rollback result mismatch", "Rollback result mismatch",
) )
evidence = self.planner.backup_evidence.load( evidence = self.backup_evidence.load(
identifier identifier
) )
@@ -153,7 +142,7 @@ class RollbackArchive:
require( require(
isinstance(record, dict) isinstance(record, dict)
and record.get("status") == "ARCHIVED" and record.get("status") == "ARCHIVED"
and record.get("site") == self.planner.site and record.get("site") == self.site
and record.get("database_restored") is False and record.get("database_restored") is False
and record.get("checksum") == digest(record), and record.get("checksum") == digest(record),
"Invalid rollback archive", "Invalid rollback archive",
@@ -165,7 +154,7 @@ class RollbackArchive:
require( require(
transaction["transaction_id"] == identifier transaction["transaction_id"] == identifier
and transaction["site"] == self.planner.site, and transaction["site"] == self.site,
"Archived transaction identity mismatch", "Archived transaction identity mismatch",
) )
@@ -190,6 +179,15 @@ class RollbackArchive:
"Rollback archive validation failed" "Rollback archive validation failed"
) from None ) 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): def _plan(self):
self.destination.validate_directory() self.destination.validate_directory()
+5 -4
View File
@@ -11,10 +11,11 @@ The existing `--policy` command evaluates caller-supplied data as a simulation.
Both outputs are read-only. They grant no archival or deletion authority. Both outputs are read-only. They grant no archival or deletion authority.
For an existing runtime with retired deployment journals, place verified For an existing runtime with retired deployment journals, place verified
ordinary transaction archives in the canonical `archive/` directory and ordinary transaction and rollback archives in the canonical `archive/` directory and
supply `--site` with the configured site identifier. Each archive must pass supply `--site` with the configured site identifier. Each archive must pass
the framework's transaction and backup evidence validation. When the live the framework's transaction and backup evidence validation. When the live
journal is absent, exactly one archived verified transaction must match the journal is absent, exactly one archived verified transaction must match the
active release. All releases referenced by validated archives are protected. active release. Rollback archives also require their original rollback and
Unknown archive entries, rollback archive formats, and ambiguous or corrupt backup evidence and the failed release's matching quarantine marker. All
records deny planning pending review. releases referenced by validated archives are protected. Unknown, ambiguous
or corrupt archive entries deny planning pending review.
+46
View File
@@ -46,3 +46,49 @@ class ArchivedRetentionTests(unittest.TestCase):
(self.path.parent / "unknown.json").write_text("{}") (self.path.parent / "unknown.json").write_text("{}")
with self.assertRaises(RetentionError): with self.assertRaises(RetentionError):
self.plan() self.plan()
class RollbackRetentionTests(unittest.TestCase):
def setUp(self):
import test_rollback_archive
from core.approval_store import ApprovalStore
fixture = test_rollback_archive.RollbackArchiveTests()
self.addCleanup(fixture.doCleanups)
fixture.setUp()
self.root = fixture.recovery.root.resolve()
approvals = self.root / "approvals"
approvals.mkdir(mode=0o700, exist_ok=True)
fixture.journal.bind_migration_guard(ApprovalStore(approvals))
canonical = self.root / "archive"
fixture.directory.rename(canonical)
fixture.archive.destination = ApprovalStore(canonical)
self.record = fixture.execute()
self.journal = fixture.journal
self.marker = fixture.marker
self.archive_path = fixture.archive.path(fixture.identifier)
def plan(self):
return plan_site_retention(self.root, keep=2, site=self.record["site"])
def test_retired_rollback_preserves_failed_candidate(self):
marker_before = self.marker.read_bytes()
archive_before = self.archive_path.read_bytes()
plan = self.plan()
self.assertEqual(plan["status"], "READY")
self.assertEqual(plan["current"], "1")
self.assertEqual(plan["failed"], ["2"])
self.assertEqual(plan["retained"], ["1", "2", "3"])
self.assertIn("failed_release", plan["reasons"]["2"])
self.assertFalse(plan["execution_permitted"])
self.assertIsNone(self.journal.load())
self.assertEqual(marker_before, self.marker.read_bytes())
self.assertEqual(archive_before, self.archive_path.read_bytes())
def test_tampered_or_missing_quarantine_marker_denies_planning(self):
self.marker.write_text("wrong")
with self.assertRaises(RetentionError):
self.plan()
self.marker.unlink()
with self.assertRaises(RetentionError):
self.plan()