# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-pruning-to-preserve-the-rewrite-integrity-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-pruning-to-preserve-the-rewrite-integrity-invariant.warrant.json
# Markdown SHA-256:   f72195ce02da358ed7083a6ce22212feb5d8b841aa600a3703b026fe75c5cef8
# Code AST SHA-256:   44b0f100b3a06346ce99c87d198620f8b266e216493e86cbd823df2960342922
# Verified Classes:   RewriteIntegrityError, Span, RewritePolicy
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class RewriteIntegrityError(RuntimeError):
    """Raised when a model-driven prune/rewrite would violate the
    rewrite-integrity invariant (unaccounted eviction)."""


@dataclass(frozen=True)
class Span:
    span_id: str
    generation: int          # 0 = original content
    is_tombstone: bool = False
    is_constraint: bool = False


@dataclass
class RewritePolicy:
    evict: frozenset[str]
    justification_spans: frozenset[str] = field(default_factory=frozenset)
    recompress: frozenset[str] = field(default_factory=frozenset)


MAX_GENERATION = 3


def validate_rewrite(
    window: Iterable[Span],
    policy: RewritePolicy,
    *,
    tombstones_immutable: bool = True,
) -> None:
    """Pre-commit check. Raises RewriteIntegrityError on any unaccounted eviction.

    Must be called BEFORE the window is mutated, and the tombstone write must
    commit atomically with the eviction.
    """
    by_id = {s.span_id: s for s in window}

    # 1. Tombstones are outside the selectable set. A policy that can evict
    #    its own audit records has no audit records.
    if tombstones_immutable:
        for sid in policy.evict | policy.recompress:
            span = by_id.get(sid)
            if span is not None and span.is_tombstone:
                raise RewriteIntegrityError(
                    f"policy targets tombstone {sid!r}; audit trail is not selectable"
                )

    # 2. Non-self-justifying eviction: the grounds for evicting S must not
    #    live inside S. Otherwise the post-rewrite window cannot verify itself.
    for sid in policy.evict:
        if sid in policy.justification_spans:
            raise RewriteIntegrityError(
                f"eviction of {sid!r} is justified by content inside {sid!r}; "
                "self-ratifying eviction refused"
            )

    # 3. Constraints may not be silently dropped; they must be re-anchored
    #    into a non-evictable region first.
    for sid in policy.evict:
        span = by_id.get(sid)
        if span is not None and span.is_constraint:
            raise RewriteIntegrityError(
                f"active constraint {sid!r} selected for eviction; "
                "re-anchor into non-evictable region before commit"
            )

    # 4. Generation ceiling: prune-of-a-prune must not silently re-compress.
    for sid in policy.recompress:
        span = by_id.get(sid)
        if span is None:
            raise RewriteIntegrityError(f"recompress targets unknown span {sid!r}")
        if span.generation + 1 > MAX_GENERATION:
            raise RewriteIntegrityError(
                f"recompress of {sid!r} would reach generation "
                f"{span.generation + 1} > {MAX_GENERATION}; checkpoint required"
            )
