# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-evict-the-pinned-span-invariant-in-hierarchical-context-budget-governors.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-evict-the-pinned-span-invariant-in-hierarchical-context-budget-governors.warrant.json
# Markdown SHA-256:   47b3417806c34cf91a44c192164d2302b3e891a22d9a410785636318b54cf8b9
# Code AST SHA-256:   2fa0c9d8d475f24d548042c26b52489ecc90b4e93fc72531f0b4e4e1599db0af
# Verified Classes:   DanglingReferenceError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class DanglingReferenceError(RuntimeError):
    """Raised when eviction would orphan a live reference in the surviving window."""
    pass


@dataclass
class Span:
    span_id: str
    tokens: int
    pinned: bool = False
    referents: set[str] = field(default_factory=set)  # span_ids this span depends on


def evict_to_ceiling(spans: list[Span], ceiling: int) -> tuple[list[Span], list[Span]]:
    """
    Return (surviving, evicted). Enforces reference-closed eviction:
    a span may be evicted only if no surviving span depends on it.
    Pinned spans are never evictable. Raises on irreconcilable budget.
    """
    total = sum(s.tokens for s in spans)
    if total <= ceiling:
        return spans, []

    # Candidates: unpinned, in ascending token cost (cheapest reclaim first).
    evictable = sorted((s for s in spans if not s.pinned), key=lambda s: s.tokens)
    evicted: list[Span] = []
    reclaimed = 0
    evicted_ids: set[str] = set()

    for cand in evictable:
        if total - reclaimed <= ceiling:
            break
        # Reference-closure check: cannot evict a span still referenced
        # by any span that will survive (i.e., not itself evicted).
        survivors = [s for s in spans if s.span_id not in evicted_ids and s.span_id != cand.span_id]
        if any(cand.span_id in s.referents for s in survivors):
            continue  # dangling reference risk: skip, do not evict
        evicted.append(cand)
        evicted_ids.add(cand.span_id)
        reclaimed += cand.tokens

    if total - reclaimed > ceiling:
        pinned_tokens = sum(s.tokens for s in spans if s.pinned)
        raise DanglingReferenceError(
            f"cannot reach ceiling {ceiling}: reclaimed {reclaimed}, "
            f"pinned {pinned_tokens} tokens are non-evictable; "
            f"compress referrers or decompose task, do not drop pinned spans"
        )

    surviving = [s for s in spans if s.span_id not in evicted_ids]
    return surviving, evicted
