# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-a-context-window-whose-only-reclaimable-tokens-are-the-provenance-chain-of-its-own-prior-comp.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-a-context-window-whose-only-reclaimable-tokens-are-the-provenance-chain-of-its-own-prior-comp.warrant.json
# Markdown SHA-256:   fe6b31301294ca51d74d575a509b2af8c95e31a17a40563036f2ca5ccce1d87a
# Code AST SHA-256:   4c8f6dc152a743d5f0e405ee58fc722db1eff90302bbc27de27ea8a532739d9e
# Verified Classes:   ProvenanceCompactionRefused, Span, Context
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceCompactionRefused(RuntimeError):
    """Raised when the only reclaimable tokens are provenance for retained claims."""


@dataclass(frozen=True)
class Span:
    span_id: str
    tokens: int
    is_provenance: bool
    covers_claims: FrozenSet[str] = field(default_factory=frozenset)


@dataclass
class Context:
    retained_claims: FrozenSet[str]
    live_provenance: FrozenSet[str]  # claim ids still linked to a source
    spans: list


def attribution_coverage(ctx: Context, evicted: FrozenSet[str]) -> float:
    if not ctx.retained_claims:
        return 1.0
    surviving = ctx.live_provenance - {
        c for s in ctx.spans if s.span_id in evicted for c in s.covers_claims
    }
    return len(surviving & ctx.retained_claims) / len(ctx.retained_claims)


def select_eviction(ctx: Context, pressure_tokens: int) -> FrozenSet[str]:
    """Greedy by token cost, then guard attribution coverage."""
    ranked = sorted(ctx.spans, key=lambda s: (s.is_provenance, -s.tokens))
    chosen, freed = set(), 0
    for span in ranked:
        if freed >= pressure_tokens:
            break
        chosen.add(span.span_id)
        freed += span.tokens
    if attribution_coverage(ctx, frozenset(chosen)) < 1.0:
        provenance_only = all(
            s.is_provenance for s in ctx.spans if s.span_id in chosen
        )
        if provenance_only:
            raise ProvenanceCompactionRefused(
                f"eviction set {sorted(chosen)} would drop attribution coverage "
                f"to {attribution_coverage(ctx, frozenset(chosen)):.2f}; "
                f"refusing to compact provenance of retained claims"
            )
    return frozenset(chosen)
