# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-arbitrate-a-context-budget-when-tool-schemas-and-recalled-memory-compete-for-the-same-token-reserve.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-arbitrate-a-context-budget-when-tool-schemas-and-recalled-memory-compete-for-the-same-token-reserve.warrant.json
# Markdown SHA-256:   e6f25d6f3cfdae7d315aa2c7ebc70b828ef96fff1f1f6a0fac5001d6e17b0842
# Code AST SHA-256:   d817f06bd438bcff500c2632da7bbdf8ef27cfcb8b6f6f6e4958016f6173e7c8
# Verified Classes:   BindingEvictionError, ToolManifest, BudgetPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class BindingEvictionError(RuntimeError):
    """Raised when a budget plan would leave a callable tool without the
    memory-resident bindings its arguments require."""
    pass


@dataclass
class ToolManifest:
    name: str
    schema_tokens: int
    requires_binding: Set[str] = field(default_factory=set)


@dataclass
class BudgetPlan:
    memory_keys: Set[str]
    active_tools: Set[str]
    memory_tokens: int
    schema_tokens: int


def couple_arbitration(
    memory: Dict[str, int],          # key -> token cost
    tools: Dict[str, ToolManifest],
    memory_budget: int,
    schema_budget: int,
) -> BudgetPlan:
    # Start from full admission, then trim memory to budget.
    admitted_keys = set(memory)
    admitted_tools = set(tools)

    while sum(memory[k] for k in admitted_keys) > memory_budget:
        # Evict the most expensive non-required key first.
        required = set()
        for t in admitted_tools:
            required |= tools[t].requires_binding
        candidates = [k for k in admitted_keys if k not in required]
        if not candidates:
            break
        victim = max(candidates, key=lambda k: memory[k])
        admitted_keys.discard(victim)

    # Enforce coupling: no active tool may reference an evicted binding.
    for t in list(admitted_tools):
        missing = tools[t].requires_binding - admitted_keys
        if missing:
            admitted_tools.discard(t)

    schema_tokens = sum(tools[t].schema_tokens for t in admitted_tools)
    if schema_tokens > schema_budget:
        # Schema set itself over budget: drop tools until it fits, then
        # re-run the binding check because dropping a tool may free a
        # required key for another.
        raise BindingEvictionError(
            f"schema set {sorted(admitted_tools)} costs {schema_tokens} > "
            f"budget {schema_budget}; cannot finalize plan without "
            f"re-arbitrating bindings"
        )

    mem_tokens = sum(memory[k] for k in admitted_keys)
    return BudgetPlan(admitted_keys, admitted_tools, mem_tokens, schema_tokens)


def guarded_call(plan: BudgetPlan, tool: str, args: Dict[str, str]) -> None:
    if tool not in plan.active_tools:
        raise BindingEvictionError(
            f"tool {tool!r} not active this turn; bindings for its "
            f"arguments were evicted or schema dropped"
        )
    # ... dispatch ...
