# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-has-entered-rewrite-divergence-during-budget-constrained-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-has-entered-rewrite-divergence-during-budget-constrained-eviction.warrant.json
# Markdown SHA-256:   4f7c81fed7b792313825a37e5c02c23c19593641c134aad575fb7241ad321f91
# Code AST SHA-256:   d58231f48a6c51641a52f52a185469af6e040e5b17622fd9aeec8374c5f3cf3c
# Verified Classes:   RewriteDivergenceError, Artifact, ProvenanceBudget
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class RewriteDivergenceError(RuntimeError):
    """Raised when a model-driven rewrite increases provenance depth
    without increasing anchor count, i.e. the context is compressing
    its own paraphrase instead of its ground-truth spans."""


@dataclass
class Artifact:
    tokens: int
    anchors: frozenset  # ids of distinct raw spans this traces to
    depth: int = 1      # 1 = raw span, >1 = rewrite of rewrites

    @property
    def anchor_density(self) -> float:
        return len(self.anchors) / max(self.tokens, 1)


@dataclass
class ProvenanceBudget:
    max_rewrite_depth: int = 2
    min_window_anchors: int = 5
    _window: list = field(default_factory=list)

    def admit(self, art: Artifact) -> None:
        self._window.append(art)

    def rewrite(self, inputs: list, new_tokens: int) -> Artifact:
        depth = max(a.depth for a in inputs) + 1
        anchors = frozenset().union(*(a.anchors for a in inputs))
        out = Artifact(tokens=new_tokens, anchors=anchors, depth=depth)

        if depth > self.max_rewrite_depth:
            raise RewriteDivergenceError(
                f"rewrite depth {depth} exceeds cap {self.max_rewrite_depth}; "
                f"drop derivative artifacts instead of re-summarizing"
            )

        consumed_density = sum(len(a.anchors) for a in inputs) / max(
            sum(a.tokens for a in inputs), 1
        )
        if out.anchor_density < consumed_density:
            raise RewriteDivergenceError(
                f"anchor density fell {consumed_density:.4f} -> "
                f"{out.anchor_density:.4f}: rewrite diluted provenance, "
                f"re-anchor from raw store instead"
            )

        self.admit(out)
        return out

    def window_anchors(self) -> int:
        return len(frozenset().union(*(a.anchors for a in self._window)))

    def check_reanchor(self) -> None:
        if self.window_anchors() < self.min_window_anchors:
            raise RewriteDivergenceError(
                f"window anchors {self.window_anchors()} below floor "
                f"{self.min_window_anchors}: force re-fetch of raw spans"
            )


def evict_pass(budget: ProvenanceBudget, stale: list) -> Artifact:
    """Run one model-driven summarize pass, guarded by provenance budget."""
    if any(a.depth > 1 for a in stale) and all(a.depth > 1 for a in stale):
        # all inputs are already derivative -> dropping is honest, rewriting is not
        raise RewriteDivergenceError(
            "all eviction candidates are derivative; drop rather than rewrite"
        )
    summary = budget.rewrite(stale, new_tokens=400)
    budget.check_reanchor()
    return summary
