# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-policy-and-the-rollback-target-is-itself-rewritten.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-policy-and-the-rollback-target-is-itself-rewritten.warrant.json
# Markdown SHA-256:   2da27d6cd8e9fc067c7fb6a3a584399293fc356cd331d6a56008a4146e9095fd
# Code AST SHA-256:   a0b48827c47b36816faabb31f88484fa0603ca3ed3ac15ee2e1390a882a34d4c
# Verified Classes:   ContaminatedRollbackError, PolicySnapshot, ContextPolicyStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ContaminatedRollbackError(RuntimeError):
    """Raised when a policy rollback would be executed under the very policy
    it is trying to escape, or when reconstruction depends on mutable base
    state that the active policy can evict."""
    pass


class PolicySnapshot:
    def __init__(self, version: str, entries: dict, full_materialization: bool, author: str):
        self.version = version
        self.entries = entries
        self.full_materialization = full_materialization
        self.author = author


class ContextPolicyStore:
    """Append-only store for policy snapshots. The active policy may write NEW
    snapshots here but may never mutate or evict existing ones."""

    def __init__(self):
        self._snapshots: dict[str, PolicySnapshot] = {}
        self._active: str | None = None

    def commit(self, snap: PolicySnapshot) -> None:
        if snap.version in self._snapshots:
            raise ContaminatedRollbackError(
                f"snapshot {snap.version} already exists; policy store is append-only"
            )
        self._snapshots[snap.version] = snap
        self._active = snap.version

    def get(self, version: str) -> PolicySnapshot:
        if version not in self._snapshots:
            raise ContaminatedRollbackError(f"unknown snapshot {version}")
        return self._snapshots[version]


def rollback_policy(
    store: ContextPolicyStore,
    target_version: str,
    requesting_instance: str,
    executor_id: str,
    executor_policy_independent: bool,
    base_entries_present: bool,
) -> PolicySnapshot:
    """Rollback is sound only if the executor is policy-independent, the target
    is a full materialization, and no base entry is missing. Any violation is a
    hard error — never a substitution."""
    target = store.get(target_version)

    if not executor_policy_independent:
        raise ContaminatedRollbackError(
            f"executor {executor_id} consults the active policy; rollback would be "
            f"circular for instance {requesting_instance}"
        )
    if not target.full_materialization:
        raise ContaminatedRollbackError(
            f"snapshot {target_version} is a delta against mutable live state; "
            f"its base may have been evicted by the active policy"
        )
    if not base_entries_present:
        raise ContaminatedRollbackError(
            f"reconstruction of {target_version} is missing base entries; "
            f"substitution would produce a hybrid state that no version describes"
        )

    store._active = target_version
    return target
