# 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-when-the-eviction-candidate-set-is-causally-upstream-of-an-unresolved-tool-c.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-a-context-window-when-the-eviction-candidate-set-is-causally-upstream-of-an-unresolved-tool-c.warrant.json
# Markdown SHA-256:   9bb45dfc94d849e60feb3d350d82d94b125d4a67bfa42a18be92dd79b1745ae7
# Code AST SHA-256:   bb984ae41c1d7821025c6e38c1792a216e9739a13adc4c9828fa89a881b6d3e6
# Verified Classes:   ObligationClosureOverflow, Obligation, ContextBudget
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ObligationClosureOverflow(RuntimeError):
    """Raised when pending obligations cannot survive a compaction pass intact."""
    pass


@dataclass(frozen=True)
class Obligation:
    call_id: str
    binding_tokens: FrozenSet[str]   # token ids that are the sole binding for this obligation
    resolved: bool = False


@dataclass
class ContextBudget:
    capacity: int
    obligations: list = field(default_factory=list)

    def closure_of_unresolved(self) -> FrozenSet[str]:
        pinned = set()
        for o in self.obligations:
            if not o.resolved:
                pinned |= o.binding_tokens
        return frozenset(pinned)

    def compact(self, eviction_candidates: FrozenSet[str]) -> FrozenSet[str]:
        """Return the actually-evictable set, or refuse if the closure cannot fit."""
        pinned = self.closure_of_unresolved()
        if len(pinned) > self.capacity:
            unresolved = [o.call_id for o in self.obligations if not o.resolved]
            raise ObligationClosureOverflow(
                f"pinned closure size {len(pinned)} exceeds capacity {self.capacity}; "
                f"unresolved obligations: {unresolved}. Refusing to compact — "
                f"serialize to durable store or halt."
            )
        illegal = eviction_candidates & pinned
        if illegal:
            # silently dropping these is the wrong-target-write bug; surface it instead
            raise ObligationClosureOverflow(
                f"eviction candidates intersect obligation closure: {sorted(illegal)}. "
                f"Compaction unsound; exempt these tokens from eviction."
            )
        return eviction_candidates - pinned
