# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-budget-context-by-downstream-tool-call-risk-rather-than-by-token-count-alone.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-budget-context-by-downstream-tool-call-risk-rather-than-by-token-count-alone.warrant.json
# Markdown SHA-256:   c843c844dcefbb65947d419d2997fe0e91910975977af130551d9817e2b1daaa
# Code AST SHA-256:   7655471ce586d8f22c3f5b81715f7f86e18fd69363407d52db2721e9364adb9f
# Verified Classes:   ConstraintEvictedError, Span, PlannedCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ConstraintEvictedError(RuntimeError):
    """Raised when a pending irreversible tool call's constraining context
    span is no longer resident and has not been replaced by a pinned record."""


@dataclass
class Span:
    span_id: str
    tokens: int
    resident: bool = True


@dataclass
class PlannedCall:
    step: int
    irreversible: bool
    constrains: list[str] = field(default_factory=list)
    executed: bool = False


def pinned_span_ids(plan: list[PlannedCall]) -> set[str]:
    pinned: set[str] = set()
    for call in plan:
        if not call.executed and call.irreversible:
            pinned.update(call.constrains)
    return pinned


def evict_to_budget(spans: list[Span], plan: list[PlannedCall], budget: int) -> list[Span]:
    pinned = pinned_span_ids(plan)
    total = sum(s.tokens for s in spans if s.resident)
    # Evict non-pinned, oldest-first, until within budget.
    for span in spans:
        if total <= budget:
            break
        if span.resident and span.span_id not in pinned:
            span.resident = False
            total -= span.tokens
    if total > budget:
        # Pinned set alone exceeds budget: externalize, never silently drop.
        raise ConstraintEvictedError(
            f"pinned constraint set requires {total} tokens > budget {budget}; "
            f"externalize pinned spans {sorted(pinned)} before proceeding"
        )
    return spans


def dispatch(call: PlannedCall, spans: list[Span]) -> None:
    resident = {s.span_id for s in spans if s.resident}
    missing = [sid for sid in call.constrains if sid not in resident]
    if call.irreversible and missing:
        raise ConstraintEvictedError(
            f"step {call.step} irreversible call missing constraining spans {missing}; "
            f"re-plan or re-fetch before dispatch"
        )
    call.executed = True
