# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-quota-driven-compaction-eviction-that-silently-drops-the-active-tool-call-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-quota-driven-compaction-eviction-that-silently-drops-the-active-tool-call-warrant.warrant.json
# Markdown SHA-256:   8e3ce49b50510b015e098a37ab4248124ef31e0b123f727d2586a11c12fd906a
# Code AST SHA-256:   e1171c569cdb0dbde021564ab3ecc8aac4daa0e16667d5465a99b6620bafe16e
# Verified Classes:   WarrantEvictionError, Warrant, ToolResult, ContextState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class WarrantEvictionError(RuntimeError):
    """Raised when a tool result cannot be bound to a surviving warrant,
    indicating quota-driven compaction evicted the invocation contract."""
    pass


@dataclass
class Warrant:
    call_id: str
    schema_ref: str
    args_hash: str
    authorization_scope: str
    pinned: bool = True


@dataclass
class ToolResult:
    call_id: str
    payload: dict


@dataclass
class ContextState:
    warrants: dict = field(default_factory=dict)          # call_id -> Warrant
    evicted_turn_ranges: list = field(default_factory=list)
    token_quota: int = 96_000
    tokens_used: int = 0


def compact(state: ContextState, reclaim_target: int) -> None:
    """Simulate an eviction pass. Pinned warrants are reserved first;
    if reservation alone exceeds reclaimable budget, we must refuse to
    evict warrants and escalate instead of silently dropping them."""
    pinned_cost = sum(1 for _ in state.warrants.values()) * 40  # rough token cost
    reclaimable = state.token_quota - state.tokens_used
    if pinned_cost > reclaimable - reclaim_target:
        # Budget cannot accommodate pinned warrants + reclaim target.
        # Correct behavior: escalate to checkpoint-and-restart, do NOT evict warrants.
        raise WarrantEvictionError(
            f"pinned warrant cost {pinned_cost} exceeds reclaimable budget "
            f"{reclaimable - reclaim_target}; refusing quota-driven warrant eviction"
        )
    # Narrative spans evicted here; warrants retained verbatim.
    state.evicted_turn_ranges.append((1, 20))
    state.tokens_used -= reclaim_target


def ingest_result(state: ContextState, result: ToolResult) -> dict:
    """A tool result must bind to a surviving warrant before entering working state."""
    warrant: Optional[Warrant] = state.warrants.get(result.call_id)
    if warrant is None:
        # Distinguish compaction-induced loss from benign protocol fault.
        if state.evicted_turn_ranges:
            raise WarrantEvictionError(
                f"result call_id={result.call_id} unresolvable after eviction of "
                f"turn ranges {state.evicted_turn_ranges}; context corrupted by "
                f"quota-driven compaction, not a benign missing record"
            )
        raise WarrantEvictionError(
            f"result call_id={result.call_id} has no warrant and no eviction recorded; "
            f"treat as protocol fault, do not merge result"
        )
    if warrant.schema_ref != result.payload.get("_schema_ref", warrant.schema_ref):
        raise WarrantEvictionError(
            f"schema mismatch for call_id={result.call_id}: "
            f"warrant={warrant.schema_ref} result={result.payload.get('_schema_ref')}"
        )
    return result.payload


# Trigger trace: quota pressure forces compaction, warrant is pinned-or-escalate,
# and any unresolvable result halts the loop instead of poisoning state.
state = ContextState()
state.warrants["c-27"] = Warrant("c-27", "search.v3", "abc123", "read:web")
state.tokens_used = 90_000

compact(state, reclaim_target=8_000)  # may raise if pinned cost too high
ingest_result(state, ToolResult("c-27", {"_schema_ref": "search.v3", "data": "ok"}))
