# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-context-pruning-when-the-retention-policy-is-itself-rewritten-mid-episode.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-context-pruning-when-the-retention-policy-is-itself-rewritten-mid-episode.warrant.json
# Markdown SHA-256:   c4c843c149f193bee86201495b07310e74c0def03bab0813a36372e8bfb23cef
# Code AST SHA-256:   106537ace62863e5b550fb623ce9caa1a30a16b7c19fc4a8c61d8caf53329b04
# Verified Classes:   PolicyContaminationError, StalePolicyError, ContextState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class PolicyContaminationError(RuntimeError):
    """Raised when a pruning cycle mutated or lost the retention policy region."""
    pass


class StalePolicyError(RuntimeError):
    """Raised when the live policy version does not match the committed version."""
    pass


@dataclass
class ContextState:
    policy_text: str
    payload: list[str]
    policy_version: int = 1
    tagged_items: set[int] = field(default_factory=set)


def policy_hash(state: ContextState) -> str:
    return hashlib.sha256(state.policy_text.encode()).hexdigest()[:16]


def prune_cycle(state: ContextState, summarizer, committed_version: int) -> ContextState:
    """
    Run one model-driven pruning cycle under the partition invariant.

    The summarizer receives ONLY the mutable payload. The policy region is
    never passed to the model and is re-attached verbatim afterward.
    """
    pre_hash = policy_hash(state)

    if state.policy_version != committed_version:
        raise StalePolicyError(
            f"live policy v{state.policy_version} != committed v{committed_version}; "
            "refusing to prune under an uncommitted retention law"
        )

    # Invariant: summarizer input span is exactly the payload.
    new_payload = summarizer(state.payload)

    # Re-attach policy verbatim; it must be byte-identical.
    post_state = ContextState(
        policy_text=state.policy_text,
        payload=new_payload,
        policy_version=state.policy_version,
        tagged_items=state.tagged_items,
    )
    if policy_hash(post_state) != pre_hash:
        raise PolicyContaminationError(
            "retention policy region was reachable by the summarizer; "
            "context is contaminated and must be rebuilt from last clean checkpoint"
        )

    # Compliance telemetry: tagged items must survive at expected rate.
    surviving = {i for i in state.tagged_items if i < len(new_payload)}
    retention_rate = len(surviving) / max(len(state.tagged_items), 1)
    if retention_rate < 0.95:
        raise PolicyContaminationError(
            f"tagged-item retention {retention_rate:.2f} below 0.95 floor; "
            "model pruned protected content under a live policy"
        )

    return post_state
