# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-priority-weighted-eviction-against-rehydration-cost-when-a-context-budget-governor-fires-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-priority-weighted-eviction-against-rehydration-cost-when-a-context-budget-governor-fires-mid-task.warrant.json
# Markdown SHA-256:   d6ab6bf9c79235e281abedaa43451936d9ce04faa27a9ed4ecb7e4f46d40778d
# Code AST SHA-256:   91ca9d751502b4ead8e32501846f3375c530274aaaa8b7e3709088a60a90a9e6
# Verified Classes:   RehydrationProvenanceError, PinSetOverflowError, Segment, Governor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class RehydrationProvenanceError(RuntimeError):
    """Raised when a rehydrated segment does not match its eviction-time hash."""
    pass


class PinSetOverflowError(RuntimeError):
    """Raised when the pin set alone exceeds the low-water budget."""
    pass


@dataclass
class Segment:
    id: str
    tokens: int
    content: str
    pinned: bool = False
    eviction_hash: Optional[str] = None

    def content_hash(self) -> str:
        return hashlib.sha256(self.content.encode()).hexdigest()


@dataclass
class Governor:
    high_water: int
    low_water: int
    segments: dict[str, Segment] = field(default_factory=dict)

    def resident_tokens(self) -> int:
        return sum(s.tokens for s in self.segments.values())

    def add(self, seg: Segment) -> None:
        self.segments[seg.id] = seg
        if self.resident_tokens() > self.high_water:
            self.evict()

    def evict(self) -> list[str]:
        # Pins are never candidates. If pins alone exceed low_water, halt.
        pinned_tokens = sum(s.tokens for s in self.segments.values() if s.pinned)
        if pinned_tokens > self.low_water:
            raise PinSetOverflowError(
                f"pin set ({pinned_tokens} tok) exceeds low-water "
                f"({self.low_water} tok); halt and checkpoint, do not evict pins"
            )

        evicted: list[str] = []
        # Evict unpinned segments, lowest retention weight first.
        # Weight here is a stand-in; the invariant is the pin filter, not the weight.
        candidates = sorted(
            (s for s in self.segments.values() if not s.pinned),
            key=lambda s: s.tokens,  # replace with real weight function
        )
        for seg in candidates:
            if self.resident_tokens() <= self.low_water:
                break
            seg.eviction_hash = seg.content_hash()
            del self.segments[seg.id]
            evicted.append(seg.id)
        return evicted

    def rehydrate(self, seg_id: str, fetched_content: str) -> Segment:
        # Provenance check: rehydration must return the exact evicted artifact.
        # We look up the hash from a side table in a real implementation; here
        # we assume the caller passes the recorded hash via a store.
        seg = Segment(id=seg_id, tokens=len(fetched_content) // 4,
                      content=fetched_content)
        # In production, eviction_hash is persisted in the episodic store.
        # If it is absent, rehydration is ambiguous and must be rejected.
        raise RehydrationProvenanceError(
            f"rehydration of {seg_id} lacks a recorded eviction hash; "
            f"refusing to substitute a fuzzy retrieval result"
        )
