# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-policy-has-crossed-its-own-rollback-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-policy-has-crossed-its-own-rollback-horizon.warrant.json
# Markdown SHA-256:   7def90cc9c1b4d01fc41da9efb0b44d0af42a4ff6d619cd77be4c4882eca89be
# Code AST SHA-256:   584ae959e25586031c179e1c44c8342577f85a57e54f2f02c238038cc88d9e48
# Verified Classes:   RollbackHorizonExceeded, SelfErasingRewrite, Policy, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class RollbackHorizonExceeded(RuntimeError):
    """Raised when a rollback target cannot falsify the active rewrite policies."""


class SelfErasingRewrite(RuntimeError):
    """Raised when a proposed context rewrite would evict its own justification."""


@dataclass(frozen=True)
class Policy:
    policy_id: str
    removed_span_ids: FrozenSet[str]
    justification_span_ids: FrozenSet[str]
    falsification_condition: str


@dataclass
class Checkpoint:
    index: int
    present_span_ids: FrozenSet[str]
    policy_ledger: FrozenSet[str] = field(default_factory=frozenset)

    def can_falsify(self, policy: Policy) -> bool:
        # Provenance-reconstructability: checkpoint must expose either the
        # removed spans, the justification spans, or a named tombstone.
        has_removed = policy.removed_span_ids <= self.present_span_ids
        has_justification = policy.justification_span_ids <= self.present_span_ids
        has_tombstone = policy.policy_id in self.policy_ledger
        return has_removed or has_justification or has_tombstone


def propose_rewrite(policy: Policy, current_trace_span_ids: FrozenSet[str]) -> None:
    # Scope-justification intersection: a rewrite whose predicate touches its
    # own rationale is self-erasing and must be gated or refused.
    if policy.justification_span_ids & policy.removed_span_ids:
        raise SelfErasingRewrite(
            f"policy {policy.policy_id} evicts its own justification spans "
            f"{sorted(policy.justification_span_ids & policy.removed_span_ids)}; "
            f"emit a tombstone or refuse the rewrite"
        )


def rollback(checkpoints: list[Checkpoint], target_index: int,
             active_policies: list[Policy]) -> Checkpoint:
    target = next((c for c in checkpoints if c.index == target_index), None)
    if target is None:
        raise RollbackHorizonExceeded(f"no checkpoint at index {target_index}")

    blind = [p.policy_id for p in active_policies if not target.can_falsify(p)]
    if blind:
        # Target restores bytes but cannot discriminate the rewrite that failed.
        raise RollbackHorizonExceeded(
            f"checkpoint {target_index} is below the rollback horizon: it cannot "
            f"falsify active policies {blind}. Do not retry; reconstruct from "
            f"external ground truth or tombstone ledger."
        )
    return target
