# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-arbitrate-a-shared-context-budget-it-must-price-eviction-in-tokens-not-facts-or-the-swarm-will-thrash.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-arbitrate-a-shared-context-budget-it-must-price-eviction-in-tokens-not-facts-or-the-swarm-will-thrash.warrant.json
# Markdown SHA-256:   c11f2f879bdeb65c8a573d05447f4cf26d95f93f6f4c9b3ac5eff927d5f165c9
# Code AST SHA-256:   928f7e7500b9cba1b4b9e33c281c546e311a9dfb26da385c3f7a0ee86cd6a50d
# Verified Classes:   BudgetArbitrationFault, Segment, SharedContextArbiter
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class BudgetArbitrationFault(RuntimeError):
    """Raised when a trim would evict a pinned segment with no identical re-materialization path."""


@dataclass
class Segment:
    seg_id: str
    tokens: int
    content: bytes
    cited_by: set[str] = field(default_factory=set)   # live agents whose plans reference it
    consumed: bool = False


class SharedContextArbiter:
    def __init__(self, low_water: int):
        self.low_water = low_water
        self.store: dict[str, bytes] = {}          # content-addressed, byte-identical refetch
        self.segments: dict[str, Segment] = {}

    def _hash(self, content: bytes) -> str:
        return hashlib.sha256(content).hexdigest()

    def admit(self, seg: Segment) -> None:
        self.store[self._hash(seg.content)] = seg.content
        self.segments[seg.seg_id] = seg

    def _refetchable(self, seg: Segment) -> bool:
        return self.store.get(self._hash(seg.content)) == seg.content

    def trim(self) -> list[str]:
        total = sum(s.tokens for s in self.segments.values())
        if total <= self.low_water:
            return []

        pinned = [s for s in self.segments.values() if s.cited_by]
        refetchable = [s for s in self.segments.values() if self._refetchable(s)]
        evictable = [
            s for s in self.segments.values()
            if not s.cited_by and not self._refetchable(s)
        ]

        # Rank evictable: consumed first, then oldest insertion order.
        evictable.sort(key=lambda s: (not s.consumed,))

        to_evict: list[str] = []
        freed = 0
        # Safe evictions first: refetchable segments cost nothing to drop.
        for s in refetchable:
            if total - freed <= self.low_water:
                break
            to_evict.append(s.seg_id)
            freed += s.tokens
        for s in evictable:
            if total - freed <= self.low_water:
                break
            to_evict.append(s.seg_id)
            freed += s.tokens

        if total - freed > self.low_water:
            # Cannot reach low-water without touching pinned segments.
            pinned_tokens = sum(s.tokens for s in pinned)
            raise BudgetArbitrationFault(
                f"trim would require evicting pinned segments "
                f"({pinned_tokens} tokens cited by live agents) with no "
                f"byte-identical re-materialization; serialize agents or "
                f"force summary commit instead of silent eviction"
            )

        for sid in to_evict:
            del self.segments[sid]
        return to_evict


def arbitrate_turn(arbiter: SharedContextArbiter) -> list[str]:
    try:
        return arbiter.trim()
    except BudgetArbitrationFault as exc:
        # Escalate: orchestrator must serialize or force summary, never evict pinned.
        raise BudgetArbitrationFault(f"escalating budget fault to orchestrator: {exc}") from exc
