# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-prune-its-own-context-when-the-pruning-policy-is-co-resident-with-the-data-it-prunes.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-prune-its-own-context-when-the-pruning-policy-is-co-resident-with-the-data-it-prunes.warrant.json
# Markdown SHA-256:   7584c13e8b550bda0b466258719c0c67ed2f87bb673bc0474dde4e74dffd2e5a
# Code AST SHA-256:   faadcb04edcecbd861c3a7537621cf3e1ee32ff630319afabbdfefb72afbb8bb
# Verified Classes:   PolicyEvictionError, ContextRewriter
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PolicyEvictionError(RuntimeError):
    """Raised when a context rewrite would evict or mutate a protected policy span."""
    pass


class ContextRewriter:
    def __init__(self, protected_span_ids: frozenset[str]):
        # Protected set is fixed by the harness, never derived from buffer contents.
        self._protected = protected_span_ids

    def commit(self, buffer: dict[str, str], proposed_retained: set[str]) -> dict[str, str]:
        # Invariant: committed = (proposed ∩ protected) ∪ protected.
        # A proposal that drops a protected span is rejected, not silently repaired.
        missing = self._protected - proposed_retained
        if missing:
            raise PolicyEvictionError(
                f"rewrite proposed evicting protected policy spans: {sorted(missing)}; "
                f"refusing to commit — policy partition is a floor, not a candidate"
            )
        # Also reject any attempt to rewrite (not just drop) a protected span.
        for sid in self._protected:
            if sid not in buffer:
                raise PolicyEvictionError(
                    f"protected span {sid!r} absent from buffer at commit — "
                    f"partition boundary violated upstream"
                )
        retained = (proposed_retained & set(buffer)) | self._protected
        return {sid: buffer[sid] for sid in retained}


def rewrite_under_budget(
    rewriter: ContextRewriter,
    buffer: dict[str, str],
    proposed_retained: set[str],
    token_count,
    budget: int,
) -> dict[str, str]:
    committed = rewriter.commit(buffer, proposed_retained)
    if token_count(committed) > budget:
        # Fail closed: do not compress policy to fit. Spill payload externally.
        raise PolicyEvictionError(
            f"payload exceeds budget ({token_count(committed)} > {budget}) after maximal "
            f"pruning; spill to external store and re-retrieve — do not compress policy"
        )
    return committed
