# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-arbitrate-context-budget-across-concurrent-subagents-rather-than-rely-on-per-agent-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-arbitrate-context-budget-across-concurrent-subagents-rather-than-rely-on-per-agent-eviction.warrant.json
# Markdown SHA-256:   b6ab3a3ee6835c9c21390501810adb4419172d3ffbaa5532f32aff64916f438e
# Code AST SHA-256:   eaabecfef0ccbe8b34b4321b38297281c6aa24eb01fce1f860f61dd5b3ec5b50
# Verified Classes:   ContextArbitrationError, ReservationLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ContextArbitrationError(RuntimeError):
    """Raised when eviction would violate cross-agent referential integrity."""


@dataclass
class ReservationLedger:
    pinned: Set[str] = field(default_factory=set)
    cited_by: Dict[str, Set[str]] = field(default_factory=dict)

    def cite(self, item_id: str, agent_id: str) -> None:
        self.cited_by.setdefault(item_id, set()).add(agent_id)
        if len(self.cited_by[item_id]) > 1:
            # Item is now referenced by more than one agent: must be pinned.
            self.pinned.add(item_id)

    def request_eviction(self, item_id: str, requesting_agent: str) -> None:
        if item_id in self.pinned:
            raise ContextArbitrationError(
                f"agent {requesting_agent} attempted to evict pinned item "
                f"{item_id} cited by {sorted(self.cited_by[item_id])}; "
                f"cross-agent arbitration required, local eviction refused"
            )


def evict_under_arbitration(
    ledger: ReservationLedger, item_id: str, agent_id: str
) -> None:
    # Central arbitration path: never trust per-agent recency alone.
    ledger.request_eviction(item_id, agent_id)
    # Safe to evict: no other agent references this item.
    ledger.cited_by.pop(item_id, None)
