# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-evicts-a-tool-schema-block-mid-turn-under-a-hard-token-budget-the-schema-orphan-compaction-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-evicts-a-tool-schema-block-mid-turn-under-a-hard-token-budget-the-schema-orphan-compaction-failure.warrant.json
# Markdown SHA-256:   0b63732c232a216659c51bd731de2d8590b6cc9e8b3fb1ee1678ebb0b3a6ba75
# Code AST SHA-256:   27923c7c87ca0eb725ef45e0c6a6f46bfa06d199237ae95eb779b68f11990aa1
# Verified Classes:   SchemaOrphanError, UncorrectableRetryError, Block, BudgetManager, Dispatch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SchemaOrphanError(RuntimeError):
    """Raised when eviction would orphan a tool schema still referenced by a retained turn."""
    pass


class UncorrectableRetryError(RuntimeError):
    """Raised when the agent retries a schema-mismatched call without schema re-injection."""
    pass


@dataclass
class Block:
    kind: str          # "system" | "task_state" | "preamble" | "schema" | "message" | "observation"
    name: str
    tokens: int
    priority: int      # higher = evicted later
    refs: set = field(default_factory=set)  # tool names this block references


class BudgetManager:
    def __init__(self, budget: int):
        self.budget = budget
        self.blocks: list[Block] = []

    def used(self) -> int:
        return sum(b.tokens for b in self.blocks)

    def _referenced_schemas(self) -> set:
        # Schemas still needed by any retained message/observation.
        needed = set()
        for b in self.blocks:
            if b.kind in ("message", "observation"):
                needed |= b.refs
        return needed

    def evict_to_fit(self, incoming_tokens: int) -> None:
        pinned = self._referenced_schemas()
        while self.used() + incoming_tokens > self.budget:
            # Candidate eviction: lowest priority, but never a pinned schema.
            candidates = [
                b for b in self.blocks
                if b.kind != "system"
                and not (b.kind == "schema" and b.name in pinned)
            ]
            if not candidates:
                raise SchemaOrphanError(
                    f"Cannot free {incoming_tokens} tokens without orphaning "
                    f"pinned schemas {sorted(pinned)}; evict invoking turns instead."
                )
            victim = min(candidates, key=lambda b: b.priority)
            # Guard: refuse to evict a schema referenced by a surviving turn.
            if victim.kind == "schema" and victim.name in pinned:
                raise SchemaOrphanError(
                    f"Eviction of schema '{victim.name}' would orphan a retained call."
                )
            self.blocks.remove(victim)


class Dispatch:
    def __init__(self, registry: dict):
        self.registry = registry
        self.mismatch_count = 0
        self.schema_reinjected = False

    def validate(self, tool: str, args: dict) -> None:
        schema = self.registry[tool]
        if set(args.keys()) != set(schema["required"]):
            self.mismatch_count += 1
            if not self.schema_reinjected:
                raise SchemaOrphanError(
                    f"Call to '{tool}' mismatches live schema {schema['required']}; "
                    f"re-inject authoritative schema before retry."
                )
            if self.mismatch_count >= 2:
                raise UncorrectableRetryError(
                    f"Repeated schema-mismatched retry for '{tool}' after re-injection; halting."
                )
        self.mismatch_count = 0
        self.schema_reinjected = False
