"""Read-only release retention planning. The caller must supply a complete and trustworthy inventory of releases and transaction protections. No filesystem modification is performed. """ import os import re import stat from core.compatibility import canonical_hash class RetentionError(RuntimeError): """Invalid or unsafe release retention policy.""" FIELDS = { "inventory", "current", "keep", "protected", "failed", "unresolved", } def require(condition, message): if not condition: raise RetentionError(message) def validate_release(value): require( isinstance(value, str) and re.fullmatch( r"[1-9][0-9]{0,19}", value, ) is not None, "Invalid release identifier", ) def validate_inventory(values): require( isinstance(values, list) and len(values) <= 100000, "Invalid release inventory", ) for value in values: validate_release(value) require( len(values) == len(set(values)), "Duplicate release identifiers", ) return sorted(values, key=int) def plan_retention(policy): require( isinstance(policy, dict) and set(policy) == FIELDS, "Invalid retention policy structure", ) inventory = validate_inventory( policy["inventory"] ) require( bool(inventory), "Release inventory is empty", ) current = policy["current"] validate_release(current) available = set(inventory) require( current in available, "Active release missing from inventory", ) keep = policy["keep"] require( type(keep) is int and 2 <= keep <= 1000, "Retention count must be between 2 and 1000", ) protections = {} for field in ( "protected", "failed", "unresolved", ): values = validate_inventory( policy[field] ) require( set(values) <= available, f"Unknown release in {field} inventory", ) protections[field] = values failed = set(protections["failed"]) require( current not in failed, "Active release is marked failed", ) reasons = {} def protect(release, reason): reasons.setdefault(release, set()).add(reason) protect(current, "active") for release in inventory[-keep:]: protect(release, "recent_release") for release in protections["protected"]: protect(release, "explicitly_protected") for release in protections["failed"]: protect(release, "failed_release") for release in protections["unresolved"]: protect(release, "unresolved_transaction") previous = [ release for release in inventory if int(release) < int(current) and release not in failed ] if previous: protect(previous[-1], "previous_available") blocked = bool(protections["unresolved"]) if blocked: for release in inventory: protect(release, "operation_unresolved") retained = [ release for release in inventory if release in reasons ] candidates = [ release for release in inventory if release not in reasons ] plan = { "format_version": 1, "status": "BLOCKED" if blocked else "READY", "current": current, "keep": keep, "inventory": inventory, "protected": protections["protected"], "failed": protections["failed"], "unresolved": protections["unresolved"], "retained": retained, "archive_candidates": candidates, "reasons": { release: sorted(reasons[release]) for release in retained }, "automatic_archival": False, "automatic_deletion": False, "execution_permitted": False, } plan["fingerprint"] = canonical_hash(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): """Read canonical runtime state under its deployment and journal locks.""" from pathlib import Path from core.approval_store import ApprovalStore from core.archive import TransactionArchive from core.backup_evidence import BackupEvidence from core.locking import DeploymentLock from core.operation_guard import OperationGuard from core.releases import ReleaseManager from core.rollback_archive import RollbackArchiveReader from core.transactions import TransactionJournal root = Path(runtime_root) require(root.is_absolute() and root.resolve() == root, "Invalid retention runtime directory") try: journal = TransactionJournal(root / "state") with DeploymentLock(journal.directory / ".deployment.lock"), DeploymentLock(journal.lock_path): approvals = journal.migration_guard_directory() require(approvals == root / "approvals", "Missing trusted migration guard binding") guard = OperationGuard(ApprovalStore(approvals)).inspect() transaction = journal.load() releases = ReleaseManager(root / "app") inventory = releases.inventory() current = releases.current() protected = set() failed = set() retired = False archive_directory = root / "archive" 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), "Configured site identity required for retention archives") archives = TransactionArchive( site=site, directory=archive_directory, lock_path=journal.directory / ".deployment.lock", journal=journal, releases=releases, provenance=None, backup_evidence=BackupEvidence(journal.directory), backup_verify=None, health_probe=None, ) rollbacks = RollbackArchiveReader( site=site, journal=journal, directory=archive_directory, backup_evidence=BackupEvidence(journal.directory), ) matching = [] for path in archive_directory.iterdir(): match = re.fullmatch(r"([a-f0-9]{32})\.(archive|rollback-archive)\.json", path.name) require(match is not None, "Unexpected retention archive entry") 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"])) if active == current: matching.append(archived) if transaction is None: require(len(matching) == 1, "Active release has no unambiguous verified archive") transaction = matching[0] retired = True require(transaction is not None, "No verified retention transaction") require(site is None or transaction["site"] == site, "Retention transaction belongs to another site") references = [transaction["previous"], transaction["candidate"]] protected.update(references) require(current in references, "Live active release differs from the transaction") unresolved = ( (not retired and (transaction["phase"] != "VERIFIED" or current != transaction["candidate"])) or guard["status"] != "CLEAR" ) plan = plan_retention({ "inventory": inventory, "current": current, "keep": keep, "protected": sorted(protected), "failed": sorted(failed), "unresolved": inventory if unresolved else [], }) del plan["fingerprint"] plan.update(inventory_source="site_runtime", journal_checksum=transaction["checksum"]) plan["fingerprint"] = canonical_hash(plan) return plan except RetentionError: raise except Exception: raise RetentionError("Unable to verify trusted retention inventory") from None