# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-model-driven-context-prune-because-the-eviction-policy-and-the-reasoning-loop-disagree-about-what-is-load-bearing.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-model-driven-context-prune-because-the-eviction-policy-and-the-reasoning-loop-disagree-about-what-is-load-bearing.warrant.json
# Markdown SHA-256:   ee26cbc1c3d61d4ee7df1cc5376b012572f1c26e4fb26be9e3ff1becd5c2928e
# Code AST SHA-256:   62f0ee4bb97fcf6cb4436ddf0da6fbe4dd14c908f57078daaba4e652ccff165c
# Verified Classes:   ContextPruneRefused, Segment, Obligation, ContextLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ContextPruneRefused(RuntimeError):
    """Raised when a model-proposed eviction set would delete a segment
    referenced by an open derivation obligation."""
    pass


@dataclass
class Segment:
    seg_id: str
    text: str
    score: float          # relevance score assigned by the model
    derived: bool = False  # True if this is a lossy self-authored summary


@dataclass
class Obligation:
    ob_id: str
    depends_on: Set[str]   # segment IDs that warrant this obligation
    open: bool = True


@dataclass
class ContextLedger:
    segments: Dict[str, Segment] = field(default_factory=dict)
    obligations: Dict[str, Obligation] = field(default_factory=dict)

    def open_dependency_union(self) -> Set[str]:
        deps: Set[str] = set()
        for ob in self.obligations.values():
            if ob.open:
                deps |= ob.depends_on
        return deps


def apply_model_prune(ledger: ContextLedger, proposed_evict: List[str],
                      active_obligations: Set[str]) -> List[str]:
    """Two-phase prune. Phase 1: propose. Phase 2: check against open
    obligations. Returns the actually-evicted IDs, or raises if the
    proposal touches an actively-reasoned obligation."""
    referenced = ledger.open_dependency_union()

    # Hard refusal: eviction set intersects obligations the current turn
    # is actively deriving over.
    active_deps: Set[str] = set()
    for ob_id in active_obligations:
        ob = ledger.obligations.get(ob_id)
        if ob and ob.open:
            active_deps |= ob.depends_on

    collision = set(proposed_evict) & active_deps
    if collision:
        raise ContextPruneRefused(
            f"eviction set {sorted(collision)} is load-bearing for active "
            f"obligations {sorted(active_obligations)}; aborting prune"
        )

    # Soft filter: drop any referenced segment from the proposal; it may be
    # rewritten in place but not deleted. Derived summaries are never
    # warrants and are freely evictable.
    evicted: List[str] = []
    for seg_id in proposed_evict:
        seg = ledger.segments.get(seg_id)
        if seg is None:
            continue
        if seg_id in referenced and not seg.derived:
            # retain; caller must discharge the obligation before retrying
            continue
        evicted.append(seg_id)
        ledger.segments.pop(seg_id, None)

    return evicted


def discharge_or_downgrade(ledger: ContextLedger, ob_id: str,
                           surviving_evidence: Set[str]) -> bool:
    """Attempt to discharge an obligation against surviving segments.
    If evidence is insufficient, downgrade the conclusion to unverified
    rather than silently keeping it."""
    ob = ledger.obligations.get(ob_id)
    if ob is None:
        raise ContextPruneRefused(f"unknown obligation {ob_id}")
    if ob.depends_on <= surviving_evidence:
        ob.open = False
        return True
    # Evidence lost: mark unverified, do not assert.
    ob.open = False
    return False
