# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-pruning-when-relevance-scored-eviction-deletes-the-antecedent-that-licenses-a-later-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-pruning-when-relevance-scored-eviction-deletes-the-antecedent-that-licenses-a-later-tool-call.warrant.json
# Markdown SHA-256:   d0639ae9ba98d5736e3ad6a422e82a50e3e77e4f18f55875d041a16b664309a1
# Code AST SHA-256:   30b2d75b0cd3baa5834cc4abd5047f65dfca06e2b655397264cf22f6ac441fed
# Verified Classes:   UnboundArgumentError, Span, Context
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnboundArgumentError(RuntimeError):
    """Raised when a tool call emits an argument with no surviving context binding."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    binds: set[str] = field(default_factory=set)  # argument slots this span grounds


@dataclass
class Context:
    retained: list[Span] = field(default_factory=list)
    evicted: dict[str, Span] = field(default_factory=dict)  # recoverable store

    def bindings_for(self, slot: str) -> Optional[Span]:
        for span in self.retained:
            if slot in span.binds:
                return span
        return None


def prune(ctx: Context, reachable_slots: set[str], relevance: dict[str, float],
          threshold: float) -> Context:
    """Dependency-preserving eviction: pin antecedents, score only the residual."""
    pinned, residual = [], []
    for span in ctx.retained:
        if span.binds & reachable_slots:
            pinned.append(span)          # antecedent: survive regardless of score
        else:
            residual.append(span)
    survivors = pinned + [s for s in residual if relevance.get(s.span_id, 0.0) >= threshold]
    evicted = {s.span_id: s for s in ctx.retained if s not in survivors}
    return Context(retained=survivors, evicted={**ctx.evicted, **evicted})


def emit_tool_call(ctx: Context, tool: str, args: dict[str, str],
                   required_slots: dict[str, set[str]]) -> dict[str, str]:
    """Reject any argument whose slot lacks a surviving binding."""
    for slot in required_slots.get(tool, set()):
        if slot not in args:
            continue
        if ctx.bindings_for(slot) is None:
            # Backstop: recoverable store may still hold it; if not, hard fail.
            recovered = next(
                (s for s in ctx.evicted.values() if slot in s.binds), None
            )
            if recovered is None:
                raise UnboundArgumentError(
                    f"tool={tool} slot={slot!r} value={args[slot]!r} has no surviving "
                    f"or recoverable binding; refusing to emit fabricated argument"
                )
            # Recoverable: re-pin and proceed, never emit blind.
            ctx.retained.append(recovered)
    return args


# Reproduction of the observed failure, now bounded:
ctx = Context(retained=[
    Span("s1", "PO-4417 currency=EUR status=superseded_by PO-4417-R2",
         binds={"currency", "po_target"}),
    Span("s2", "line items for PO-4417", binds={"line_items"}),
])
# Pruner scores s1 low against 'compute totals' and would evict it:
ctx = prune(ctx, reachable_slots={"currency", "po_target"},
            relevance={"s1": 0.05, "s2": 0.91}, threshold=0.3)
assert ctx.bindings_for("currency") is not None  # pinned as antecedent

# If a buggy pruner had dropped s1 entirely, the emit boundary catches it:
broken = Context(retained=[Span("s2", "line items", binds={"line_items"})])
emit_tool_call(broken, "post_adjustment", {"currency": "USD"},
               required_slots={"post_adjustment": {"currency", "po_target"}})
