# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-model-driven-context-pruning-when-the-eviction-scorer-and-the-retention-invariant-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-model-driven-context-pruning-when-the-eviction-scorer-and-the-retention-invariant-disagree.warrant.json
# Markdown SHA-256:   935ee982dd6fafbda37b3791f04eb943ef84ef5b0088110af2f50b4c2ae78662
# Code AST SHA-256:   26e280856d9c6a1c9acbe75c225a9b293ee0bc9588161789a789f3610f7f281f
# Verified Classes:   PruneArbitrationError, Obligation, Segment, PruneDirective, ArbitrationResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class PruneArbitrationError(RuntimeError):
    """Raised when a prune directive cannot be safely arbitrated."""


class Obligation(str, Enum):
    OPEN = "open"
    CLOSED = "closed"
    NONE = "none"


@dataclass
class Segment:
    seg_id: str
    tokens: int
    relevance: float
    obligation: Obligation = Obligation.NONE
    provenance_anchor: bool = False


@dataclass
class PruneDirective:
    evict: list[str]
    target_tokens: int


@dataclass
class ArbitrationResult:
    accepted: list[str] = field(default_factory=list)
    quarantined: list[str] = field(default_factory=list)
    rejected: list[str] = field(default_factory=list)
    denial_reasons: dict[str, str] = field(default_factory=dict)


def arbitrate(
    context: dict[str, Segment],
    directive: PruneDirective,
    current_tokens: int,
    max_reject_fraction: float = 0.5,
) -> ArbitrationResult:
    """
    Enforce the ordering invariant: evictability is a predicate over
    obligations; relevance only orders the survivors. Never sort-then-truncate.
    """
    result = ArbitrationResult()

    for seg_id in directive.evict:
        seg = context.get(seg_id)
        if seg is None:
            raise PruneArbitrationError(
                f"directive references unknown segment {seg_id!r}"
            )

        if seg.obligation is Obligation.OPEN:
            result.rejected.append(seg_id)
            result.denial_reasons[seg_id] = (
                "open obligation: segment carries a pending handle, "
                "transaction, warrant, or unacknowledged constraint"
            )
            continue

        if seg.provenance_anchor:
            result.rejected.append(seg_id)
            result.denial_reasons[seg_id] = (
                "provenance anchor: sole carrier of a value the plan "
                "will re-emit; eviction converts recall into hallucination"
            )
            continue

        if seg.obligation is Obligation.CLOSED:
            # Permitted, but closure must be durable before eviction.
            result.quarantined.append(seg_id)
            result.denial_reasons[seg_id] = (
                "closed obligation: eviction allowed only after closure "
                "is written to the side-ledger"
            )
            continue

        result.accepted.append(seg_id)

    projected = current_tokens - sum(
        context[s].tokens for s in result.accepted
    )
    if projected > directive.target_tokens:
        if len(result.rejected) > max_reject_fraction * len(directive.evict):
            raise PruneArbitrationError(
                "token target unreachable without violating retention "
                "invariants; replan instead of evicting further"
            )

    return result


def apply_prune(
    context: dict[str, Segment],
    directive: PruneDirective,
    current_tokens: int,
) -> tuple[dict[str, Segment], ArbitrationResult]:
    result = arbitrate(context, directive, current_tokens)
    if any(s not in context for s in result.accepted):
        raise PruneArbitrationError("arbitration produced a non-existent segment")
    new_context = {k: v for k, v in context.items() if k not in result.accepted}
    return new_context, result
